创建权限
class Permission(object):
# 255的二进制方式来表示 1111 1111
ALL_PERMISSION = 0b11111111
# 1. 访问者权限
VISITOR = 0b00000001
# 2. 管理帖子权限
POST = 0b00000010
# 3. 管理评论的权限
COMMENT = 0b00000100
# 4. 管理板块的权限
BANNER = 0b00001000
# 5. 管理前台用户的权限
USER = 0b00010000
# 6. 管理后台管理员的权限
STAFF = 0b01000000
class RoleModel(db.Model, SerializerMixin):
serialize_only = ("id", "name", "desc", "create_time")
__tablename__ = 'role'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(50), nullable=False)
desc = db.Column(db.String(200),nullable=True)
create_time = db.Column(db.DateTime,default=datetime.now)
permissions = db.Column(db.Integer,default=Permission.VISITOR)
添加测试数据
commands.py
# 0b001
# 0b010
# 0b011 = ob001 | ob010
# 1|0=1,1|1=1,0|0=0
def init_roles():
# 运营
operator_role = RoleModel(name="运营", desc="负责管理帖子和评论",
permissions=Permission.POST | Permission.COMMENT | Permission.USER)
# 管理员
admin_role = RoleModel(name="管理员", desc="负责整个网站的管理",
permissions=Permission.POST | Permission.COMMENT | Permission.USER | Permission.STAFF)
# 开发者(权限是最大的)
developer_role = RoleModel(name="开发者", desc="负责网站的开发", permissions=Permission.ALL_PERMISSION)
db.session.add_all([operator_role, admin_role, developer_role])
db.session.commit()
print("角色添加成功!")
app.py
app.cli.command("init_developor")(commands.init_developor)
def bind_roles():
user1 = UserModel.query.filter_by(email="[email protected]").first()
user2 = UserModel.query.filter_by(email="[email protected]").first()
user3 = UserModel.query.filter_by(email="[email protected]").first()
role1 = RoleModel.query.filter_by(name="开发者").first()
role2 = RoleModel.query.filter_by(name="运营").first()
role3 = RoleModel.query.filter_by(name="管理员").first()
user1.role = role1
user2.role = role2
user3.role = role3
db.session.commit()
print("用户和角色绑定成功!")
app.py
app.cli.command("bind_roles")(commands.bind_roles)
执行命令
flask bind_roles
增加属性判断用户权限
UserModel
def has_permission(self, permission):
# 当前用户所拥有的权限&permission = permission
# 0b011 & 0b001 = 0b001
# 0b011 & 0b100 = 0b000
return (self.role.permissions & permission) == permission
from functools import wraps
from flask import g
from utils import restful
def permission_required(permission):
def outter(func):
@wraps(func)
def inner(*args, **kwargs):
#请求cmspi过来之前就因为设置了该属性 这里获取该属性
user = getattr(g, "user")
if not user:
return restful.unlogin_error()
if user.has_permission(permission):
return func(*args, **kwargs)
else:
return restful.permission_error(message="您没有权限访问这个接口!")
return inner
return outter
但是这样访问不太友好,虽然没有权限看不到数据但是还可以看到页面,
在登陆的时候就校验
# 如果是员工,才生成token
token = ""
permissions = []
if user.is_staff:
token = create_access_token(identity=user.id)
for attr in dir(Permission):
if not attr.startswith("_"):
permission = getattr(Permission, attr)
if user.has_permission(permission):
permissions.append(attr.lower())
if remember == 1:
# 默认session过期时间,就是只要浏览器关闭了就会过期
session.permanent = True
"""
{"avatar":"677d1194c930361e88189b315e4de934.jpg","comments":[],"email":"[email protected]","id":"fiuhqDhK6Wo6Rb9hHc9ffX","is_active":true,"is_staff":true,"join_time":"2021-11-25 15:35:40","posts":[],"signature":"欢饮刚来到知了传课学习Python","username":"zhiliaochuanke"}
"""
user_dict = user.to_dict()
user_dict['permissions'] = permissions
return restful.ok(data={"token": token, "user": user_dict})
else:
return restful.params_error(message=form.messages[0])
App.vue
methods: {
has_permission(permission){
return this.$auth.user.permissions.indexOf(permission) >= 0
}
用户 及角色展示