To implement a simple role-based access control system, we need to create a new database entity Role model that will need a many-to-many relationship for our User model so that a user can have multiple roles.
With our code from Chapter 2, Creating Models with SQLAlchemy, adding a many-to-many relationship to the User object is easy, as shown in the following code:
roles = db.Table(
'role_users',
db.Column('user_id', db.Integer, db.ForeignKey('user.id')),
db.Column('role_id', db.Integer, db.ForeignKey('role.id'))
)
class User(db.Model):
...
roles = db.relationship(
'Role',
secondary=roles,
backref=db.backref('users', lazy='dynamic')
)
def __init__(self, username=""):
default = Role.query.filter_by(name="default...