casbin


Namecasbin JSON
Version 1.36.0 PyPI version JSON
download
home_page
SummaryAn authorization library that supports access control models like ACL, RBAC, ABAC in Python
upload_time2024-02-09 01:47:44
maintainer
docs_urlNone
author
requires_python>=3.3
licenseApache 2.0
keywords casbin acl rbac abac auth authz authorization access control permission
VCS
bugtrack_url
requirements simpleeval
Travis-CI No Travis.
coveralls test coverage
            PyCasbin
====

[![GitHub Action](https://github.com/casbin/pycasbin/workflows/build/badge.svg?branch=master)](https://github.com/casbin/pycasbin/actions)
[![Coverage Status](https://coveralls.io/repos/github/casbin/pycasbin/badge.svg)](https://coveralls.io/github/casbin/pycasbin)
[![Version](https://img.shields.io/pypi/v/casbin.svg)](https://pypi.org/project/casbin/)
[![PyPI - Wheel](https://img.shields.io/pypi/wheel/casbin.svg)](https://pypi.org/project/casbin/)
[![Pyversions](https://img.shields.io/pypi/pyversions/casbin.svg)](https://pypi.org/project/casbin/)
[![Download](https://img.shields.io/pypi/dm/casbin.svg)](https://pypi.org/project/casbin/)
[![Discord](https://img.shields.io/discord/1022748306096537660?logo=discord&label=discord&color=5865F2)](https://discord.gg/S5UjpzGZjN)

<p align="center">
  <sup>Sponsored by</sup>
  <br>
  <a href="https://stytch.com/docs?utm_source=oss-sponsorship&utm_medium=paid_sponsorship&utm_campaign=casbin">
    <picture>
      <source media="(prefers-color-scheme: dark)" srcset="https://cdn.casbin.org/img/stytch-white.png">
      <source media="(prefers-color-scheme: light)" srcset="https://cdn.casbin.org/img/stytch-charcoal.png">
      <img src="https://cdn.casbin.org/img/stytch-charcoal.png" width="275">
    </picture>
  </a><br/>
  <a href="https://stytch.com/docs?utm_source=oss-sponsorship&utm_medium=paid_sponsorship&utm_campaign=casbin"><b>Build auth with fraud prevention, faster.</b><br/> Try Stytch for API-first authentication, user & org management, multi-tenant SSO, MFA, device fingerprinting, and more.</a>
  <br>
</p>

💖 [**Looking for an open-source identity and access management solution like Okta, Auth0, Keycloak ? Learn more about: Casdoor**](https://casdoor.org/)

<a href="https://casdoor.org/"><img src="https://user-images.githubusercontent.com/3787410/147868267-6ac74908-5654-4f9c-ac79-8852af9ff925.png" alt="casdoor" style="width: 50%; height: 50%"/></a>

**News**: 🔥 How to use it with `Django` ? Try [Django Authorization](https://github.com/pycasbin/django-authorization), an authorization library for `Django` framework.

**News**: Async is now supported by Pycasbin >= 1.23.0!

**News**: still worry about how to write the correct Casbin policy? ``Casbin online editor`` is coming to help! Try it at: http://casbin.org/editor/

Casbin is a powerful and efficient open-source access control library for Python projects. It provides support for enforcing authorization based on various [access control models](https://en.wikipedia.org/wiki/Computer_security_model).

## All the languages supported by Casbin:

[![golang](https://casbin.org/img/langs/golang.png)](https://github.com/casbin/casbin) | [![java](https://casbin.org/img/langs/java.png)](https://github.com/casbin/jcasbin) | [![nodejs](https://casbin.org/img/langs/nodejs.png)](https://github.com/casbin/node-casbin) | [![php](https://casbin.org/img/langs/php.png)](https://github.com/php-casbin/php-casbin)
----|----|----|----
[Casbin](https://github.com/casbin/casbin) | [jCasbin](https://github.com/casbin/jcasbin) | [node-Casbin](https://github.com/casbin/node-casbin) | [PHP-Casbin](https://github.com/php-casbin/php-casbin)
production-ready | production-ready | production-ready | production-ready

[![python](https://casbin.org/img/langs/python.png)](https://github.com/casbin/pycasbin) | [![dotnet](https://casbin.org/img/langs/dotnet.png)](https://github.com/casbin-net/Casbin.NET) | [![c++](https://casbin.org/img/langs/cpp.png)](https://github.com/casbin/casbin-cpp) | [![rust](https://casbin.org/img/langs/rust.png)](https://github.com/casbin/casbin-rs)
----|----|----|----
[PyCasbin](https://github.com/casbin/pycasbin) | [Casbin.NET](https://github.com/casbin-net/Casbin.NET) | [Casbin-CPP](https://github.com/casbin/casbin-cpp) | [Casbin-RS](https://github.com/casbin/casbin-rs)
production-ready | production-ready | beta-test | production-ready

## Table of contents

- [Supported models](#supported-models)
- [How it works?](#how-it-works)
- [Features](#features)
- [Installation](#installation)
- [Documentation](#documentation)
- [Online editor](#online-editor)
- [Tutorials](#tutorials)
- [Get started](#get-started)
- [Policy management](#policy-management)
- [Policy persistence](#policy-persistence)
- [Role manager](#role-manager)
- [Async Enforcer](#async-enforcer)
- [Benchmarks](#benchmarks)
- [Examples](#examples)
- [Middlewares](#middlewares)
- [Our adopters](#our-adopters)

## Supported models

1. [**ACL (Access Control List)**](https://en.wikipedia.org/wiki/Access_control_list)
2. **ACL with [superuser](https://en.wikipedia.org/wiki/Superuser)**
3. **ACL without users**: especially useful for systems that don't have authentication or user log-ins.
3. **ACL without resources**: some scenarios may target for a type of resources instead of an individual resource by using permissions like ``write-article``, ``read-log``. It doesn't control the access to a specific article or log.
4. **[RBAC (Role-Based Access Control)](https://en.wikipedia.org/wiki/Role-based_access_control)**
5. **RBAC with resource roles**: both users and resources can have roles (or groups) at the same time.
6. **RBAC with domains/tenants**: users can have different role sets for different domains/tenants.
7. **[ABAC (Attribute-Based Access Control)](https://en.wikipedia.org/wiki/Attribute-Based_Access_Control)**: syntax sugar like ``resource.Owner`` can be used to get the attribute for a resource.
8. **[RESTful](https://en.wikipedia.org/wiki/Representational_state_transfer)**: supports paths like ``/res/*``, ``/res/:id`` and HTTP methods like ``GET``, ``POST``, ``PUT``, ``DELETE``.
9. **Deny-override**: both allow and deny authorizations are supported, deny overrides the allow.
10. **Priority**: the policy rules can be prioritized like firewall rules.

## How it works?

In Casbin, an access control model is abstracted into a CONF file based on the **PERM metamodel (Policy, Effect, Request, Matchers)**. So switching or upgrading the authorization mechanism for a project is just as simple as modifying a configuration. You can customize your own access control model by combining the available models. For example, you can get RBAC roles and ABAC attributes together inside one model and share one set of policy rules.

The most basic and simplest model in Casbin is ACL. ACL's model CONF is:

```ini
# Request definition
[request_definition]
r = sub, obj, act

# Policy definition
[policy_definition]
p = sub, obj, act

# Policy effect
[policy_effect]
e = some(where (p.eft == allow))

# Matchers
[matchers]
m = r.sub == p.sub && r.obj == p.obj && r.act == p.act

```

An example policy for ACL model is like:

```
p, alice, data1, read
p, bob, data2, write
```

It means:

- alice can read data1
- bob can write data2

We also support multi-line mode by appending '\\'  in the end:  

```ini
# Matchers
[matchers]
m = r.sub == p.sub && r.obj == p.obj \ 
  && r.act == p.act
```

Further more, if you are using ABAC,  you can try operator `in` like following in Casbin **golang** edition (jCasbin and Node-Casbin are not supported yet):

```ini
# Matchers
[matchers]
m = r.obj == p.obj && r.act == p.act || r.obj in ('data2', 'data3')
```

But you **SHOULD** make sure that the length of the array is **MORE** than **1**, otherwise there will cause it to panic.

For more operators, you may take a look at [govaluate](https://github.com/Knetic/govaluate)

## Features

What Casbin does:

1. enforce the policy in the classic ``{subject, object, action}`` form or a customized form as you defined, both allow and deny authorizations are supported.
2. handle the storage of the access control model and its policy.
3. manage the role-user mappings and role-role mappings (aka role hierarchy in RBAC).
4. support built-in superuser like ``root`` or ``administrator``. A superuser can do anything without explict permissions.
5. multiple built-in operators to support the rule matching. For example, ``keyMatch`` can map a resource key ``/foo/bar`` to the pattern ``/foo*``.

What Casbin does NOT do:

1. authentication (aka verify ``username`` and ``password`` when a user logs in)
2. manage the list of users or roles. I believe it's more convenient for the project itself to manage these entities. Users usually have their passwords, and Casbin is not designed as a password container. However, Casbin stores the user-role mapping for the RBAC scenario. 

## Installation

```
pip install casbin
```

## Documentation

https://casbin.org/docs/overview

## Online editor

You can also use the online editor (http://casbin.org/editor/) to write your Casbin model and policy in your web browser. It provides functionality such as ``syntax highlighting`` and ``code completion``, just like an IDE for a programming language.

## Tutorials

https://casbin.org/docs/tutorials

## Get started

1. New a Casbin enforcer with a model file and a policy file:

```python
import casbin
e = casbin.Enforcer("path/to/model.conf", "path/to/policy.csv")
```

Note: you can also initialize an enforcer with policy in DB instead of file, see [Policy persistence](#policy-persistence) section for details.

2. Add an enforcement hook into your code right before the access happens:

```python
sub = "alice"  # the user that wants to access a resource.
obj = "data1"  # the resource that is going to be accessed.
act = "read"  # the operation that the user performs on the resource.

if e.enforce(sub, obj, act):
    # permit alice to read data1
    pass
else:
    # deny the request, show an error
    pass
```

3. Besides the static policy file, Casbin also provides API for permission management at run-time. For example, You can get all the roles assigned to a user as below:

```python
roles = e.get_roles_for_user("alice")
```

See [Policy management APIs](#policy-management) for more usage.

4. Please refer to the ``tests`` files for more usage.

## Policy management

Casbin provides two sets of APIs to manage permissions:

- [Management API](https://github.com/casbin/casbin/blob/master/management_api.go): the primitive API that provides full support for Casbin policy management. See [here](https://github.com/casbin/casbin/blob/master/management_api_test.go) for examples.
- [RBAC API](https://github.com/casbin/casbin/blob/master/rbac_api.go): a more friendly API for RBAC. This API is a subset of Management API. The RBAC users could use this API to simplify the code. See [here](https://github.com/casbin/casbin/blob/master/rbac_api_test.go) for examples.

We also provide a web-based UI for model management and policy management:

![model editor](https://hsluoyz.github.io/casbin/ui_model_editor.png)

![policy editor](https://hsluoyz.github.io/casbin/ui_policy_editor.png)

## Policy persistence

https://casbin.org/docs/adapters

## Role manager

https://casbin.org/docs/role-managers

## Async Enforcer

If your code use `async` / `await` and is heavily dependent on I/O operations, you can adopt Async Enforcer!

1. Create an async engine and new a Casbin AsyncEnforcer with a model file and an async Pycasbin adapter (AsyncAdapter subclass):

```python
import asyncio
import os

import casbin
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker

from casbin_async_sqlalchemy_adapter import Adapter, CasbinRule


async def get_enforcer():
    engine = create_async_engine("sqlite+aiosqlite://", future=True)
    adapter = Adapter(engine)
    await adapter.create_table()

    async_session = sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
    async with async_session() as s:
        s.add(CasbinRule(ptype="p", v0="alice", v1="data1", v2="read"))
        s.add(CasbinRule(ptype="p", v0="bob", v1="data2", v2="write"))
        s.add(CasbinRule(ptype="p", v0="data2_admin", v1="data2", v2="read"))
        s.add(CasbinRule(ptype="p", v0="data2_admin", v1="data2", v2="write"))
        s.add(CasbinRule(ptype="g", v0="alice", v1="data2_admin"))
        await s.commit()

    e = casbin.AsyncEnforcer("path/to/model.conf", adapter)
    await e.load_policy()
    return e
```

Note: you can see all supported adapters in [Adapters | Casbin](https://casbin.org/docs/adapters).

Built-in async adapters are available in `casbin.persist.adapters.asyncio`.

2. Add an enforcement hook into your code right before the access happens:

```python
async def main():
    e = await get_enforcer()
    if e.enforce("alice", "data1", "read"):
        print("alice can read data1")
    else:
        print("alice can not read data1")
```

3. Run the code:

```python
asyncio.run(main())
```

4. Please refer to the ``tests`` files for more usage.

## Benchmarks

https://casbin.org/docs/benchmark

## Examples

Model | Model file | Policy file
----|------|----
ACL | [basic_model.conf](https://github.com/casbin/casbin/blob/master/examples/basic_model.conf) | [basic_policy.csv](https://github.com/casbin/casbin/blob/master/examples/basic_policy.csv)
ACL with superuser | [basic_model_with_root.conf](https://github.com/casbin/casbin/blob/master/examples/basic_with_root_model.conf) | [basic_policy.csv](https://github.com/casbin/casbin/blob/master/examples/basic_policy.csv)
ACL without users | [basic_model_without_users.conf](https://github.com/casbin/casbin/blob/master/examples/basic_without_users_model.conf) | [basic_policy_without_users.csv](https://github.com/casbin/casbin/blob/master/examples/basic_without_users_policy.csv)
ACL without resources | [basic_model_without_resources.conf](https://github.com/casbin/casbin/blob/master/examples/basic_without_resources_model.conf) | [basic_policy_without_resources.csv](https://github.com/casbin/casbin/blob/master/examples/basic_without_resources_policy.csv)
RBAC | [rbac_model.conf](https://github.com/casbin/casbin/blob/master/examples/rbac_model.conf)  | [rbac_policy.csv](https://github.com/casbin/casbin/blob/master/examples/rbac_policy.csv)
RBAC with resource roles | [rbac_model_with_resource_roles.conf](https://github.com/casbin/casbin/blob/master/examples/rbac_with_resource_roles_model.conf)  | [rbac_policy_with_resource_roles.csv](https://github.com/casbin/casbin/blob/master/examples/rbac_with_resource_roles_policy.csv)
RBAC with domains/tenants | [rbac_model_with_domains.conf](https://github.com/casbin/casbin/blob/master/examples/rbac_with_domains_model.conf)  | [rbac_policy_with_domains.csv](https://github.com/casbin/casbin/blob/master/examples/rbac_with_domains_policy.csv)
ABAC | [abac_model.conf](https://github.com/casbin/casbin/blob/master/examples/abac_model.conf)  | N/A
RESTful | [keymatch_model.conf](https://github.com/casbin/casbin/blob/master/examples/keymatch_model.conf)  | [keymatch_policy.csv](https://github.com/casbin/casbin/blob/master/examples/keymatch_policy.csv)
Deny-override | [rbac_model_with_deny.conf](https://github.com/casbin/casbin/blob/master/examples/rbac_with_deny_model.conf)  | [rbac_policy_with_deny.csv](https://github.com/casbin/casbin/blob/master/examples/rbac_with_deny_policy.csv)
Priority | [priority_model.conf](https://github.com/casbin/casbin/blob/master/examples/priority_model.conf)  | [priority_policy.csv](https://github.com/casbin/casbin/blob/master/examples/priority_policy.csv)

## Middlewares

Authz middlewares for web frameworks: https://casbin.org/docs/middlewares

## Our adopters

https://casbin.org/docs/adopters

## Contributors

This project exists thanks to all the people who contribute. 
<a href="https://github.com/casbin/pycasbin/graphs/contributors"><img src="https://opencollective.com/pycasbin/contributors.svg?width=890&button=false" /></a>

## Backers

Thank you to all our backers! 🙏 [[Become a backer](https://opencollective.com/casbin#backer)]

<a href="https://opencollective.com/casbin#backers" target="_blank"><img src="https://opencollective.com/casbin/backers.svg?width=890"></a>

## Sponsors

Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [[Become a sponsor](https://opencollective.com/casbin#sponsor)]

<a href="https://opencollective.com/casbin/sponsor/0/website" target="_blank"><img src="https://opencollective.com/casbin/sponsor/0/avatar.svg"></a>
<a href="https://opencollective.com/casbin/sponsor/1/website" target="_blank"><img src="https://opencollective.com/casbin/sponsor/1/avatar.svg"></a>
<a href="https://opencollective.com/casbin/sponsor/2/website" target="_blank"><img src="https://opencollective.com/casbin/sponsor/2/avatar.svg"></a>
<a href="https://opencollective.com/casbin/sponsor/3/website" target="_blank"><img src="https://opencollective.com/casbin/sponsor/3/avatar.svg"></a>
<a href="https://opencollective.com/casbin/sponsor/4/website" target="_blank"><img src="https://opencollective.com/casbin/sponsor/4/avatar.svg"></a>
<a href="https://opencollective.com/casbin/sponsor/5/website" target="_blank"><img src="https://opencollective.com/casbin/sponsor/5/avatar.svg"></a>
<a href="https://opencollective.com/casbin/sponsor/6/website" target="_blank"><img src="https://opencollective.com/casbin/sponsor/6/avatar.svg"></a>
<a href="https://opencollective.com/casbin/sponsor/7/website" target="_blank"><img src="https://opencollective.com/casbin/sponsor/7/avatar.svg"></a>
<a href="https://opencollective.com/casbin/sponsor/8/website" target="_blank"><img src="https://opencollective.com/casbin/sponsor/8/avatar.svg"></a>
<a href="https://opencollective.com/casbin/sponsor/9/website" target="_blank"><img src="https://opencollective.com/casbin/sponsor/9/avatar.svg"></a>

## License

This project is licensed under the [Apache 2.0 license](LICENSE).

## Contact

If you have any issues or feature requests, please contact us. PR is welcomed.
- https://github.com/casbin/pycasbin/issues
- techlee@qq.com
- Tencent QQ group: [546057381](//shang.qq.com/wpa/qunwpa?idkey=8ac8b91fc97ace3d383d0035f7aa06f7d670fd8e8d4837347354a31c18fac885)

            

Raw data

            {
    "_id": null,
    "home_page": "",
    "name": "casbin",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.3",
    "maintainer_email": "",
    "keywords": "casbin,acl,rbac,abac,auth,authz,authorization,access control,permission",
    "author": "",
    "author_email": "TechLee <techlee@qq.com>",
    "download_url": "https://files.pythonhosted.org/packages/7c/13/05c93880f034e916718532f2b9e59ea86ecad1c60f9dd44f73705e8e2aed/casbin-1.36.0.tar.gz",
    "platform": null,
    "description": "PyCasbin\n====\n\n[![GitHub Action](https://github.com/casbin/pycasbin/workflows/build/badge.svg?branch=master)](https://github.com/casbin/pycasbin/actions)\n[![Coverage Status](https://coveralls.io/repos/github/casbin/pycasbin/badge.svg)](https://coveralls.io/github/casbin/pycasbin)\n[![Version](https://img.shields.io/pypi/v/casbin.svg)](https://pypi.org/project/casbin/)\n[![PyPI - Wheel](https://img.shields.io/pypi/wheel/casbin.svg)](https://pypi.org/project/casbin/)\n[![Pyversions](https://img.shields.io/pypi/pyversions/casbin.svg)](https://pypi.org/project/casbin/)\n[![Download](https://img.shields.io/pypi/dm/casbin.svg)](https://pypi.org/project/casbin/)\n[![Discord](https://img.shields.io/discord/1022748306096537660?logo=discord&label=discord&color=5865F2)](https://discord.gg/S5UjpzGZjN)\n\n<p align=\"center\">\n  <sup>Sponsored by</sup>\n  <br>\n  <a href=\"https://stytch.com/docs?utm_source=oss-sponsorship&utm_medium=paid_sponsorship&utm_campaign=casbin\">\n    <picture>\n      <source media=\"(prefers-color-scheme: dark)\" srcset=\"https://cdn.casbin.org/img/stytch-white.png\">\n      <source media=\"(prefers-color-scheme: light)\" srcset=\"https://cdn.casbin.org/img/stytch-charcoal.png\">\n      <img src=\"https://cdn.casbin.org/img/stytch-charcoal.png\" width=\"275\">\n    </picture>\n  </a><br/>\n  <a href=\"https://stytch.com/docs?utm_source=oss-sponsorship&utm_medium=paid_sponsorship&utm_campaign=casbin\"><b>Build auth with fraud prevention, faster.</b><br/> Try Stytch for API-first authentication, user & org management, multi-tenant SSO, MFA, device fingerprinting, and more.</a>\n  <br>\n</p>\n\n\ud83d\udc96 [**Looking for an open-source identity and access management solution like Okta, Auth0, Keycloak ? Learn more about: Casdoor**](https://casdoor.org/)\n\n<a href=\"https://casdoor.org/\"><img src=\"https://user-images.githubusercontent.com/3787410/147868267-6ac74908-5654-4f9c-ac79-8852af9ff925.png\" alt=\"casdoor\" style=\"width: 50%; height: 50%\"/></a>\n\n**News**: \ud83d\udd25 How to use it with `Django` ? Try [Django Authorization](https://github.com/pycasbin/django-authorization), an authorization library for `Django` framework.\n\n**News**: Async is now supported by Pycasbin >= 1.23.0!\n\n**News**: still worry about how to write the correct Casbin policy? ``Casbin online editor`` is coming to help! Try it at: http://casbin.org/editor/\n\nCasbin is a powerful and efficient open-source access control library for Python projects. It provides support for enforcing authorization based on various [access control models](https://en.wikipedia.org/wiki/Computer_security_model).\n\n## All the languages supported by Casbin:\n\n[![golang](https://casbin.org/img/langs/golang.png)](https://github.com/casbin/casbin) | [![java](https://casbin.org/img/langs/java.png)](https://github.com/casbin/jcasbin) | [![nodejs](https://casbin.org/img/langs/nodejs.png)](https://github.com/casbin/node-casbin) | [![php](https://casbin.org/img/langs/php.png)](https://github.com/php-casbin/php-casbin)\n----|----|----|----\n[Casbin](https://github.com/casbin/casbin) | [jCasbin](https://github.com/casbin/jcasbin) | [node-Casbin](https://github.com/casbin/node-casbin) | [PHP-Casbin](https://github.com/php-casbin/php-casbin)\nproduction-ready | production-ready | production-ready | production-ready\n\n[![python](https://casbin.org/img/langs/python.png)](https://github.com/casbin/pycasbin) | [![dotnet](https://casbin.org/img/langs/dotnet.png)](https://github.com/casbin-net/Casbin.NET) | [![c++](https://casbin.org/img/langs/cpp.png)](https://github.com/casbin/casbin-cpp) | [![rust](https://casbin.org/img/langs/rust.png)](https://github.com/casbin/casbin-rs)\n----|----|----|----\n[PyCasbin](https://github.com/casbin/pycasbin) | [Casbin.NET](https://github.com/casbin-net/Casbin.NET) | [Casbin-CPP](https://github.com/casbin/casbin-cpp) | [Casbin-RS](https://github.com/casbin/casbin-rs)\nproduction-ready | production-ready | beta-test | production-ready\n\n## Table of contents\n\n- [Supported models](#supported-models)\n- [How it works?](#how-it-works)\n- [Features](#features)\n- [Installation](#installation)\n- [Documentation](#documentation)\n- [Online editor](#online-editor)\n- [Tutorials](#tutorials)\n- [Get started](#get-started)\n- [Policy management](#policy-management)\n- [Policy persistence](#policy-persistence)\n- [Role manager](#role-manager)\n- [Async Enforcer](#async-enforcer)\n- [Benchmarks](#benchmarks)\n- [Examples](#examples)\n- [Middlewares](#middlewares)\n- [Our adopters](#our-adopters)\n\n## Supported models\n\n1. [**ACL (Access Control List)**](https://en.wikipedia.org/wiki/Access_control_list)\n2. **ACL with [superuser](https://en.wikipedia.org/wiki/Superuser)**\n3. **ACL without users**: especially useful for systems that don't have authentication or user log-ins.\n3. **ACL without resources**: some scenarios may target for a type of resources instead of an individual resource by using permissions like ``write-article``, ``read-log``. It doesn't control the access to a specific article or log.\n4. **[RBAC (Role-Based Access Control)](https://en.wikipedia.org/wiki/Role-based_access_control)**\n5. **RBAC with resource roles**: both users and resources can have roles (or groups) at the same time.\n6. **RBAC with domains/tenants**: users can have different role sets for different domains/tenants.\n7. **[ABAC (Attribute-Based Access Control)](https://en.wikipedia.org/wiki/Attribute-Based_Access_Control)**: syntax sugar like ``resource.Owner`` can be used to get the attribute for a resource.\n8. **[RESTful](https://en.wikipedia.org/wiki/Representational_state_transfer)**: supports paths like ``/res/*``, ``/res/:id`` and HTTP methods like ``GET``, ``POST``, ``PUT``, ``DELETE``.\n9. **Deny-override**: both allow and deny authorizations are supported, deny overrides the allow.\n10. **Priority**: the policy rules can be prioritized like firewall rules.\n\n## How it works?\n\nIn Casbin, an access control model is abstracted into a CONF file based on the **PERM metamodel (Policy, Effect, Request, Matchers)**. So switching or upgrading the authorization mechanism for a project is just as simple as modifying a configuration. You can customize your own access control model by combining the available models. For example, you can get RBAC roles and ABAC attributes together inside one model and share one set of policy rules.\n\nThe most basic and simplest model in Casbin is ACL. ACL's model CONF is:\n\n```ini\n# Request definition\n[request_definition]\nr = sub, obj, act\n\n# Policy definition\n[policy_definition]\np = sub, obj, act\n\n# Policy effect\n[policy_effect]\ne = some(where (p.eft == allow))\n\n# Matchers\n[matchers]\nm = r.sub == p.sub && r.obj == p.obj && r.act == p.act\n\n```\n\nAn example policy for ACL model is like:\n\n```\np, alice, data1, read\np, bob, data2, write\n```\n\nIt means:\n\n- alice can read data1\n- bob can write data2\n\nWe also support multi-line mode by appending '\\\\'  in the end:  \n\n```ini\n# Matchers\n[matchers]\nm = r.sub == p.sub && r.obj == p.obj \\ \n  && r.act == p.act\n```\n\nFurther more, if you are using ABAC,  you can try operator `in` like following in Casbin **golang** edition (jCasbin and Node-Casbin are not supported yet):\n\n```ini\n# Matchers\n[matchers]\nm = r.obj == p.obj && r.act == p.act || r.obj in ('data2', 'data3')\n```\n\nBut you **SHOULD** make sure that the length of the array is **MORE** than **1**, otherwise there will cause it to panic.\n\nFor more operators, you may take a look at [govaluate](https://github.com/Knetic/govaluate)\n\n## Features\n\nWhat Casbin does:\n\n1. enforce the policy in the classic ``{subject, object, action}`` form or a customized form as you defined, both allow and deny authorizations are supported.\n2. handle the storage of the access control model and its policy.\n3. manage the role-user mappings and role-role mappings (aka role hierarchy in RBAC).\n4. support built-in superuser like ``root`` or ``administrator``. A superuser can do anything without explict permissions.\n5. multiple built-in operators to support the rule matching. For example, ``keyMatch`` can map a resource key ``/foo/bar`` to the pattern ``/foo*``.\n\nWhat Casbin does NOT do:\n\n1. authentication (aka verify ``username`` and ``password`` when a user logs in)\n2. manage the list of users or roles. I believe it's more convenient for the project itself to manage these entities. Users usually have their passwords, and Casbin is not designed as a password container. However, Casbin stores the user-role mapping for the RBAC scenario. \n\n## Installation\n\n```\npip install casbin\n```\n\n## Documentation\n\nhttps://casbin.org/docs/overview\n\n## Online editor\n\nYou can also use the online editor (http://casbin.org/editor/) to write your Casbin model and policy in your web browser. It provides functionality such as ``syntax highlighting`` and ``code completion``, just like an IDE for a programming language.\n\n## Tutorials\n\nhttps://casbin.org/docs/tutorials\n\n## Get started\n\n1. New a Casbin enforcer with a model file and a policy file:\n\n```python\nimport casbin\ne = casbin.Enforcer(\"path/to/model.conf\", \"path/to/policy.csv\")\n```\n\nNote: you can also initialize an enforcer with policy in DB instead of file, see [Policy persistence](#policy-persistence) section for details.\n\n2. Add an enforcement hook into your code right before the access happens:\n\n```python\nsub = \"alice\"  # the user that wants to access a resource.\nobj = \"data1\"  # the resource that is going to be accessed.\nact = \"read\"  # the operation that the user performs on the resource.\n\nif e.enforce(sub, obj, act):\n    # permit alice to read data1\n    pass\nelse:\n    # deny the request, show an error\n    pass\n```\n\n3. Besides the static policy file, Casbin also provides API for permission management at run-time. For example, You can get all the roles assigned to a user as below:\n\n```python\nroles = e.get_roles_for_user(\"alice\")\n```\n\nSee [Policy management APIs](#policy-management) for more usage.\n\n4. Please refer to the ``tests`` files for more usage.\n\n## Policy management\n\nCasbin provides two sets of APIs to manage permissions:\n\n- [Management API](https://github.com/casbin/casbin/blob/master/management_api.go): the primitive API that provides full support for Casbin policy management. See [here](https://github.com/casbin/casbin/blob/master/management_api_test.go) for examples.\n- [RBAC API](https://github.com/casbin/casbin/blob/master/rbac_api.go): a more friendly API for RBAC. This API is a subset of Management API. The RBAC users could use this API to simplify the code. See [here](https://github.com/casbin/casbin/blob/master/rbac_api_test.go) for examples.\n\nWe also provide a web-based UI for model management and policy management:\n\n![model editor](https://hsluoyz.github.io/casbin/ui_model_editor.png)\n\n![policy editor](https://hsluoyz.github.io/casbin/ui_policy_editor.png)\n\n## Policy persistence\n\nhttps://casbin.org/docs/adapters\n\n## Role manager\n\nhttps://casbin.org/docs/role-managers\n\n## Async Enforcer\n\nIf your code use `async` / `await` and is heavily dependent on I/O operations, you can adopt Async Enforcer!\n\n1. Create an async engine and new a Casbin AsyncEnforcer with a model file and an async Pycasbin adapter (AsyncAdapter subclass):\n\n```python\nimport asyncio\nimport os\n\nimport casbin\nfrom sqlalchemy.ext.asyncio import create_async_engine, AsyncSession\nfrom sqlalchemy.orm import sessionmaker\n\nfrom casbin_async_sqlalchemy_adapter import Adapter, CasbinRule\n\n\nasync def get_enforcer():\n    engine = create_async_engine(\"sqlite+aiosqlite://\", future=True)\n    adapter = Adapter(engine)\n    await adapter.create_table()\n\n    async_session = sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)\n    async with async_session() as s:\n        s.add(CasbinRule(ptype=\"p\", v0=\"alice\", v1=\"data1\", v2=\"read\"))\n        s.add(CasbinRule(ptype=\"p\", v0=\"bob\", v1=\"data2\", v2=\"write\"))\n        s.add(CasbinRule(ptype=\"p\", v0=\"data2_admin\", v1=\"data2\", v2=\"read\"))\n        s.add(CasbinRule(ptype=\"p\", v0=\"data2_admin\", v1=\"data2\", v2=\"write\"))\n        s.add(CasbinRule(ptype=\"g\", v0=\"alice\", v1=\"data2_admin\"))\n        await s.commit()\n\n    e = casbin.AsyncEnforcer(\"path/to/model.conf\", adapter)\n    await e.load_policy()\n    return e\n```\n\nNote: you can see all supported adapters in [Adapters | Casbin](https://casbin.org/docs/adapters).\n\nBuilt-in async adapters are available in `casbin.persist.adapters.asyncio`.\n\n2. Add an enforcement hook into your code right before the access happens:\n\n```python\nasync def main():\n    e = await get_enforcer()\n    if e.enforce(\"alice\", \"data1\", \"read\"):\n        print(\"alice can read data1\")\n    else:\n        print(\"alice can not read data1\")\n```\n\n3. Run the code:\n\n```python\nasyncio.run(main())\n```\n\n4. Please refer to the ``tests`` files for more usage.\n\n## Benchmarks\n\nhttps://casbin.org/docs/benchmark\n\n## Examples\n\nModel | Model file | Policy file\n----|------|----\nACL | [basic_model.conf](https://github.com/casbin/casbin/blob/master/examples/basic_model.conf) | [basic_policy.csv](https://github.com/casbin/casbin/blob/master/examples/basic_policy.csv)\nACL with superuser | [basic_model_with_root.conf](https://github.com/casbin/casbin/blob/master/examples/basic_with_root_model.conf) | [basic_policy.csv](https://github.com/casbin/casbin/blob/master/examples/basic_policy.csv)\nACL without users | [basic_model_without_users.conf](https://github.com/casbin/casbin/blob/master/examples/basic_without_users_model.conf) | [basic_policy_without_users.csv](https://github.com/casbin/casbin/blob/master/examples/basic_without_users_policy.csv)\nACL without resources | [basic_model_without_resources.conf](https://github.com/casbin/casbin/blob/master/examples/basic_without_resources_model.conf) | [basic_policy_without_resources.csv](https://github.com/casbin/casbin/blob/master/examples/basic_without_resources_policy.csv)\nRBAC | [rbac_model.conf](https://github.com/casbin/casbin/blob/master/examples/rbac_model.conf)  | [rbac_policy.csv](https://github.com/casbin/casbin/blob/master/examples/rbac_policy.csv)\nRBAC with resource roles | [rbac_model_with_resource_roles.conf](https://github.com/casbin/casbin/blob/master/examples/rbac_with_resource_roles_model.conf)  | [rbac_policy_with_resource_roles.csv](https://github.com/casbin/casbin/blob/master/examples/rbac_with_resource_roles_policy.csv)\nRBAC with domains/tenants | [rbac_model_with_domains.conf](https://github.com/casbin/casbin/blob/master/examples/rbac_with_domains_model.conf)  | [rbac_policy_with_domains.csv](https://github.com/casbin/casbin/blob/master/examples/rbac_with_domains_policy.csv)\nABAC | [abac_model.conf](https://github.com/casbin/casbin/blob/master/examples/abac_model.conf)  | N/A\nRESTful | [keymatch_model.conf](https://github.com/casbin/casbin/blob/master/examples/keymatch_model.conf)  | [keymatch_policy.csv](https://github.com/casbin/casbin/blob/master/examples/keymatch_policy.csv)\nDeny-override | [rbac_model_with_deny.conf](https://github.com/casbin/casbin/blob/master/examples/rbac_with_deny_model.conf)  | [rbac_policy_with_deny.csv](https://github.com/casbin/casbin/blob/master/examples/rbac_with_deny_policy.csv)\nPriority | [priority_model.conf](https://github.com/casbin/casbin/blob/master/examples/priority_model.conf)  | [priority_policy.csv](https://github.com/casbin/casbin/blob/master/examples/priority_policy.csv)\n\n## Middlewares\n\nAuthz middlewares for web frameworks: https://casbin.org/docs/middlewares\n\n## Our adopters\n\nhttps://casbin.org/docs/adopters\n\n## Contributors\n\nThis project exists thanks to all the people who contribute. \n<a href=\"https://github.com/casbin/pycasbin/graphs/contributors\"><img src=\"https://opencollective.com/pycasbin/contributors.svg?width=890&button=false\" /></a>\n\n## Backers\n\nThank you to all our backers! \ud83d\ude4f [[Become a backer](https://opencollective.com/casbin#backer)]\n\n<a href=\"https://opencollective.com/casbin#backers\" target=\"_blank\"><img src=\"https://opencollective.com/casbin/backers.svg?width=890\"></a>\n\n## Sponsors\n\nSupport this project by becoming a sponsor. Your logo will show up here with a link to your website. [[Become a sponsor](https://opencollective.com/casbin#sponsor)]\n\n<a href=\"https://opencollective.com/casbin/sponsor/0/website\" target=\"_blank\"><img src=\"https://opencollective.com/casbin/sponsor/0/avatar.svg\"></a>\n<a href=\"https://opencollective.com/casbin/sponsor/1/website\" target=\"_blank\"><img src=\"https://opencollective.com/casbin/sponsor/1/avatar.svg\"></a>\n<a href=\"https://opencollective.com/casbin/sponsor/2/website\" target=\"_blank\"><img src=\"https://opencollective.com/casbin/sponsor/2/avatar.svg\"></a>\n<a href=\"https://opencollective.com/casbin/sponsor/3/website\" target=\"_blank\"><img src=\"https://opencollective.com/casbin/sponsor/3/avatar.svg\"></a>\n<a href=\"https://opencollective.com/casbin/sponsor/4/website\" target=\"_blank\"><img src=\"https://opencollective.com/casbin/sponsor/4/avatar.svg\"></a>\n<a href=\"https://opencollective.com/casbin/sponsor/5/website\" target=\"_blank\"><img src=\"https://opencollective.com/casbin/sponsor/5/avatar.svg\"></a>\n<a href=\"https://opencollective.com/casbin/sponsor/6/website\" target=\"_blank\"><img src=\"https://opencollective.com/casbin/sponsor/6/avatar.svg\"></a>\n<a href=\"https://opencollective.com/casbin/sponsor/7/website\" target=\"_blank\"><img src=\"https://opencollective.com/casbin/sponsor/7/avatar.svg\"></a>\n<a href=\"https://opencollective.com/casbin/sponsor/8/website\" target=\"_blank\"><img src=\"https://opencollective.com/casbin/sponsor/8/avatar.svg\"></a>\n<a href=\"https://opencollective.com/casbin/sponsor/9/website\" target=\"_blank\"><img src=\"https://opencollective.com/casbin/sponsor/9/avatar.svg\"></a>\n\n## License\n\nThis project is licensed under the [Apache 2.0 license](LICENSE).\n\n## Contact\n\nIf you have any issues or feature requests, please contact us. PR is welcomed.\n- https://github.com/casbin/pycasbin/issues\n- techlee@qq.com\n- Tencent QQ group: [546057381](//shang.qq.com/wpa/qunwpa?idkey=8ac8b91fc97ace3d383d0035f7aa06f7d670fd8e8d4837347354a31c18fac885)\n",
    "bugtrack_url": null,
    "license": "Apache 2.0",
    "summary": "An authorization library that supports access control models like ACL, RBAC, ABAC in Python",
    "version": "1.36.0",
    "project_urls": {
        "Home-page": "https://github.com/casbin/pycasbin"
    },
    "split_keywords": [
        "casbin",
        "acl",
        "rbac",
        "abac",
        "auth",
        "authz",
        "authorization",
        "access control",
        "permission"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "240997d202545f37d6aa3b92dafb3672f9ab1be7bc05a66ad16dc7360aa3fcfe",
                "md5": "91e4c81a50ba6dff373e8bbd5318bcb7",
                "sha256": "bb15d27a3d3e6d25411c954b283a509524977f94ae51af8ef3af88be20b1adb2"
            },
            "downloads": -1,
            "filename": "casbin-1.36.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "91e4c81a50ba6dff373e8bbd5318bcb7",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.3",
            "size": 471112,
            "upload_time": "2024-02-09T01:47:41",
            "upload_time_iso_8601": "2024-02-09T01:47:41.715306Z",
            "url": "https://files.pythonhosted.org/packages/24/09/97d202545f37d6aa3b92dafb3672f9ab1be7bc05a66ad16dc7360aa3fcfe/casbin-1.36.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "7c1305c93880f034e916718532f2b9e59ea86ecad1c60f9dd44f73705e8e2aed",
                "md5": "ab18e40ad7573e205f86db1aa5ebef3f",
                "sha256": "f43511eed6d3cd05c89c19289f9cebf899ce9e13ed4eaa9316716f8ad34ffd81"
            },
            "downloads": -1,
            "filename": "casbin-1.36.0.tar.gz",
            "has_sig": false,
            "md5_digest": "ab18e40ad7573e205f86db1aa5ebef3f",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.3",
            "size": 420992,
            "upload_time": "2024-02-09T01:47:44",
            "upload_time_iso_8601": "2024-02-09T01:47:44.811450Z",
            "url": "https://files.pythonhosted.org/packages/7c/13/05c93880f034e916718532f2b9e59ea86ecad1c60f9dd44f73705e8e2aed/casbin-1.36.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-02-09 01:47:44",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "casbin",
    "github_project": "pycasbin",
    "travis_ci": false,
    "coveralls": true,
    "github_actions": true,
    "requirements": [
        {
            "name": "simpleeval",
            "specs": [
                [
                    ">=",
                    "0.9.11"
                ]
            ]
        }
    ],
    "lcname": "casbin"
}
        
Elapsed time: 0.18948s