class Permission(BaseModel): __tablename__ = 'crm_permission' __table_args__ = {'comment': '后台权限表'} name = db.Column(db.String(50), nullable=False, comment='权限名称') remark = db.Column(db.String(255), nullable=True, comment='备注') def __repr__(self): return 'Permission 模型对象-> ID:{} 权限名称:{}'.format(self.id, self.name)
class CMSUser(BaseModel): __tablename__ = 'cms_user' id = db.Column(db.Integer, primary_key=True, autoincrement=True) username = db.Column(db.String(50), nullable=False) _password = db.Column(db.String(100), nullable=False) # join_time = db.Column(db.DateTime, server_default=db.func.now()) def __init__(self, username, password): self.username = username self.password = password @property def password(self): return self._password @password.setter def password(self, raw_password): self._password = generate_password_hash(raw_password) def check_password(self, raw_password): result = check_password_hash(self.password, raw_password) return result @property def permissions(self): if not self.roles: return 0 all_permissions = 0 for role in self.roles: permissions = role.permissions all_permissions |= permissions # 整合该用户所有权限 # print('权限包含:', all_permissions) return all_permissions # 是否拥有权限 def has_permission(self, permission): # all_permissions = self.permissions # result = all_permissions&permission == permission # return result return self.permissions & permission == permission # 开发者 @property def is_developer(self): return self.has_permission(CMSPersmission.ALL_PERMISSION) def __repr__(self): return '<admin: 用户名 %s 密码 %s >' % ( self.username, self.password, )
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) # 引用模型:CMSUser # 中间表:cms_role_user # 通过CMSUser反向引用:roles users = db.relationship('CMSUser', secondary=cms_role_user, backref='roles')
class CMSUser(BaseModel): __tablename__ = 'cms_user' __table_args__ = {'comment': '用户表'} username = db.Column(db.String(50), nullable=False, comment='账号') _password = db.Column(db.String(100), nullable=False, comment='密码') # join_time = db.Column(db.DateTime, server_default=db.func.now()) def __init__(self, username, password): self.username = username self.password = password @property def password(self): return self._password @password.setter def password(self, raw_password): self._password = generate_password_hash(raw_password) def check_password(self, raw_password): result = check_password_hash(self.password, raw_password) return result @property def permissions(self): if not self.roles: return 0 all_permissions = 0 for role in self.roles: permissions = role.permissions all_permissions |= permissions # 整合该用户所有权限 # print('权限包含:', all_permissions) return all_permissions # 是否拥有权限 def has_permission(self, permission): # all_permissions = self.permissions # result = all_permissions&permission == permission # return result return self.permissions & permission == permission # 开发者 @property def is_developer(self): return self.has_permission(CMSPersmission.ALL_PERMISSION) def __repr__(self): return 'admin模型对象-> 用户名:{} 密码:{}'.format(self.username, self.password)
class Role(BaseModel): __tablename__ = 'crm_role' __table_args__ = {'comment': '后台角色表'} name = db.Column(db.String(50), nullable=False, comment='角色名称') remark = db.Column(db.String(255), nullable=True, comment='备注') user_list = db.relationship('Admin', secondary=crm_user_and_role, backref='roles') permission_list = db.relationship('Permission', secondary=crm_permission_and_role, backref='roles') def __repr__(self): return 'Role 模型对象-> ID:{} 角色名称:{}'.format(self.id, self.name)
class CMSRole(BaseModel): __tablename__ = 'cms_role' __table_args__ = {'comment': '权限角色表'} name = db.Column(db.String(50), nullable=False, comment='权限名称') desc = db.Column(db.String(200), nullable=True, comment='权限描述') # create_time = db.Column(db.DateTime, default=datetime.now) permissions = db.Column(db.Integer, default=CMSPersmission.VISITOR, comment='权限等级') # 引用模型:CMSUser # 中间表:cms_role_user # 通过CMSUser反向引用:roles users = db.relationship('CMSUser', secondary=cms_role_user, backref='roles')
class Admin(BaseModel): __tablename__ = 'crm_user' __table_args__ = {'comment': '后台用户表'} username = db.Column(db.String(50), nullable=False, comment='账号') _password = db.Column(db.String(100), nullable=False, comment='密码') mail = db.Column(db.String(100), nullable=True, comment='邮箱') remark = db.Column(db.String(255), nullable=True, comment='备注') def __init__(self, username, password): self.username = username self.password = password @property def password(self): return self._password @password.setter def password(self, raw_password): self._password = generate_password_hash(raw_password) def check_password(self, raw_password): result = check_password_hash(self.password, raw_password) return result def get_role(self): """获取当前用户的所有角色""" roles = self.roles # print(roles) roles_json = [r.to_json() for r in roles] return roles_json def get_permission(self): """获取当前用户的所有权限""" roles = self.roles permission_set = [] for r in roles: permission_set += r.permission_list # print(list(set(permission_set))) permission_json = [p.to_json() for p in list(set(permission_set))] return permission_json def __repr__(self): return 'Admin 模型对象-> ID:{} 用户名:{}'.format(self.id, self.username)
class BaseModel(db.Model): """ status:状态 create_timestamp:创建时间戳 create_time:创建时间DateTime update_timestamp:更新时间戳 update_time:更新时间DateTime """ __abstract__ = True id = db.Column(db.Integer, primary_key=True, autoincrement=True) _status = db.Column('status', db.Integer, default=1) _create_time = db.Column('create_time', db.DateTime, default=datetime.now) _create_timestamp = db.Column('create_timestamp', db.String(128), default=int(datetime.now().timestamp())) _update_time = db.Column('update_time', db.DateTime, default=datetime.now, onupdate=datetime.now) _update_timestamp = db.Column('update_timestamp', db.String(128), server_default='', onupdate=int(datetime.now().timestamp())) def __getitem__(self, item): return getattr(self, item) def to_json(self): dict = self.__dict__ if "_sa_instance_state" in dict: del dict["_sa_instance_state"] del dict["_update_timestamp"] del dict["_create_timestamp"] del dict["_create_time"] del dict["_update_time"] del dict["_status"] return dict def update(self, **kwargs): # print(self) for attr, value in kwargs.items(): try: # 部分属性无法setattr setattr(self, attr, value) except BaseException as e: pass return self
# 5. 管理前台用户的权限 FRONTUSER = 0b00010000 # 6. 管理后台用户的权限 CMSUSER = 0b00100000 # 7. 管理后台管理员的权限 ADMINER = 0b01000000 cms_role_user = db.Table( 'cms_role_user', # 表名 # 字段名:cms_role_id, # 类型 # 外键:cms_role.id, # 设置为主键 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)) # CMS角色 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)
class BaseModel(db.Model): """ status:状态 create_timestamp:创建时间戳 create_time:创建时间DateTime update_timestamp:更新时间戳 update_time:更新时间DateTime """ __abstract__ = True id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment='id') _status = db.Column('status', db.Integer, default=1, comment='状态:1正常,2删除') _create_time = db.Column('create_time', db.DateTime, default=datetime.now, comment='创建时间(结构化时间)') _create_timestamp = db.Column('create_timestamp', db.String(128), default=int(datetime.now().timestamp()), comment='创建时间(时间戳)') _update_time = db.Column('update_time', db.DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间(结构化时间)') _update_timestamp = db.Column('update_timestamp', db.String(128), server_default='', onupdate=int(datetime.now().timestamp()), comment='更新时间(时间戳)') def keys(self): """ 返回所有字段对象 :return: """ return self.__table__.columns def __getitem__(self, item): return getattr(self, item) def to_json(self): """ 旧方法 if "_sa_instance_state" in dict: del dict["_sa_instance_state"] del dict["_update_timestamp"] del dict["_create_timestamp"] del dict["_create_time"] del dict["_update_time"] del dict["_status"] if str(self.__table__) == 'cms_user': del dict["_password"] """ d = {} dict = self.__dict__ [d.update({i.name: dict.get(i.name, '')}) for i in self.keys()] print(d) del d["update_timestamp"] del d["create_timestamp"] del d["create_time"] del d["update_time"] del d["status"] return d def update(self, **kwargs): # print('self->', self) for attr, value in kwargs.items(): # print(attr, value) try: # 部分属性无法setattr setattr( self, attr, str(value) if isinstance(value, list) or isinstance(value, dict) else value) except BaseException as e: pass return self def delete_obj(self): self._status = 2 db.session.commit()
FRONTUSER = 0b00010000 # 6. 管理后台用户的权限 CMSUSER = 0b00100000 # 7. 管理后台管理员的权限 ADMINER = 0b01000000 cms_role_user = db.Table( 'cms_role_user', # 表名 # 字段名:cms_role_id, # 类型 # 外键:cms_role.id, # 设置为主键 db.Column('cms_role_id', db.Integer, db.ForeignKey('cms_role.id'), primary_key=True, comment='权限id'), db.Column('cms_user_id', db.Integer, db.ForeignKey('cms_user.id'), primary_key=True, comment='用户id'), comment='用户_角色_中间表') # CMS角色 class CMSRole(BaseModel): __tablename__ = 'cms_role' __table_args__ = {'comment': '权限角色表'} name = db.Column(db.String(50), nullable=False, comment='权限名称')
# @File : models.py # @Software: PyCharm from werkzeug.security import generate_password_hash, check_password_hash from ExtendRegister.db_register import db from common.libs.BaseModel import BaseModel """ RBAC 用户-角色-权限 """ crm_user_and_role = db.Table('cms_user_and_role', db.Column('cms_user_id', db.Integer, db.ForeignKey('crm_user.id'), primary_key=True, comment='用户id'), db.Column('cms_role_id', db.Integer, db.ForeignKey('crm_role.id'), primary_key=True, comment='角色id'), comment='用户_角色_中间表') crm_permission_and_role = db.Table('cms_permission_and_role', db.Column( 'cms_permission_id', db.Integer, db.ForeignKey('crm_permission.id'), primary_key=True,