-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathorgs.py
80 lines (68 loc) · 2.39 KB
/
orgs.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
from flask import Blueprint, g, request, jsonify
from typing import cast
from werkzeug.exceptions import Forbidden, NotFound
from ..models import Organization
from .authorization import actions, authorize, list_resources, oso, get, cache, tell
bp = Blueprint("orgs", __name__, url_prefix="/orgs")
@bp.route("", methods=["GET"])
def index():
authorized_ids = list_resources("read", "Organization")
if authorized_ids and authorized_ids[0] == "*":
orgs = g.session.query(Organization).order_by(Organization.id)
return jsonify([o.as_json() for o in orgs])
else:
orgs = (
g.session.query(Organization)
.filter(Organization.id.in_(authorized_ids))
.order_by(Organization.id)
)
return jsonify([o.as_json() for o in orgs])
@bp.route("", methods=["POST"])
def create():
payload = cast(dict, request.get_json(force=True))
if (
g.session.query(Organization)
.filter(Organization.name == payload["name"])
.first()
is not None
):
return "Organization with that name already exists", 400
org = Organization(**payload)
if not authorize("create", "Organization"):
raise Forbidden
g.session.add(org)
g.session.commit()
tell("has_role", g.current_user, "admin", org)
return org.as_json(), 201 # type: ignore
@bp.route("/<int:org_id>", methods=["GET"])
def show(org_id):
if not authorize("read", {"type": "Organization", "id": org_id}):
raise NotFound
org = g.session.get_or_404(Organization, id=org_id)
json = org.as_json()
json["permissions"] = actions(org)
return json
@bp.route("/<int:org_id>", methods=["DELETE"])
def delete(org_id):
if not authorize("read", {"type": "Organization", "id": org_id}):
raise NotFound
if not authorize("delete", {"type": "Organization", "id": org_id}):
raise Forbidden
org = g.session.get_or_404(Organization, id=org_id)
g.session.delete(org)
g.session.commit()
return "deleted", 204
@bp.route("/<int:org_id>/user_count", methods=["GET"])
@cache.memoize()
def user_count(org_id):
if not authorize("read", {"type": "Organization", "id": str(org_id)}):
raise NotFound
org_users = get(
"has_role",
{
"type": "User",
},
{},
{"type": "Organization", "id": str(org_id)},
)
return str(len(list(org_users)))