0
0
Flaskframework~30 mins

Permission checking in routes in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
Permission checking in routes
📖 Scenario: You are building a simple web app using Flask. Some pages should only be accessible to users with certain permissions. You want to check these permissions inside your route functions to keep your app secure.
🎯 Goal: Create a Flask app with a dictionary of users and their permissions. Then add a route that checks if the current user has permission before showing the page.
📋 What You'll Learn
Create a dictionary called users with usernames as keys and permission lists as values
Create a variable called current_user to represent the logged-in user
Write a route function /dashboard that checks if current_user has the 'view_dashboard' permission
Return a message 'Access granted to dashboard' if permission is present, otherwise 'Access denied'
💡 Why This Matters
🌍 Real World
Permission checks in routes are essential for web apps to control who can see or do what. This keeps user data safe and the app secure.
💼 Career
Backend developers often write permission checks in routes to enforce security rules. Understanding this helps you build secure web applications.
Progress0 / 4 steps
1
Create users dictionary
Create a dictionary called users with these exact entries: 'alice': ['view_dashboard', 'edit_profile'], 'bob': ['edit_profile'], and 'carol': ['view_dashboard'].
Flask
Need a hint?

Use curly braces {} to create the dictionary. Each key is a username string, and each value is a list of permission strings.

2
Set current user
Create a variable called current_user and set it to the string 'alice' to represent the logged-in user.
Flask
Need a hint?

Just assign the string 'alice' to the variable current_user.

3
Create dashboard route with permission check
Import Flask and request from flask. Create a Flask app called app. Then write a route function for /dashboard that checks if 'view_dashboard' is in users[current_user]. If yes, return 'Access granted to dashboard'. Otherwise, return 'Access denied'.
Flask
Need a hint?

Use @app.route('/dashboard') to create the route. Inside the function, check if 'view_dashboard' is in the list of permissions for current_user.

4
Run the Flask app
Add the code to run the Flask app only if this file is the main program. Use app.run(debug=True) inside the if __name__ == '__main__': block.
Flask
Need a hint?

This code makes sure the Flask app runs only when you run this file directly.