django项目中写入方法
这是先登录,如果用户没有存在,就给他注册一个用户,注册完之后,在让用户登录,登录时判断是否有管理权限
import redis
from rest_framework.views import APIView
from rest_framework.respoonse import Response
from django.contrib.auth.hashers import check_password
from datetime import datetime
from rest_framework_jwt.utils import jwt_payload_handler, jwt_encode_handler
# 登录视图
class LoginUserAPIView(APIView):
def post(self, request):
username = request.data.get("username")
password = request.data.get("password")
mobile = request.data.get("mobile")
sms_code = request.data.get("sms_code")
r = redis.Redis(host='127.0.0.1', port=6379)
# 判断用户名是否存在
user = User.objects.filter(username=username).first()
if user:
# 判断密码
if check_password(password, user.password):
# 密码正确,判断是否以管理员身份登录
if user.is_staff and user.is_active:
token = self.gen_token(user)
# 改变登录时间
user.last_login = datetime.now()
user.save()
return Response({
'code': 200,
'msg': '登录成功',
'user': {
'id': user.id,
'name': user.username,
'token': token
}
})
else:
return Response({'code': 206, 'msg': '没有管理员权限'})
else:
# 密码不正确,重置密码
validation = self.validate_sms_code(sms_code, mobile, r)
if validation:
# 完成短信认证, 开始重置密码
user.set_password(password)
user.save()
return Response({'code': 207, 'msg': '密码以重置'})
else:
return Response({'code': 204, 'msg': '重置失败'})
else:
# 注册用户
if sms_code:
# 使用验证码,并注册
validation = self.validate_sms_code(sms_code, mobile, r)
# 注册用户信息
if validation:
User.objects.create_user(username=username, password=password, mobile=mobile)
return Response({'code': 201, 'msg': '注册成功,申请管理员权限'})
else:
return Response({'code': 400, 'msg': '注册失败'})
else:
return Response({'code': 400, 'msg': '请输入验证码'})
@staticmethod
def gen_token(user):
# 生成payload 载荷信息
payload = jwt_payload_handler(user)
# 生成token
# token = jwt_decode_handler(payload)
token = jwt_encode_handler(payload)
return token
@staticmethod
def validate_sms_code(sms_code, mobile, r):
stared_code = r.get(mobile)
if stared_code and stared_code.decode() == sms_code:
return True
else:
return False