Skip to main content

Simple RBAC

This is a simple role based access control utility in Python.

Quick Start

1. Install Simple RBAC

pip install simple-rbac

2. Create a Access Control List

import rbac.acl

acl = rbac.acl.Registry()

3. Register Roles and Resources

acl.add_role("member")
acl.add_role("student", ["member"])
acl.add_role("teacher", ["member"])
acl.add_role("junior-student", ["student"])

acl.add_resource("course")
acl.add_resource("senior-course", ["course"])

4. Add Rules

acl.allow("member", "view", "course")
acl.allow("student", "learn", "course")
acl.allow("teacher", "teach", "course")
acl.deny("junior-student", "learn", "senior-course")

5. Use It to Check Permission

if acl.is_allowed("student", "view", "course"):
    print("Students chould view courses.")
else:
    print("Students chould not view courses.")

if acl.is_allowed("junior-student", "learn", "senior-course"):
    print("Junior students chould learn senior courses.")
else:
    print("Junior students chould not learn senior courses.")

Custom Role and Resource Class

It’s not necessary to use string as role object and resource object like “Quick Start”. You could define role class and resource class of yourself, such as a database mapped model in SQLAlchemy.

Whatever which role class and resource class you will use, it must implement __hash__ method and __eq__ method to be hashable.

Example

class Role(db.Model):
    """The role."""

    id = db.Column(db.Integer, primary_key=True)
    screen_name = db.Column(db.Unicode, nullable=False, unique=True)

    def __hash__(self):
        return hash("ROLE::%d" % self.id)

    def __eq__(self, other):
        return self.id == other.id


class Resource(db.Model):
    """The resource."""

    id = db.Column(db.Integer, primary_key=True)
    screen_name = db.Column(db.Unicode, nullable=False, unique=True)

    def __hash__(self):
        return hash("RESOURCE::%d" % self.id)

    def __eq__(self, other):
        return self.id == other.id

Of course, You could use the built-in hashable types too, such as tuple, namedtuple, frozenset and more.

Use the Identity Context Check Your Permission

Obviously, the work of checking permission is a cross-cutting concern. The module named rbac.context, our IdentityContext, provide some ways to make our work neater.

1. Create the Context Manager

acl = Registry()
context = IdentityContext(acl)

2. Set a Loader

The loader should load the roles of current user.

from myapp import get_current_user

@context.set_roles_loader
def second_load_roles():
    user = get_current_user()
    yield "everyone"
    for role in user.roles:
        yield str(role)

3. Protect Your Action

Now you could protect your action from unauthorized access. As you please, you could choose many ways to check the permission, including python decorator, python with statement or simple method calling.

Decorator

@context.check_permission("view", "article", message="can't view")
def article_page():
    return "your-article"

With Statement

def article_page():
    with context.check_permission("view", "article", message="can't view"):
        return "your-article"

Simple Method Calling

def article_page():
    context.check_permission("view", "article", message="can't view").check()
    return "your-article"

Exception Handler and Non-Zero Checking

Whatever which way you choosen, a exception rbac.context.PermissionDenied will be raised while a unauthorized access happening. The keyword arguments sent to the context.check_permission will be set into a attirbute named kwargs of the exception. You could get those data in your exception handler.

@context.check_permission("view", "article", message="can not view")
def article_page():
    return "your-article"

try:
    print article_page()
except PermissionDenied as exception:
    print "The access has been denied, you %s" % exception.kwargs['message']

If you don’t want to raise the exception but only check the access is allowed or not, you could use the checking like a boolean value.

if not context.check_permission("view", "article"):
    print "Oh! the access has been denied."

is_allowed = bool(context.check_permission("view", "article"))

Metadata

Release files for simple-rbac 0.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for simple-rbac 0.1.1
File Size Uploaded Provenance
simple-rbac-0.1.1.zip 11.9 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for simple-rbac 0.1.1
File Interpreter ABI Platform
simple-rbac-0.1.1.win-amd64.exe Details

Total release size: 248.1 kB

Release files / simple-rbac-0.1.1.zip

Download URL simple-rbac-0.1.1.zip
Size 11.9 kB
Tags Source
SHA-256 checksum
How to use checksums
e740e793fd4db759ad786ab6ec8b4e97fa0db43ca65f91e2570e2621044e3ad3
BLAKE2b-256 checksum
How to use checksums
19490ebe7834f85e781c4e0a1edbc99b444707dbe7d6e1789cd1fa99291481bd
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No

Release files / simple-rbac-0.1.1.win-amd64.exe

Download URL simple-rbac-0.1.1.win-amd64.exe
Size 236.2 kB
Tags Source
SHA-256 checksum
How to use checksums
d0489c11afc775a02f32a20b7e74c79f20ec217f725d739bdc2ff2a3f21699b8
BLAKE2b-256 checksum
How to use checksums
24bdbe82023accf80e7a714a0b1107383c0eef2cd9ce33d128762178672403d1
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No

Security for simple-rbac 0.1.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

Release history Release notifications | RSS feed

This release

0.1.1 This release

2 release files No provenance

0.1

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page