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 292 forks source link

Remove Role #244

Closed Chaostheorie closed 4 years ago

Chaostheorie commented 5 years ago

There is no way to remove a user role with the API and the role based system.

bmarsh9 commented 4 years ago

Hi there, you can remove roles by using this:

# Querying Role and User table with the ID, add a filter if you want to find the record by name
user = User.query.get(<user_id>) # or User.query.filter(User.email == email).first()
role = Role.query.get(<role_id>)
user.roles.remove(role)
db.session.commit()
carissableker commented 2 years ago

Some more complete code in case it's helpful for future...

Caveat:

Use jinja2 to fill in the user id and role if you wish.

@app.route('/user/remove_role/<int:id>/<string:role_name>')
@login_required
@roles_required('admin')
def remove_role(id, role_name):
    try:
        user = current_app.user_manager.db_manager.get_user_by_id(id)
        role = current_app.user_manager.db_manager.db_adapter.find_first_object(Role, name=role_name)
        user.roles.remove(role)
        current_app.user_manager.db_manager.commit()

        flash(f"User {user.first_name} {user.last_name} removed as {role_name}. ")
        return redirect(url_for('admin.admin_page'))

    except Exception as e:
        flash(f"User not found. ")
        return redirect(url_for('admin.admin_page'))

@app.route('/user/add_curator/<int:id>/<string:role_name>')
@login_required
@roles_required('curator')
def add_role(id, role_name):
    try:
        user = current_app.user_manager.db_manager.get_user_by_id(id)

        current_app.user_manager.db_manager.add_user_role(user, rolel_name)
        current_app.user_manager.db_manager.commit()

        flash(f"User {user.first_name} {user.last_name} made {role_name}. ")
        return redirect(url_for('admin.admin_page'))

    except Exception as e:
        flash(f"Something went wrong. ")
        return redirect(url_for('admin.admin_page'))

In the html add buttons (replacing "some role here" with actual role, and "user id" with actual user id):

<a type="submit" class="btn btn-default btn-danger" href="{{ url_for('remove_role', id="user id", role="some role here") }}">Remove</a>
<a type="submit" class="btn btn-default btn-success" href="{{ url_for('add_role, id="user id", role="some role here") }}">Add</a>