D Emma
D Emma

Reputation: 317

In Python Flask, how to get the role name by the current logged in user?

I have 3 tables for user-role many-to-many relationship in Flask. How should I get the role name from the current user?

In my models.py

class User(db.Model, UserMixin):
    __tablename__ = "Users"
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(100), nullable=False, unique=True)
    password = db.Column(db.String(255), nullable=False, server_default='')

    # Define the relationship to Role via UserRoles
    roles = db.relationship('Role', secondary='UserRoles', backref=db.backref("user", lazy="dynamic"))


# Define the Role data-model
class Role(db.Model):
    __tablename__ = 'Roles'
    id = db.Column(db.Integer(), primary_key=True)
    name = db.Column(db.String(50), unique=True)
    users = db.relationship('User', secondary='UserRoles', backref=db.backref("role", lazy="dynamic"))


# # Define the UserRoles association table
class UserRole(db.Model):
    __tablename__ = 'UserRoles'
    id = db.Column(db.Integer(), primary_key=True)
    user_id = db.Column(db.Integer(), db.ForeignKey('Users.id', ondelete='CASCADE'))
    role_id = db.Column(db.Integer(), db.ForeignKey('Roles.id', ondelete='CASCADE'))

In my views.py:

from flask_user import current_user

@app.route("/TestUserRole")
def user_role():
    role = current_user.role
    return str(role)

On the browser, it shows me the returned result:

SELECT [Roles].id AS [Roles_id], [Roles].name AS [Roles_name] FROM [Roles], [UserRoles] WHERE [UserRoles].user_id = ? AND [Roles].id = [UserRoles].role_id

Is there a possible way to show the role name of the current user, something like the following (bad example, though, since it will pop out error)?

role = current_user.role.name

Upvotes: 3

Views: 5152

Answers (2)

Matheus Alves
Matheus Alves

Reputation: 33

I know the question is old, but I'll comment on the solution in case anyone encounters the same problem.

roles = current_user.roles
list_roles = []
for role in roles:
    list_roles.append(role.name)

Upvotes: 1

Nizamudheen At
Nizamudheen At

Reputation: 334

The current_user.has_roles function will help.

It is quite simple: Suppose you have configure below roles like

Role1: Admin

Role2: Manager

If user has no role associated then, current_user.has_roles() will be False.

If logged in user has a role of 'Admin', this can be verified using current_user.has_roles('Admin').

So users roles can be accessed via has_roles().

Upvotes: 1

Related Questions