Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add usage instructions, example code to README #6

Merged
merged 1 commit into from
Apr 24, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,60 @@ This is an Adapter for [PyCasbin](https://github.com/casbin/pycasbin) that imple
pip install casbin_databases_adapter
```

## Simple Example

```python
import casbin_databases_adapter
import casbin
from databases import Database
import sqlalchemy
from sqlalchemy import Table, Column, String, Integer
from sqlalchemy.sql.ddl import CreateTable
import asyncio

DATABASE_URL = "sqlite+aiosqlite:///example.db"

async def create_casbin_rule_table(db: Database):
metadata = sqlalchemy.MetaData()
table = Table(
"casbin_rules",
metadata,
Column("id", Integer, primary_key=True),
Column("ptype", String(255)),
Column("v0", String(255)),
Column("v1", String(255)),
Column("v2", String(255)),
Column("v3", String(255)),
Column("v4", String(255)),
Column("v5", String(255)),
)
q = CreateTable(table)
await db.execute(query=str(q))
return table

async def main():
database = Database(DATABASE_URL)
await database.connect()
casbin_rule_table = await create_casbin_rule_table(database)
adapter = casbin_databases_adapter.DatabasesAdapter(db=database, table=casbin_rule_table)

e = casbin.Enforcer('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

# run the main function
asyncio.run(main())
```

### Getting Help

- [PyCasbin](https://github.com/casbin/pycasbin)
Expand Down
Loading