~homeworkprod/byceps

ref: 90357856fb25b54d9e60125d1b658be3514449ae byceps/scripts/create_initial_admin_user.py -rwxr-xr-x 1.7 KiB
90357856 — Jochen Kupperschmidt Prepare login-based test with frozen time for Flask v2.x, Werkzeug v2.x 5 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
#!/usr/bin/env python

"""Create an initial user with admin privileges to begin BYCEPS setup.

:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""

import click

from byceps.services.authorization import service as authorization_service
from byceps.services.user import command_service as user_command_service
from byceps.services.user import creation_service as user_creation_service

from _util import call_with_app_context


@click.command()
@click.option('--screen_name', prompt=True)
@click.option('--email_address', prompt=True)
@click.option('--password', prompt=True, hide_input=True)
def execute(screen_name, email_address, password):
    click.echo(f'Creating user "{screen_name}" ... ', nl=False)
    user = _create_user(screen_name, email_address, password)
    click.secho('done.', fg='green')

    click.echo(f'Initializing user "{screen_name}" ... ', nl=False)
    user_command_service.initialize_account(user.id)
    click.secho('done.', fg='green')

    roles = _get_roles()
    click.echo(
        f'Assigning {len(roles)} roles to user "{screen_name}" ... ', nl=False
    )
    _assign_roles_to_user(roles, user.id)
    click.secho('done.', fg='green')


def _create_user(screen_name, email_address, password):
    try:
        user, event = user_creation_service.create_basic_user(
            screen_name, email_address, password
        )
        return user
    except ValueError as e:
        raise click.UsageError(e)


def _get_roles():
    return authorization_service.get_all_roles_with_titles()


def _assign_roles_to_user(roles, user_id):
    for role in roles:
        authorization_service.assign_role_to_user(role.id, user_id)


if __name__ == '__main__':
    call_with_app_context(execute)