pythonflaskpermissionsrolesflask-security

Flask Security Permissions of Roles


Flask Security offers a role system, a user can be assigned one or more roles. Similar to the login with @login_requiered, there is a @roles_required('Admin').

In Flask Security there are also permissions. My understanding is that I can assign different permissions to roles and if a user with a certain role is logged in later, I can use @permissions_required('permissionXYZ') to check that this user has the required permission.

I have managed to create roles and users and also the check whether a user has a role works. I just can't get the whole part with the permissions to work. To be exactly i get bonly the permission system running with an Intger value. What do I have to do to add permissions to a role?

I cant find an example of this role-permission system somewhere and the documentation is not complety clear for me (https://flask-security-too.readthedocs.io/en/stable/api.html#flask_security.permissions_required)

class User(db.Model, UserMixin):
    __tablename__ = "users"
    id = Column(Integer, primary_key=True)
    username = Column(String(64), index=True, unique=True, nullable=False)
    password_hash = Column(String(256))
    email = Column(String(80), index=True, unique=True, nullable=False)
    roles = db.relationship('Role', secondary=roles_users, backref='roled')
    fs_uniquifier = Column(String(255), unique=True,
                           nullable=False, default=lambda: str(uuid.uuid4()))

class Role(db.Model, RoleMixin):
    __tablename__ = 'role'
    id = db.Column(db.Integer(), primary_key=True)
    name = db.Column(db.String(80), unique=True)
    permissions = db.Column(db.String(80), default='')
admin_role = user_datastore.create_role(name="admin", permissions=1)
user = User(username=os.getenv('ADMIN_USERNAME'), email=os.getenv('ADMIN_EMAIL'))
password = os.getenv('ADMIN_PASSWORD')
        if user and password:
            user.set_password(password)
            security.datastore.add_role_to_user(user, admin_role)
@permissions_required('1')
def exmaple():
         stuff...

I tried to simply add the permission parameter with an Integer (in the example with 1 it worked). But the idea is (if i understood the documentation right) to store there a list (data type), which of course does not work in this form in a (maria)DB.


Solution

  • In the model documentation: https://flask-security.readthedocs.io/en/stable/models.html#additional-functionality it describes that the ORM layer is responsible for handling 'list-of-string' - which some ORM/DB such as Mongo support natively. For SQL-like ORMs - Flask-Security provides a utility method AsaList - documented here: https://flask-security.readthedocs.io/en/stable/api.html#flask_security.AsaList