django 提供内置view处理登陆和退出。
查看django.contrib.auth源码,主要查看三个函数authenticate,login,logout。
authenticate(request=None, **credentials)
它接受两个参数,用户名 username 和 密码 password ,并在密码对给出的用户名合法的情况下返回一个 User 对象。 如果密码不合法,authenticate()返回None。
login(request, user, backend=None)
登录,本质在session表中创建session_id and session_data
举个栗子
from django.contrib import auth
def login_view(request):
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = auth.authenticate(username=username, password=password)
if user is not None and user.is_active:
# Correct password, and the user is marked "active"
auth.login(request, user)
# Redirect to a success page.
return HttpResponseRedirect("/account/loggedin/")
else:
# Show an error page
return HttpResponseRedirect("/account/invalid/")
logout
即使用户没有登录, logout() 也不会抛出任何异常
from django.contrib import auth
def logout_view(request):
auth.logout(request)
# Redirect to a success page.
return HttpResponseRedirect("/account/loggedout/")
让我们继续深入django内置的password生成和验证机制是怎么样的,
查看如下源码
from django.contrib.auth.hashers import make_password
from django.contrib.auth.hashers import check_password
限制未登录用户访问
装饰器解决问题
from django.http import HttpResponseRedirect
def is_login(request):
if not request.user.is_authenticated():
return HttpResponseRedirect('/accounts/login/')
限制已登录用户访问
限制访问可以基于某种权限,某些检查或者为login视图提供不同的位置,这些实现方式大致相同
def vote(request):
if request.user.is_authenticated() and request.user.has_perm('polls.can_vote')):
# vote here
else:
return HttpResponse("deny")
上述约束条件可自行修改,【查询自建权限表】