一百零七:CMS系统之权限和角色模型定义

 

模型与权限关系映射表

class CMSPersmission:
""" 权限管理映射 """
# 255的二进制方式来表示 1111 1111
ALL_PERMISSION = 0b11111111
# 1. 访问者权限
VISITOR = 0b00000001
# 2. 管理帖子权限
POSTER = 0b00000010
# 3. 管理评论的权限
COMMENTER = 0b00000100
# 4. 管理板块的权限
BOARDER = 0b00001000
# 5. 管理前台用户的权限
FRONTUSER = 0b00010000
# 6. 管理后台用户的权限
CMSUSER = 0b00100000
# 7. 管理后台管理员的权限
ADMINER = 0b01000000


# 用户与权限的中间表
cms_role_user = db.Table(
'cms_role_user',
db.Column('cms_role_id', db.Integer, db.ForeignKey('cms_role.id'), primary_key=True),
db.Column('cms_user_id', db.Integer, db.ForeignKey('cms_user.id'), primary_key=True)
)


class CMSRole(db.Model):
__tablename__ = 'cms_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=CMSPersmission.VISITOR)
users = db.relationship('CMSUser', secondary=cms_role_user, backref='roles')

执行数据库脚本迁移

python manager.py db migrate
python manager.py db upgrade

定义角色

@manager.command
def create_role():
""" 创建不同权限的角色 """
# 1.访问者(可以修改个人信息)
visitor = CMSRole(name='访问者', desc='只能看相关数据,不能修改')
visitor.permissions = CMSPermission.VISITOR

# 2.运营角色(修改个人信息、管理帖子、管理评论、管理前台用户)
# 0b00000001|0b00000010|0b00100000|0b00000100 = 0b00010111
operator = CMSRole(name='运营', desc='管理帖子、评论、前台用户')
operator.permissions = CMSPermission.VISITOR | CMSPermission.POSTER | CMSPermission.CMSUSER | CMSPermission.COMMENTER | CMSPermission.FRONTUSER

# 3.管理员(拥有绝大部分权限,不含同级别的权限)
# 0b00000001|0b00000010|0b00100000|0b00000100|0b00001000 = 0b00011111
admin = CMSRole(name='管理员', desc='拥有本系统所有权限')
admin.permissions = CMSPermission.VISITOR | CMSPermission.POSTER | CMSPermission.CMSUSER | CMSPermission.COMMENTER | CMSPermission.FRONTUSER | CMSPermission.BOARDER

# 4.开发者(所有权限)
developer = CMSRole(name='开发者', desc='开发人员专用角色')
developer.permissions = CMSPermission.ALL_PERMISSION
db.session.add_all([visitor, operator, admin, developer])
db.session.commit()

命令行执行:python manager.py create_role

 

posted @ 2019-11-25 21:48  向前走。  阅读(872)  评论(0编辑  收藏  举报