1

I want to list all roles a given user has.

I'm not looking for current_user nor has_role. The idea is to make an 'edituser.html' where an admin can change/add/remove roles for a given user. For that use case I need to show what roles the user to be edited has.

I've read: Flask Security- check what Roles a User has but I don't understand how to use it in for example a route/view.

My models.py is like this.

class Role(db.Document, RoleMixin):
    def __str__(self):
        return self.name
    name = db.StringField(max_length=80, unique=True)
    description = db.StringField(max_length=255)
    permissions = db.StringField(max_length=255)

class User(db.Document, UserMixin):
    def __str__(self):
        return self.username

    username = db.StringField(max_length=255)
    password = db.StringField(max_length=255)
    active = db.BooleanField(default=True)
    fs_uniquifier = db.StringField(max_length=64, unique=True)
    confirmed_at = db.DateTimeField()
    current_login_at = db.DateTimeField()
    last_login_at = db.DateTimeField()
    current_login_ip = db.StringField(max_length=255)
    last_login_ip = db.StringField(max_length=255)
    login_count = db.IntField(max_length=255)
    roles = db.ListField(db.ReferenceField(Role), default=[])

user_datastore = MongoEngineUserDatastore(db, User, Role)
aquatic7
  • 615
  • 1
  • 6
  • 19

1 Answers1

1

Here is something I do in my app:

@staticmethod
def get_users():
    """Return list of all users"""
    attrs = (
        "email",
        "active",
        "confirmed_at",
        "create_datetime",
        "update_datetime",
        "last_login_at",
        "current_login_at",
        "current_login_ip",
    )
    query = current_app.sywuserdb.user_model.query
    users = query.all()

    # convert to a list of dict of interesting info
    rv = []
    for user in users:
        # copy simple attributes
        userdata = {}
        for attr in attrs:
            userdata[attr] = getattr(user, attr)
        userdata["roles"] = [r.name for r in user.roles]
        rv.append(userdata)

    # users is a list of tuples - convert to list of dict
    return {"status": 200, "msgs": [], "data": rv}

Change 'sywuserdb' to your data store ('user_datastore' in your question).

This is called as part of your API - I have an 'admin' blueprint that has the following endpoint defined:

@api.route("/users", methods=["GET"])
@auth_required("token", "session")
@roles_accepted("admin")
def get_users():
    rv = get_users()
    return flask.jsonify(rv), rv["status"]

Ignore the @staticmethod - that is since I have it as part of a UserFactory class since I have a bunch of admin methods and API to manage users.

jwag
  • 662
  • 5
  • 6
  • Thank you A LOT for your answer! Where should I put this and how would I call it? I am not really familiar with decorators and not really sure where to put it. – aquatic7 May 19 '21 at 18:50