Learn

Protecting pages is the primary objective of authentication. We can leverage some very useful functions from Flask-Login to ensure our different pages or routes are protected.

One of the key pieces of code that we previously added is the LoginManager object that we initialized with our instance of the Flask application. LoginManagers have a method user_loader that needs to be defined in order to load and verify a user from our database.

@login_manager.user_loader def load_user(id): return User.query.get(int(id))
  • this method retrieves our User with an id value id from our database
  • without this function, we won’t be able to verify users on our protected routes!

Next we need to import the login_required function from flask_login at the top of our file:

from flask_login import login_required

We can now add the @login_required function as a decorator to different routes to make logging in necessary.

@app.route('/home') @login_required def home(): return render_template('logged_in.html')

The @login_required decorator will force the user to login before being able to view the page

Instructions

1.

Import the login_required function from flask_login.

2.

Add the @login_required decorator to the home endpoint so that it is only accessible when logged in.

Sign up to start coding

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?