自定义token
#原理自定义token,放入cookie中,不用存数据库
#token定义方式 >>>>> "加密字符串"|登陆用户id|用户登陆时间
#加密字符串由登陆用户id,登陆时间和盐通过md5加密完成
import hashlib
def get_token(user_id,current_time):
md5= hashlib.md5()
md5.update("宝塔镇河妖".encode("utf-8"))
md5.update(str(current_time).encode("utf-8"))
md5.update(str(user_id).encode("utf-8"))
md5.update("egon掏大刀".encode("utf-8"))
token ="|".join([md5.hexdigest(),str(user_id),str(current_time)])
return token
#对应的解密方法
def check_token(token,redis_conn):
try:
res = redis_conn.get(token)
if not res:
return False,"未登陆"
user_info = token.split("|")
user_id = user_info[1]
create_time = user_info[2]
if token != get_token(user_id,create_time):
return False,"非法登陆"
return True,"登陆成功"
except Exception as e:
print(e)
return False,"未知错误"
pass
#登陆函数
def post(self, request):
uname = request.POST.get("uname")
user = User.objects.filter(uname=uname)
if not user:
return Response({"status": 101, "msg": "user not exists"})
pwd = request.POST.get("pwd")
hashlib_pwd = hash_pwd(pwd)
db_pwd = user[0].pwd
if hashlib_pwd != db_pwd:
return Response({"status": 102, "msg": "password error"})
try:
token = get_token(user[0].pk, time.time())
if user[0].isadmin:
response = render(request, "admin/index.html", {"uname": uname})
else:
response = render(request, "user/index.html", {"uname": uname})
#将token信息放入cookie中,客户端就会将token存入cookie中,下次来的时候request.COOKIE.get("token")就能拿到
response.set_cookie("token", token)
return response
except Exception as e:
return Response({"status": 103, "msg": "unknown error"})