0
0
Flaskframework~30 mins

Role-based access control in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
Role-based access control
📖 Scenario: You are building a simple web app where users have different roles like 'admin' and 'user'. You want to control which pages each role can see.
🎯 Goal: Create a Flask app that stores user roles, checks the role before showing a page, and only allows admins to see the admin page.
📋 What You'll Learn
Create a dictionary called users with usernames as keys and roles as values
Create a variable called current_user to simulate the logged-in user
Write a function check_access(role) that returns true if current_user has the given role
Use @app.route to create two pages: '/' for all users and '/admin' only for admins
💡 Why This Matters
🌍 Real World
Role-based access control is used in websites and apps to show or hide pages based on who is logged in, like admins managing content and users viewing it.
💼 Career
Understanding role-based access control is important for backend developers and web developers to secure parts of applications and manage user permissions.
Progress0 / 4 steps
1
Set up user roles dictionary
Create a dictionary called users with these exact entries: 'alice': 'admin', 'bob': 'user', 'carol': 'user'.
Flask
Need a hint?

Think of users as a list of people with their roles.

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

This variable tells the app who is currently using it.

3
Create access check function
Write a function called check_access(role) that returns True if the current_user has the given role, otherwise False. Use the users dictionary to find the role.
Flask
Need a hint?

Use users.get(current_user) to get the role of the logged-in user.

4
Create Flask routes with role checks
Import Flask and abort from flask. Create a Flask app called app. Add two routes: @app.route('/') that returns 'Welcome, user!' for all users, and @app.route('/admin') that returns 'Welcome, admin!' only if check_access('admin') is true, otherwise abort with 403.
Flask
Need a hint?

Use abort(403) to block access if the user is not an admin.