0
0
Flaskframework~30 mins

Login_required decorator in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
Login_required decorator
📖 Scenario: You are building a simple Flask web app that has some pages only accessible to logged-in users.To protect these pages, you want to create a login_required decorator that checks if a user is logged in before allowing access.
🎯 Goal: Create a login_required decorator in Flask that redirects users to the login page if they are not logged in.Use this decorator on a protected route to ensure only logged-in users can see it.
📋 What You'll Learn
Create a Flask app with a route /dashboard that requires login
Create a login_required decorator that checks if session['logged_in'] is true
If not logged in, redirect to /login
Use the decorator on the /dashboard route
💡 Why This Matters
🌍 Real World
Web apps often need to restrict access to certain pages only to logged-in users. This decorator pattern helps keep code clean and reusable.
💼 Career
Understanding how to protect routes and manage user sessions is a key skill for backend web developers working with Flask or similar frameworks.
Progress0 / 4 steps
1
Set up Flask app and session
Import Flask and create an app instance called app. Set a secret key 'secret123' for sessions.
Flask
Need a hint?

Remember to import Flask and create the app variable.

2
Create the login_required decorator
Define a function called login_required that takes a function f as argument. Inside, define a wrapper function decorated_function that checks if session.get('logged_in') is true. If not, return redirect(url_for('login')). Otherwise, return f(). Use functools.wraps(f) to preserve function metadata. Return decorated_function from login_required.
Flask
Need a hint?

Use functools.wraps and check session.get('logged_in').

3
Create the protected dashboard route
Create a route /dashboard using @app.route('/dashboard'). Define a function dashboard decorated with @login_required. Return the string 'Welcome to your dashboard!' from this function.
Flask
Need a hint?

Use @app.route('/dashboard') and decorate with @login_required.

4
Add a simple login route to set session
Create a route /login using @app.route('/login'). Define a function login that sets session['logged_in'] = True and returns the string 'You are now logged in.'.
Flask
Need a hint?

Create a simple login route that sets session['logged_in'] to True.