flask 利用装饰器进行用户认证

from flask import request, g

from User.models import XPCUser, VIPUser
from my_second_flask.extension import cache

'''用户认证必须登录才能进行相关的操作'''
def login_required(fun):
    def inner(*args, **kwargs):
        token = request.args.get('token')
        if not token:
            data = {
                'msg':'请登录',
                'status':400
            }
            return data
        user_id = cache.get(token)
        if not user_id:
            data = {
                'msg':'登录到期,请重新获取登录令牌',
                'status':400
            }
            return data
        g.user_id = user_id
        return fun(*args, **kwargs)
    return inner


'''判断用户的身份为普通用户还是vip用户'''
def login_authentication(fun):

    def inner(*args, **kwargs):
        try:
            token = request.args.get('token')
            user_id = cache.get(token)
            user = XPCUser.query.get(user_id)
            if not user:
                raise Exception("用户不存在")
            else:
                vip_user = VIPUser.query.get(user_id)
                if vip_user and vip_user.is_vip:
                    is_vip = True
                else:
                    is_vip = False
                g.token = token
                g.user_id = user_id
                g.user = user
                g.is_vip = is_vip
        except Exception as e:
            print(e)
            g.user_id = 0
            g.is_vip = False

        return fun(*args, **kwargs)
    return inner

你可能感兴趣的:(flask 利用装饰器进行用户认证)