第二章:用户权限篇

权限五表

第二章:用户权限篇_第1张图片

模型代码实现:

user_role = db.Table(
    'user_role',
    db.Column('user_id', db.Integer, db.ForeignKey('user.id'), primary_key=True),
    db.Column('role_id', db.Integer, db.ForeignKey('role.id'), primary_key=True)
)

role_auth = db.Table(
    'role_auth',
    db.Column('role_id', db.Integer, db.ForeignKey('role.id'), primary_key=True),
    db.Column('auth_id', db.Integer, db.ForeignKey('auth.id'), primary_key=True)
)


class User(Base):
    name = db.Column(db.String(32), unique=True, nullable=False, comment='用户名')
    email = db.Column(db.String(32), unique=True, nullable=True, comment='邮箱')
    is_admin = db.Column(db.Boolean, unique=False, nullable=False, default=False, comment='是否是超级管理员')
    # is_active = db.Column(db.Boolean, unique=False, nullable=False, default=True, comment='是否激活')
    roles = db.relationship('Role', secondary=user_role, backref=db.backref('users', lazy='dynamic'), lazy='dynamic')
    _password = db.Column('password', db.String(100), comment='密码')

    ,,,


class Role(Base):
    name = db.Column(db.String(32), unique=True, comment='角色名称')
    describe = db.Column(db.String(255), comment='角色描述')
    auths = db.relationship('Auth', secondary=role_auth, backref=db.backref('roles', lazy='dynamic'), lazy='dynamic')

    ...


class Auth(Base):
    name = db.Column(db.String(32), unique=True, comment='权限名称')
    module = db.Column(db.String(32), comment='权限模块')
    endpoint = db.Column(db.String(255), comment='路由端点')

    ...

JWT认证

主要实现token的生成和验证

from flask_jwt_extended import verify_jwt_in_request, create_access_token

def get_token(user):
    identity['uid'] = user.id
    access_token = create_access_token(identity=identity)
    return access_token

其中,添加权限、角色验证、登录验证以及管理员验证也在JWT模块中实现:

def add_auth(name, module, prefix):
    """添加权限装饰器"""

    def wrapper(func):
        auths.append([name, module, prefix + '.' + func.__name__])
        return func

    return wrapper


def admin_required(fn):
    """管理权限装饰器"""

    @wraps(fn)
    def wrapper(*args, **kwargs):
        verify_jwt_in_request()
        current_user = get_current_user()
        if not current_user.is_admin:
            raise AuthException(message='权限不足')
        return fn(*args, **kwargs)

    return wrapper


def role_required(fn):
    """角色权限装饰器"""

    @wraps(fn)
    def wrapper(*args, **kwargs):
        verify_jwt_in_request()
        current_user = get_current_user()
        if not current_user.is_admin:
            roles = current_user.roles.all()
            it = is_user_allowed(roles)
            if not it:
                raise AuthException(message='权限不足')
            else:
                return fn(*args, **kwargs)
        else:
            return fn(*args, **kwargs)

    return wrapper


def login_required(fn):
    """登录装饰器"""

    @wraps(fn)
    def wrapper(*args, **kwargs):
        verify_jwt_in_request()
        return fn(*args, **kwargs)

    return wrapper

你可能感兴趣的:(Flask后端项目实战)