class User(AbstractUser): username = models.CharField( max_length=20, unique=True, primary_key=True, verbose_name="用户名" ) email = models.EmailField(max_length=256, null=False, verbose_name="邮箱", blank=True) password = models.CharField(max_length=128, verbose_name="密码") token = models.CharField(max_length=256, null=True, verbose_name="Token") token_begin_time = models.DateField(null=True, verbose_name="Token生效时间") token_last_time = models.DateField(null=True, verbose_name="Token失效时间") class Meta: verbose_name_plural = "用户信息表"def generateToken(flag,username): import datetime import uuid headers = {"alg": "HS256", "typ": "JWT"} token_new = jwt.encode(payload={"name": username+f"_{str(uuid.uuid1())}"}, key="ess_token_check_key", algorithm='HS256', headers=headers) date_now_new = datetime.datetime.now() date_week_new = (date_now_new + datetime.timedelta(days=6)).strftime("%Y-%m-%d") date_date_now_new = date_now_new.strftime("%Y-%m-%d")
if flag == "username": user_model = models.User.objects.get(username=username) if flag == "email": user_model = models.User.objects.get(email=username)
if user_model.token == None and user_model.token_begin_time == None and user_model.token_last_time == None: user_model user_model.token = token_new user_model.token_begin_time = date_date_now_new user_model.token_last_time = date_week_new user_model.save() return token_new else: if datetime.date(*map(int, date_date_now_new.split('-'))) <= user_model.token_last_time: return user_model.token else: user_model.token = token_new user_model.token_begin_time = date_date_now_new user_model.token_last_time = date_week_new user_model.save() return token_new
def login(request): if request.method == "POST": data = QueryDict(request.body)
# token = request.META.get('HTTP_TOKEN') # 获取请求头中的token
username = data.get("user") password = data.get("pwd") db_pwd = models.User.objects.filter(username=username).values("password")[0]["password"] pwd_flag = check_password(password, db_pwd) if pwd_flag: token = generateToken(flag="username", username=username)return JsonResponse({"data": "successful", "zhuname": zhuname, "power": power, "token":token}) else: return JsonResponse({"data": "账号或密码错误!"})
$.ajax("/insert/", { method: "POST", headers: {
"token": window.localStorage.getItem("token") }, contentType: "application/json; charset=utf-8", dataType: "json", data: {uname: uname, pname: pname},
}).done(function (res) { if (res && res.data == "successful") {console.log('successfule')
}
标签:username,认证,token,user,date,new,model,django From: https://www.cnblogs.com/taotao0805/p/17356983.html