lingthio / Flask-User

Customizable User Authorization & User Management: Register, Confirm, Login, Change username/password, Forgot password and more.
http://flask-user.readthedocs.io/
MIT License
1.06k stars 294 forks source link

give permission to the exact role? #265

Open bestspang opened 5 years ago

bestspang commented 5 years ago

I'm really new to Flask and use it as learning tools and find Flask-User really fascinating! So, this is how to verify user as a authenticated user right? But How you make the content avalible for a user with specific Role?

{% block content %}
{% if current_user.is_authenticated %}
<a href={{ url_for('home_page') }}>{%trans%}admin{%endtrans%}</a>
{% endif %}
{% endblock %}

for specific username, it's work fine. {% if current_user.username == 'myusername' %} but with current_user.roles it returns some SQLAlchemy object which is uncomparable. i go aroung with Jinja2 and Flask-login doesn't seen to have a way, please help!

bestspang commented 5 years ago

I adding this to UserModel and it's to work when a user in log-in.

def has_roles(self, *args):
    return set(args).issubset({role.name for role in self.roles})

But got this error when the user log out: flask_login.AnonymousUserMixin object' has no attribute has_roles

So the only option now would be by pure Jinja2:

{% for role in current_user.roles %}
        {% if role.name == 'admin' %}
        <a href={{ url_for('admin_page') }}>{%trans%}Admin{%endtrans%}</a>
        {% endif %}
        {% endfor %}

and it's work well. i hope there is a better way rather than this.