专栏首页sktjflask 用户、角色、权限模型(flask 86)

flask 用户、角色、权限模型(flask 86)

import os from datetime import datetime

from flask import current_app from flask_avatars import Identicon from flask_login import UserMixin from werkzeug.security import generate_password_hash, check_password_hash

from extensions import db, whooshee

roles_permissions = db.Table('roles_permissions', db.Column('role_id', db.Integer, db.ForeignKey('role.id')), db.Column('permission_id', db.Integer, db.ForeignKey('permission.id')) ) class Permission(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(30), unique=True) roles = db.relationship('Role', secondary=roles_permissions, back_populates='permissions') class Role(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(30), unique=True) users = db.relationship('User', back_populates='role') permissions = db.relationship('Permission', secondary=roles_permissions, back_populates='roles')

@staticmethod
def init_role():
    roles_permissions_map = {
        'Locked': ['FOLLOW', 'COLLECT'],
        'User': ['FOLLOW', 'COLLECT', 'COMMENT', 'UPLOAD'],
        'Moderator': ['FOLLOW', 'COLLECT', 'COMMENT', 'UPLOAD', 'MODERATE'],
        'Administrator': ['FOLLOW', 'COLLECT', 'COMMENT', 'UPLOAD', 'MODERATE', 'ADMINISTER']
    }

    for role_name in roles_permissions_map:
        role = Role.query.filter_by(name=role_name).first()
        if role is None:
            role = Role(name=role_name)
            db.session.add(role)
        role.permissions = []
        for permission_name in roles_permissions_map[role_name]:
            permission = Permission.query.filter_by(name=permission_name).first()
            if permission is None:
                permission = Permission(name=permission_name)
                db.session.add(permission)
            role.permissions.append(permission)
    db.session.commit()

@whooshee.register_model('name', 'username') class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(20), unique=True, index=True) email = db.Column(db.String(254), unique=True, index=True) password_hash = db.Column(db.String(128)) name = db.Column(db.String(30)) website = db.Column(db.String(255)) bio = db.Column(db.String(120)) location = db.Column(db.String(50)) member_since = db.Column(db.DateTime, default=datetime.utcnow) avatar_s = db.Column(db.String(64)) avatar_m = db.Column(db.String(64)) avatar_l = db.Column(db.String(64)) avatar_raw = db.Column(db.String(64))

confirmed = db.Column(db.Boolean, default=False)
locked = db.Column(db.Boolean, default=False)
active = db.Column(db.Boolean, default=True)

role_id = db.Column(db.Integer, db.ForeignKey('role.id'))

role = db.relationship('Role', back_populates='users')

def __init__(self, **kwargs):
    super(User, self).__init__(**kwargs)
    self.generate_avatar()
    self.follow(self)  # follow self
    self.set_role()

def set_password(self, password):
    self.password_hash = generate_password_hash(password)

def set_role(self):
    if self.role is None:
        if self.email == current_app.config['ALBUMY_ADMIN_EMAIL']:
            self.role = Role.query.filter_by(name='Administrator').first()
        else:
            self.role = Role.query.filter_by(name='User').first()
        db.session.commit()

def validate_password(self, password):
    return check_password_hash(self.password_hash, password)

def block(self):
    self.active = False
    db.session.commit()

def unblock(self):
    self.active = True
    db.session.commit()

def generate_avatar(self):
    avatar = Identicon()
    filenames = avatar.generate(text=self.username)
    self.avatar_s = filenames[0]
    self.avatar_m = filenames[1]
    self.avatar_l = filenames[2]
    db.session.commit()

@property
def is_admin(self):
    return self.role.name == 'Administrator'

@property
def is_active(self):
    return self.active

def can(self, permission_name):
    permission = Permission.query.filter_by(name=permission_name).first()
    return permission is not None and self.role is not None and permission in self.role.permissions

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • python flask web开发实战 DB flask-sqlalchemy

    MySQL mysql://username:password@hostname/database Postgres postgresql://usernam...

    用户5760343
  • flask 数据库配置(flask 25)

    from flask_sqlalchemy import SQLAlchemy WIN = sys.platform.startswith('win') i...

    用户5760343
  • flask 邻接列表关系(flask 48)

    class Comment(db.Model): id = db.Column(db.Integer, primary_key=True) author =...

    用户5760343
  • 使用mongo shell远程连接数据库

    codecraft
  • MongoDB基础语句

    闺蜜苏苏工作是前端开发,她竟然被要求用到MongoDB数据库,所以先让她安装好先,再来测试下面语句~ MongoDB数据库安装地址:http://jingya...

    MonroeCode
  • python flask web开发实战 DB flask-sqlalchemy

    MySQL mysql://username:password@hostname/database Postgres postgresql://usernam...

    用户5760343
  • flask 数据库配置(flask 25)

    from flask_sqlalchemy import SQLAlchemy WIN = sys.platform.startswith('win') i...

    用户5760343
  • flask 数据库关系(flask 28)

    class Writer(db.Model): books=db.relationship('Book',back_populates='writer') ...

    用户5760343
  • flask + pymysql操作Mysql数据库

    安装flask-sqlalchemy、pymysql模块 pip install flask-sqlalchemy pymysql  ### Flask-SQL...

    用户1173509
  • flask 邻接列表关系(flask 48)

    class Comment(db.Model): id = db.Column(db.Integer, primary_key=True) author =...

    用户5760343

扫码关注云+社区

领取腾讯云代金券