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.1.0.tar.gz (6.2 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.1.0-py3-none-any.whl (6.3 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: simple_python_rbac-0.1.0.tar.gz
  • Upload date:
  • Size: 6.2 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.1.0.tar.gz
Algorithm Hash digest
SHA256 9ec2461ed325165d3fba97831e8dbed9b429b79cd44cbccf562ba514701e8a5f
MD5 41ed48dae8c13bd3ba429d11b5f04724
BLAKE2b-256 5a149941e7784b35d86949742b3beb3bceee937de6916b7817dd0c5e11388702

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for simple_python_rbac-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 b2dc079b3aea585517ece835d30a6a9d9850154d57764ece299a5247415b82a8
MD5 8546db920540b3a27ae8ff50cfd6a5ab
BLAKE2b-256 a4b6e5295c3b92797e4ea10e2a16cd3c2354fd3ad61f806d4c96bf77a995f34a

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