0
0
Flaskframework~30 mins

Why authentication matters in Flask - See It in Action

Choose your learning style9 modes available
Why authentication matters
📖 Scenario: You are building a simple web app where users can see a secret message only if they are logged in. This helps protect private information from strangers.
🎯 Goal: Create a Flask app that stores a username and password, checks if the user is logged in, and shows a secret message only to logged-in users.
📋 What You'll Learn
Create a dictionary called users with one user: username 'admin' and password 'secret123'
Create a variable called logged_in and set it to False
Write a function called authenticate that takes username and password and returns True if they match the users dictionary
Add a route /login that sets logged_in to True if authentication succeeds
Add a route /secret that shows 'Secret message: Flask is fun!' only if logged_in is True, otherwise shows 'Please log in first.'
💡 Why This Matters
🌍 Real World
Authentication is essential to protect private data and control access in web apps.
💼 Career
Understanding basic authentication helps you build secure web applications and is a key skill for web developers.
Progress0 / 4 steps
1
Set up user data
Create a dictionary called users with one entry: username 'admin' and password 'secret123'.
Flask
Need a hint?

Use a Python dictionary with the username as key and password as value.

2
Add login status variable
Create a variable called logged_in and set it to False to track if the user is logged in.
Flask
Need a hint?

This variable will help us know if the user has logged in or not.

3
Create authentication function
Write a function called authenticate that takes username and password as parameters and returns True if the password matches the one in the users dictionary for that username, otherwise False.
Flask
Need a hint?

Use users.get(username) to get the password and compare it with the given password.

4
Add Flask routes for login and secret page
Import Flask and create an app. Add a route /login that sets logged_in to True if authenticate('admin', 'secret123') returns True. Add a route /secret that returns 'Secret message: Flask is fun!' if logged_in is True, otherwise returns 'Please log in first.'.
Flask
Need a hint?

Use @app.route decorators to create routes. Use global logged_in inside the login function to modify the variable.