This is an asynchronous adapter for pycasbin using Tortoise ORM.
Supports Python 3.7+.
python3 -m pip install --user casbin-tortoise-adapter
# or via your favorite dependency manager, like PDM
The current supported databases are limited by Tortoise ORM.
The only configurable is the underlying Model used by TortoiseAdapter
. While simple, it should be plenty to cover most use cases that one could come across. You can change the model by passing the modelclass: CasbinRule
keyword argument to the adapter and updating the model in your Tortoise ORM init configuration.
The modelclass
value must inherit from casbin_tortoise_adapter.CasbinRule
to ensure that all the expected fields are present. A TypeError
will throw if this is not the case.
A custom Model, combined with advanced configuration like show in the Tortoise ORM "Two Databases" example, allow you to change where your authorization rules are stored (database, model name, etc.)
from casbin import AsyncEnforcer
from tortoise import Tortoise
from casbin_tortoise_adapter import CasbinRule, TortoiseAdapter
async def main()
# connect to db and generate schemas
await Tortoise.init(
db_url="postgres://postgres:password@test-db:5432/my_app",
modules={"models": ["casbin_tortoise_adapter"]},
)
await Tortoise.generate_schemas()
adapter = casbin_tortoise_adapter.TortoiseAdapter()
e = AsyncEnforcer('path/to/model.conf', adapter)
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
This project, like other adapters, is licensed under the Apache 2.0 License.
This package is Treeware. If you use it in production, then we ask that you buy the world a tree to thank us for our work. By contributing to my forest you’ll be creating employment for local families and restoring wildlife habitats.