~homeworkprod/byceps

ref: 4237b3ec9496efe95dcce82bea3207ab9de4d520 byceps/scripts/export_permissions_and_roles.py -rwxr-xr-x 1.7 KiB
4237b3ec — Jochen Kupperschmidt Move ticketing blueprint into `site` subpackage 1 year, 10 months ago
                                                                                
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
#!/usr/bin/env python

"""Export all permissions, roles, and their relations as JSON to STDOUT.

:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""

import json
import sys

import click

from byceps.database import db
from byceps.services.authorization.models import Permission, Role
from byceps.util.system import get_config_filename_from_env_or_exit

from _util import app_context


@click.command()
def execute():
    permissions = list(collect_permissions())
    roles = list(collect_roles())

    data = {
        'permissions': permissions,
        'roles': roles,
    }

    json.dump(data, sys.stdout, indent=2, sort_keys=True)


def collect_permissions():
    """Collect all permissions, even those not assigned to any role."""
    permissions = Permission.query \
        .options(
            db.undefer('title'),
        ) \
        .order_by(Permission.id) \
        .all()

    for permission in permissions:
        yield {
            'id': permission.id,
            'title': permission.title,
        }


def collect_roles():
    """Collect all roles and the permissions assigned to them."""
    roles = Role.query \
        .options(
            db.undefer('title'),
            db.joinedload('role_permissions'),
        ) \
        .order_by(Role.id) \
        .all()

    for role in roles:
        permission_ids = [permission.id for permission in role.permissions]
        permission_ids.sort()

        yield {
            'id': role.id,
            'title': role.title,
            'assigned_permissions': permission_ids,
        }


if __name__ == '__main__':
    config_filename = get_config_filename_from_env_or_exit()
    with app_context(config_filename):
        execute()