You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
75 lines
2.4 KiB
75 lines
2.4 KiB
import json
|
|
from datetime import datetime, timedelta
|
|
|
|
import jwt
|
|
|
|
from django.views.decorators.csrf import csrf_exempt
|
|
from Student.models import *
|
|
from teacher.models import Teacher
|
|
from EduSystemServer.settings import TOKEN_KEY
|
|
from EduSystemServer.utils import *
|
|
|
|
# 用户登录成功后生成 JWT Token
|
|
def generate_jwt_token(user, _type):
|
|
# 设置 Token 的有效期
|
|
expiration_time = datetime.utcnow() + timedelta(hours=1)
|
|
|
|
# 构建 Token 数据
|
|
payload = {
|
|
'type': _type,
|
|
'username': user.username,
|
|
'exp': expiration_time
|
|
}
|
|
# 使用密钥对数据进行签名生成 Token
|
|
token = jwt.encode(payload, TOKEN_KEY, algorithm='HS256')
|
|
return token
|
|
|
|
@csrf_exempt
|
|
def login(request):
|
|
"""
|
|
登录
|
|
"""
|
|
username = request.POST.get("username")
|
|
password = request.POST.get("password")
|
|
_type = request.POST.get("type")
|
|
if _type == "student":
|
|
student = Student.objects.filter(username=username,
|
|
password=password).first()
|
|
if student:
|
|
result = student.to_dict()
|
|
result = ResponseUtil.ok(result, "login success!")
|
|
result["token"] = generate_jwt_token(student, "student").decode("utf-8")
|
|
else:
|
|
result = {"code": -1, "message": "username or password error!"}
|
|
elif _type == "teacher":
|
|
teacher = Teacher.objects.filter(username=username,
|
|
password=password).first()
|
|
if teacher:
|
|
result = teacher.to_dict()
|
|
result = ResponseUtil.ok(result, "login success!")
|
|
result["token"] = generate_jwt_token(teacher, "teacher").decode("utf-8")
|
|
else:
|
|
result = ResponseUtil.error("username or password error!")
|
|
else:
|
|
result = ResponseUtil.error("type error!")
|
|
response = JsonResponse(result)
|
|
return response
|
|
|
|
@csrf_exempt
|
|
def get_user_info(request):
|
|
"""
|
|
返回用户信息
|
|
"""
|
|
_type = request.jwt_payload.get("type")
|
|
username = request.jwt_payload.get("username")
|
|
if _type == "student":
|
|
student = Student.objects.filter(username=username).first()
|
|
result = ResponseUtil.ok(student.to_dict())
|
|
elif _type == "teacher":
|
|
teacher = Teacher.objects.filter(username=username).first()
|
|
result = ResponseUtil.ok(teacher.to_dict())
|
|
else:
|
|
result = ResponseUtil.error("type error")
|
|
request.session.clear()
|
|
return JsonResponse(result)
|