So I'm creating a simple website in flask that allows two types of users. Admin and regular users. I have a class called "User" which has an attribute "isUser". I then have a route call "addMovie" which takes in a parameter "isUser" to check to see if the current user has the rights to add a movie. How do I check that? As of right now, I user that has that attribute set to "Yes" can still add a movie.
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
first_name = db.Column(db.String(120))
last_name = db.Column(db.String(120))
email = db.Column(db.String(180), unique=True)
password = db.Column(db.String(255))
isUser = db.Column(db.String(10))
active = db.Column(db.Boolean())
confirmed_at = db.Column(db.DateTime())
roles = db.relationship('Role', secondary=roles_users,backref=db.backref('users', lazy='dynamic'))
@app.route('/addMovie/<isUser>', methods=['GET', 'POST'])
@login_required
def addMovie(isUser):
error = None
if(isUser == "Yes"):
error = "You must have Admin Privaledges to add a Movie/TV Show"
return redirect(url_for('index'))
else:
return render_template('addMovie.html', error=error)
I assume you are using Flask-Login. Have you tried current_user?
Then you can check if the current logged in user is an admin or not. Finally call this method where admin functionalities is required.
from flask_login import current_user, login_required, LoginManager
@login_manager.user_loader
def load_user(id):
return User.query.get(int(id))
def require_admin():
if current_user.isUser:
abort(403)
@app.errorhandler(403)
def error_access_forbidden(error):
error_code = 403
error_message = "Sorry, access denied or forbidden!"
return render_template('4xx.html',
error_code = error_code,
error_message=error_message), 403
@app.route('/addMovie', methods=['GET', 'POST'])
@login_required
def addMovie():
require_admin()
error = None
return render_template('addMovie.html', error=error)
The 4xx.html template may show the error code, error message and links for redirection. It is the right approach to handle the HTTP errors. You may implement other HTTP errors also.
Here is a sample error page that I have used one of my project:

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With