At the moment, if you simply navigate to /secrets you can see the secret page and the download link. There are no authentication barriers. How can we make sure that only registered/logged in users can see that page and download the file?

We'll need to secure certain routes in our server and make them only accessible if a user is authenticated.

To do this, most Flask developers will use the Flask-Login package.

HARD CHALLENGE: Only allow logged-in users to download the file

Use the Flask-Login documentation to implement the /login route. The /secrets route should be secured so that it requires the user to be logged in.

You'll need to configure Flask-login and then modify the code for several routes: /register, /login, /secrets, and /download.

I recommend tackling this problem in the following order:

  1. Configure Flask-Login

  2. Log the user in upon registering

  3. Protect secrets and download routes so only logged-in users can access them

  4. Write the code for the /login and /logout routes

This is what you're aiming for:

HINT 1: You will  need to configure your Flask app to use Flask_Login.

HINT 2: You will need to create a user_loader callback.

HINT 3: Make sure you implement the UserMixin in your User class.

Note: A Mixin is simply a way to provide multiple inheritance to Python. This is how you add a Mixin:

class MyClass(MixinClassB, MixinClassA, BaseClass):

Further Reading on Mixins

HINT 4: You can check the user's password using the check_password_hash function.

HINT 5: You need to find the user by the email they entered in the login form (e.g., with a where clause).

HINT 6: If the user has successfully logged in or registered, you need to use the login_user() function to authenticate them.

HINT 7: Both the /secrets and /download route need to be secured so that only authenticated users can access them.


SOLUTION