Building Role-Based Access Control in Flask

Tutorial 5 of 5

1. Introduction

In this tutorial, we will explore how to implement Role-Based Access Control (RBAC) in a Flask application. RBAC is a system that restricts access to certain parts of your application based on the roles assigned to individual users.

By the end of this tutorial, you will be able to:
- Understand the concept and importance of RBAC
- Implement RBAC in a Flask application
- Control user access based on roles

Prerequisites:
- Basic knowledge of Python
- Familiarity with Flask web framework
- Knowledge of SQL databases (we'll use SQLite)

2. Step-by-Step Guide

RBAC is built on the premise that you can create roles, assign them to users, and also attach permissions to these roles. With this, you can easily manage who has access to what in your application.

Step 1: Install Flask and Flask-SQLAlchemy

pip install Flask Flask-SQLAlchemy

Step 2: Set up database models for User and Roles

from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash

db = SQLAlchemy()

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    password_hash = db.Column(db.String(120), nullable=False)
    role_id = db.Column(db.Integer, db.ForeignKey('role.id'), nullable=False)
    role = db.relationship('Role', backref=db.backref('users', lazy=True))

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

class Role(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), unique=True, nullable=False)
    permissions = db.Column(db.String(120), nullable=False)

Step 3: Create a decorator to check permissions

from functools import wraps
from flask import g, request, redirect, url_for, abort

def permission_required(permission):
    def decorator(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            if not g.current_user.role or permission not in g.current_user.role.permissions:
                abort(403)
            return f(*args, **kwargs)
        return decorated_function
    return decorator

3. Code Examples

Consider a scenario where you have two roles: admin and user. The admin can read and write while the user can only read.

admin = Role(name='admin', permissions='read,write')
user = Role(name='user', permissions='read')
db.session.add(admin)
db.session.add(user)
db.session.commit()

Now, let's assign the admin role to a new user:

new_user = User(username='testuser')
new_user.set_password('testpassword')
new_user.role = admin
db.session.add(new_user)
db.session.commit()

To use the permission_required decorator, simply add it before your routes:

@app.route('/admin')
@permission_required('write')
def admin_page():
    return 'Admin Page'

If a user with only read permission tries to access this page, they will receive a 403 Forbidden error.

4. Summary

In this tutorial, we've looked into how to set up Role-Based Access Control (RBAC) in a Flask application. We've seen how roles can be created and assigned to users, and how permissions can be checked using a decorator.

Next, you can try to extend this by adding more roles and permissions, or by implementing a system to change a user's role.

Additional resources:
- Flask Documentation
- SQLAlchemy Documentation

5. Practice Exercises

  1. Add a new role that can only write and assign it to a new user.
  2. Implement a route that can only be accessed by users with read and write permissions.
  3. Try to access the route implemented in exercise 2 with a user that only has read permission.

Solutions

write_only = Role(name='write_only', permissions='write')
db.session.add(write_only)
write_user = User(username='write_user')
write_user.set_password('write_password')
write_user.role = write_only
db.session.add(write_user)
db.session.commit()
@app.route('/readwrite')
@permission_required('read')
@permission_required('write')
def readwrite_page():
    return 'Read-Write Page'
  1. If you try to access the /readwrite page with a user that only has read permission, you will get a 403 Forbidden error.