Django rstful登陆认证并检查session是否过期代码实例

时间:2021-05-22

这篇文章主要介绍了Django rstful登陆认证并检查session是否过期代码实例,下面我们可以来一起学习一下。

一:restful用户视图

#!/usr/bin/env python# -*- coding:UTF-8 -*-# Author:Leslie-xfrom users import modelsfrom rest_framework.decorators import actionfrom rest_framework.response import Responsefrom rest_framework import viewsetsfrom rest_framework import serializersfrom django.contrib.auth import authenticate, login, logoutclass UserSerializer(serializers.ModelSerializer): class Meta: model = models.User exclude = ('password',)class UserViewSet(viewsets.ReadOnlyModelViewSet): serializer_class = UserSerializer queryset = User.objects.all() authentication_classes = (UserAuthentication,) @action(detail=False, methods=['post']) def register(self, request, *args, **kwargs): username = request.data.get("username") queryset = User.objects.filter(username=username) if queryset.exists(): raise exceptions.PermissionDenied('该账号已经被注册') user = User.objects.create_user(**request.data) UserProfile.objects.create(user=user, nickname=user.username) data = self.get_serializer(user).data return Response(data) @action(detail=False, methods=['post']) def login(self, request, *args, **kwargs): username = request.data.get("username") password = request.data.get("password") user = authenticate(username=username, password=password) if not user: raise exceptions.PermissionDenied('用户名或密码错误') auth_id = request.session.get('_auth_user_id') if auth_id != str(user.pk): logout(request) login(request, user) data = self.get_serializer(user).data data['session_key'] = request.session.session_key return Response(data) @action(detail=False, methods=['post']) def logout(self, request, *args, **kwargs): logout(request) return Response()

二:检查session是否过期

from rest_framework.authentication import SessionAuthenticationfrom rest_framework.request import Requestfrom django.contrib.sessions.models import Sessionfrom rest_framework import exceptionsimport arrowclass CustomAuth(SessionAuthentication): def check_session(self, request): session_key = request.session.session_key queryset = Session.objects.filter(session_key=session_key) if not queryset.exists(): raise exceptions.PermissionDenied('非法用户,拒绝访问') expire_date = queryset.first().expire_date now = arrow.now().format('YYYY-MM-DD HH:mm:ss') if not arrow.get(now) < arrow.get(expire_date): raise exceptions.PermissionDenied('session expired') def authenticate(self, request: Request): ret = super().authenticate(request)     self.check_session(request)     return ret

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章