flask 带时效令牌验证(flask 92)

2019-08-20 18:06:03 浏览数 (1)

from itsdangerous import BadSignature, SignatureExpired from itsdangerous import TimedJSONWebSignatureSerializer as Serializer

def generate_token(user, operation, expire_in=None, **kwargs): s = Serializer(current_app.config['SECRET_KEY'], expire_in)

代码语言:javascript复制
data = {'id': user.id, 'operation': operation}
data.update(**kwargs)
return s.dumps(data)

def validate_token(user, token, operation, new_password=None): s = Serializer(current_app.config['SECRET_KEY'])

代码语言:javascript复制
try:
    data = s.loads(token)
except (SignatureExpired, BadSignature):
    return False

if operation != data.get('operation') or user.id != data.get('id'):
    return False

if operation == Operations.CONFIRM:
    user.confirmed = True
elif operation == Operations.RESET_PASSWORD:
    user.set_password(new_password)
elif operation == Operations.CHANGE_EMAIL:
    new_email = data.get('new_email')
    if new_email is None:
        return False
    if User.query.filter_by(email=new_email).first() is not None:
        return False
    user.email = new_email
else:
    return False

db.session.commit()
return True

token = generate_token(user=user, operation='confirm') send_confirm_email(user=user, token=token)

代码语言:javascript复制
if validate_token(user=current_user, token=token, operation=Operations.CONFIRM):
    flash('Account confirmed.', 'success')
    return redirect(url_for('main.index'))

默认过期事件1个小时

Serializer

0 人点赞