生成Token,验证Token代码如下:

from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, SignatureExpired, BadSignature
from config import BaseConfig
from flask import request, jsonify
from functools import wraps
from db_connect import db_select


# 生成token, 有效时间为24小时
def generate_token(id, username=None, expiration=86400):
    serializer = Serializer(BaseConfig.SECRET_KEY, expires_in=expiration)
    data = {'id': id, 'username': username} if username is not None else {}
    return serializer.dumps(data)


# 解析token
def verify_token(token):
    serializer = Serializer(BaseConfig.SECRET_KEY)
    # token正确
    try:
        data = serializer.loads(token)
        return data
    # token过期
    except SignatureExpired:
        return None
    # token错误
    except BadSignature:
        return None
    # token无值
    except Exception as e:
        return None


# 获取登录用户id
def get_user_id():
    token = request.headers.get('Authorization')
    data = verify_token(token)
    id = data["id"]
    return id


def login_required(func):
    """登录校验装饰器
    :param func:函数名
    :return: 闭包函数名
    """
    @wraps(func)
    def decorated(*args, **kwargs):
        token = request.headers.get('Authorization', None)
        if verify_token(token):
            return func(*args, **kwargs)
        return jsonify({'code': 401, 'msg': '登录过期,请重新登录!'})
    return decorated

# 判断是否为管理员
def is_admin(user_id):
    admin_sql = f"SELECT tg.name FROM tb_users tu \
                  LEFT JOIN tb_groups tg \
                  ON tu.group_id=tg.id \
                  WHERE tu.id={user_id}"
    auth_type, auth_name = db_select(admin_sql)
    if auth_type[0][0] != "管理员":
        return True
    else:
        return False

 

posted on 2022-06-15 13:50  山海经-小怪  阅读(1142)  评论(0编辑  收藏  举报