Skip to content

Exercises

These exercises extend the login system you just built.


Exercise 1 - Register page

Right now the only way to create a user is by running seed.py manually. Build a proper register page.

Add a /register route with a form that takes a username and password. When submitted:

  • Check whether that username already exists in the database
  • If it does, show an error: "That username is already taken."
  • If it does not, create the user with generate_password_hash on the password and redirect to the login page

The form should be a plain HTML form POST, same as the login form.


Exercise 2 - Protect another route

Add a new route called /profile that shows a simple page with the logged-in user's username and a welcome message.

Protect it with @login_required. Confirm that visiting /profile while logged out sends you to the login page, and visiting it while logged in shows the page.


Exercise 3 - Personalise the home page

On home.html, show different content depending on whether the user is logged in:

  • When logged in: "Welcome back, [username]! You are logged in."
  • When not logged in: "Welcome. Please log in to access more pages."

Use {% if current_user.is_authenticated %} and {% else %} in the template.


Update base.html so that:

  • When logged out, the nav shows a Login link
  • When logged in, the nav shows the username and a Logout link

You already did this on the Protecting Routes page. Now make sure it works across all your pages - home, about, dashboard, and profile.


← Protecting Routes