django的权限认证:登录和退出。auth模块和@login_required装饰器
在settings.py中配置LOGIN_URL参数:
# 用户访问带有(@login_required)标签的页面(view)时,如果没有登录,就会跳转到LOGIN_URL(即登陆url)。 LOGIN_URL = '/login/'
使用django自带的auth模块进行登录和退出:
from django.contrib.auth.models import User
from django.contrib import auth
from django.http.response import HttpResponseRedirectBase
from django.shortcuts import resolve_url
# 重新重定向,修改状态码,由302(临时重定向)->401(未授权),方便前端fetch捕获
class HttpResponseRedirect401(HttpResponseRedirectBase):
status_code = 401
def redirect401(to, *args, **kwargs):
redirect_class = HttpResponseRedirect401
return redirect_class(resolve_url(to, *args, **kwargs))
def login(request):
# 统一登录的token解析,只要可以解析,就证明登录成功 token = request.GET.get('token', 'default') if token != 'default': user_info = decrypt_by_default_public_key(token) # if user_info: user_name = user_info.get('userName') user_email = user_info.get('loginId') # 返回的时间:51050年 # time = user_info.get('time') # year 51050 is out of range # print(datetime.datetime.fromtimestamp(time)) if User.objects.filter(username=user_name): pass else: # 必须有password字段,随便给一个密码;使用create_user,会对密码hash,不可以使用create函数 User.objects.create_user(username=user_name, password='test', email=user_email) user = auth.authenticate(username=user_name, password='test') auth.login(request, user) request.session['user'] = user_name # 登录之后重定向到欢迎界面,无法重定向到用户原本请求的页面,因为前端请求的url和代理后到后端的url不一致。 return redirect("/") else: # return redirect401(JANUS_LOGIN) _next = request.GET.get('next', 'default') if _next != 'default': return redirect401(JANUS_LOGIN) return redirect(JANUS_LOGIN) def logout(request): auth.logout(request)
# 重定向到统一退出地址 return redirect(JANUS_LOGOUT)
使用login_required校验用户是否登录
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
logger = logging.getLogger(conf.get('log', 'name')) @login_required # 添加csrf例外;支持post、get、delete、put、patch等方法 @csrf_exempt def hello(request): content = {'hello': 'hello world'} # return HttpResponse("hello world") logger.error('test') logger.error('访问hello界面:error') logger.debug('访问hello界面:debug') logger.info('访问hello界面:info') logger.warning('访问hello界面:warning') logger.critical('访问hello界面:critical') logger.log(40, '测试') logger.exception('ceshi') return render(request, 'hello.html', content)
参考:
https://www.cnblogs.com/xuchengcheng1215/p/9457950.html
https://www.cnblogs.com/tangpg/p/9074418.html
https://www.cnblogs.com/xuchengcheng1215/p/9457950.html