Skip to content

Commit 468b40b

Browse files
committed
Add app.py
1 parent fb315f0 commit 468b40b

File tree

3 files changed

+41
-3
lines changed

3 files changed

+41
-3
lines changed

README.md

+11-3
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ pip install flask-authz
1818

1919
## Simple Example
2020

21-
This repo is just a working Flask app that shows the usage of flask-authz. To use it in your existing Flask app, you need:
21+
This repo is just a working Flask app that shows the usage of flask-authz (see: https://github.com/pycasbin/flask-authz/blob/master/app.py). To use it in your existing Flask app, you need:
2222

2323
```python
2424
from authz.middleware import CasbinMiddleware
@@ -46,9 +46,17 @@ if __name__ == '__main__':
4646
- The default policy ``authz_policy.csv`` is:
4747

4848
```csv
49+
p, alice, /dataset1/*, GET
50+
p, alice, /dataset1/resource1, POST
51+
p, bob, /dataset2/resource1, *
52+
p, bob, /dataset2/resource2, GET
53+
p, bob, /dataset2/folder1/*, POST
54+
p, dataset1_admin, /dataset1/*, *
55+
p, *, /login, *
56+
4957
p, anonymous, /, GET
50-
p, admin, *, *
51-
g, alice, admin
58+
59+
g, cathy, dataset1_admin
5260
```
5361

5462
It means ``anonymous`` user can only access homepage ``/``. Admin users like alice can access any pages. Currently all accesses are regarded as ``anonymous``. Add your authentication to let a user log in.

app.py

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
from authz.middleware import CasbinMiddleware
2+
import casbin
3+
from flask import Flask
4+
5+
app = Flask(__name__)
6+
7+
# Initialize the Casbin enforcer, load the casbin model and policy from files.
8+
# Change the 2nd arg to use a database.
9+
enforcer = casbin.Enforcer("tests/authz_model.conf", "tests/authz_policy.csv")
10+
11+
app.wsgi_app = CasbinMiddleware(app.wsgi_app, enforcer)
12+
13+
14+
@app.route("/")
15+
def hello_world():
16+
# ("anonymous", "/", "GET") ==> True, so return HTTP 200.
17+
return "Hello World!"
18+
19+
20+
@app.route('/data')
21+
def data():
22+
# ("anonymous", "/data", "GET") ==> False, so return HTTP 403.
23+
return "data"
24+
25+
26+
if __name__ == '__main__':
27+
app.run()

tests/authz_policy.csv

+3
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,7 @@ p, bob, /dataset2/resource2, GET
55
p, bob, /dataset2/folder1/*, POST
66
p, dataset1_admin, /dataset1/*, *
77
p, *, /login, *
8+
9+
p, anonymous, /, GET
10+
811
g, cathy, dataset1_admin

0 commit comments

Comments
 (0)