72 lines
1.9 KiB
Python
72 lines
1.9 KiB
Python
import functools
|
||
import time
|
||
|
||
from flask import request
|
||
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadSignature, SignatureExpired
|
||
|
||
from common.rsa import decrypt_data
|
||
|
||
SECRET_KEY = '0FTuOi^#Afx1@2@F'
|
||
TOKEN_EXPIRATION = 14400
|
||
|
||
|
||
def create_token(param):
|
||
"""
|
||
创建token
|
||
Parameters:
|
||
param: 传入参数,用于创建token
|
||
Returns:
|
||
token: 用户访问令牌
|
||
"""
|
||
s = Serializer(SECRET_KEY, expires_in=TOKEN_EXPIRATION)
|
||
token = '' + s.dumps(param).decode('ascii')
|
||
return token
|
||
|
||
|
||
def verify_token(func):
|
||
"""
|
||
校验token
|
||
"""
|
||
|
||
@functools.wraps(func)
|
||
def internal(*args, **kwargs):
|
||
# 检查token
|
||
try:
|
||
token = request.headers.get('token')
|
||
s = Serializer(SECRET_KEY)
|
||
cid = s.loads(token)['cid']
|
||
except TypeError:
|
||
return {"info": "参数错误"}, 401
|
||
except KeyError:
|
||
return {"info": "参数错误"}, 401
|
||
except BadSignature:
|
||
return {"info": "token错误"}, 401
|
||
except SignatureExpired:
|
||
return {"info": "token过期"}, 401
|
||
# 通过以上检查 返回原函数
|
||
return func(*args, **kwargs, cid=cid)
|
||
|
||
# 返回包装函数结果
|
||
return internal
|
||
|
||
|
||
def check_block(func):
|
||
"""
|
||
检查滑块是否通过
|
||
|
||
注: 前端发送的滑块校验码是rsa加密的时间戳,若时间戳间隔小于3秒则校验通过
|
||
"""
|
||
|
||
@functools.wraps(func)
|
||
def internal(*args, **kwargs):
|
||
try:
|
||
verify_code = decrypt_data(encrypt_msg=request.headers.get('block'))
|
||
if (time.time() - float(verify_code)/1000) > 3:
|
||
return {"info": "滑块校验失败"}, 400
|
||
except TypeError:
|
||
return {"info": "缺少滑块验证"}, 400
|
||
except ValueError:
|
||
return {"info": "滑块验证异常"}, 400
|
||
return func(*args, **kwargs)
|
||
return internal
|