Skip to main content

A simple, hierarchical Role-Based Access Control (RBAC) package for Python.

Project description

Simple Python RBAC

A lightweight, hierarchical Role-Based Access Control (RBAC) package for Python. It is designed to be framework-agnostic, with no third-party dependencies.

Features

  • Hierarchical Permissions: Supports wildcards (e.g., app.* matches app.home, app.settings).
  • Framework Agnostic: Easy integration with Streamlit, Flask, FastAPI, etc.
  • Generic Decorators: Protect functions with simple decorators.
  • Object-Level Restrictions: Hooks to implement data-level security.
  • Zero Dependencies: Pure Python, no external requirements.

Installation

You can install the package directly from the source directory:

pip install .

Or from PyPI (once published):

pip install simple-python-rbac

Core Concepts

1. Defining Permissions

Use the Permissions class to organize your permissions hierarchically.

from simple_python_rbac import Permissions

class AppPermissions(Permissions):
    class Documents:
        _prefix = "docs"
        VIEW = f"{_prefix}.view"
        EDIT = f"{_prefix}.edit"
        DELETE = f"{_prefix}.delete"
    
    class Admin:
        ALL = "admin.*"

2. Configuring Roles

Roles are defined by a name and a list of permissions.

from simple_python_rbac import RBACManager

rbac = RBACManager()

roles = [
    {
        "role_name": "viewer",
        "permissions": ["docs.view"]
    },
    {
        "role_name": "editor",
        "permissions": ["docs.*"]
    },
    {
        "role_name": "admin",
        "permissions": ["*"]
    }
]

rbac.set_roles(roles)

3. Current Role Provider

You must tell the manager how to find the current user's role.

# Example for a simple script
rbac.set_current_role_provider(lambda: "viewer")

Overloading Object Restrictions

One of the powerful features of simple-python-rbac is the ability to define restrictions on objects based on roles. To do this, you can inherit from RBACManager and override the get_object_restrictions method.

from simple_python_rbac import RBACManager

class MyRBACManager(RBACManager):
    def get_object_restrictions(self, role_name: str, object_type: str):
        """
        Returns a filter or a set of rules for the given object type.
        """
        if object_type == "document":
            if role_name == "viewer":
                return {"status": "published"}
            if role_name == "editor":
                return {"owner_id": 123} # example: only their own docs
        return None

rbac = MyRBACManager()
# ... set roles and provider ...

# Use it in your code:
restrictions = rbac.get_object_restrictions("viewer", "document")
# Use 'restrictions' to filter your database query

Framework Examples

Streamlit Example

import streamlit as st
from simple_python_rbac import RBACManager

rbac = RBACManager()
# Configure roles...
rbac.set_current_role_provider(lambda: st.session_state.get("user_role"))

def on_rbac_fail(permission):
    st.error(f"⛔ Access Denied: You need '{permission}' permission.")
    st.stop()

@rbac.require("docs.edit", on_fail=on_rbac_fail)
def edit_document():
    st.write("Editing document...")

if st.button("Edit"):
    edit_document()

Flask Example

from flask import Flask, abort, g
from simple_python_rbac import RBACManager

app = Flask(__name__)
rbac = RBACManager()

# Configure roles...
rbac.set_current_role_provider(lambda: getattr(g, "user_role", None))

def on_flask_fail(permission):
    abort(403)

@app.route("/edit")
@rbac.require("docs.edit", on_fail=on_flask_fail)
def edit():
    return "Editing document..."

Running Tests

python -m unittest discover tests

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

simple_python_rbac-0.2.0.tar.gz (8.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

simple_python_rbac-0.2.0-py3-none-any.whl (7.8 kB view details)

Uploaded Python 3

File details

Details for the file simple_python_rbac-0.2.0.tar.gz.

File metadata

  • Download URL: simple_python_rbac-0.2.0.tar.gz
  • Upload date:
  • Size: 8.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.7

File hashes

Hashes for simple_python_rbac-0.2.0.tar.gz
Algorithm Hash digest
SHA256 b2b1df0ea7123c8b89cd075dcbc7f25f6ee4761403ae866982a5ce581dcc4f20
MD5 3e2372abce916a466e5c0fc8667305e1
BLAKE2b-256 002591e05e4ec34347e4515288140da1fb09f4be56a972e9779f778e242ec8ef

See more details on using hashes here.

File details

Details for the file simple_python_rbac-0.2.0-py3-none-any.whl.

File metadata

File hashes

Hashes for simple_python_rbac-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 0eea85f2897a1fd0b8c703bddb344161b906af06a987344cb9fb8dec3cd95ea7
MD5 5a2d1faec886bf66ceaed5bc6e231ef4
BLAKE2b-256 7112283a7f0b83e3a7340206eca2535f9758ff41f0ccf817d6a051bcf981cfc9

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page