Issue
I'm using flask and mongodb, I have a user table where it has a boolean attribute is_admin and I want to make specefic views and routes accessible only for admin users, I have read about Flask-admin and Flask-Principal but they seemed complicated to me since I am very beginner and its just a school project, is there a way to achieve that without using Flask-Principle?. for example I want only admin to access this route
@users.route('/add', methods=['GET', 'POST'])
@login_required
def add():
form = UserForm(request.form)
if request.method == 'POST':
if form.validate():
user = User(username=form.username.data, password= generate_password_hash(form.password.data), vorname=form.vorname.data, nachname=form.nachname.data, geburtsdatum=form.geburtsdatum.data, email=form.email.data, admin=form.admin.data, aktiv=form.aktiv.data)
user.save()
flash("user added successfully.", "success")
return redirect(url_for('.index'))
return render_template('form.html', users=users, form=form, info=session)
Solution
If I understand your question correctly, something like this might be what you're looking for:
from flask_login import current_user
# use the suggested pattern to login user then..
@users.route('/add', methods=['GET', 'POST'])
@login_required
def add():
if not current_user.is_admin:
abort(403)
# rest of your route
This will return HTTP 403 - Forbidden
as per wikipedia:
The HTTP 403 is a HTTP status code meaning access to the requested resource is forbidden. The server understood the request, but will not fulfill it.
Answered By - TekkSparrow
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.