Passed
Push — main ( 95bc96...0b198e )
by Jochen
04:40
created

create_initial_admin_user._get_role_ids()   A

Complexity

Conditions 1

Size

Total Lines 2
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nop 0
dl 0
loc 2
rs 10
c 0
b 0
f 0
1
#!/usr/bin/env python
2
3
"""Create an initial user with admin privileges to begin BYCEPS setup.
4
5
:Copyright: 2006-2021 Jochen Kupperschmidt
6
:License: Revised BSD (see `LICENSE` file for details)
7
"""
8
9
from __future__ import annotations
10
from typing import Iterable, Sequence
11
12
import click
13
14
from byceps.services.authorization import service as authorization_service
15
from byceps.services.authorization.transfer.models import RoleID
16
from byceps.services.user import command_service as user_command_service
17
from byceps.services.user import creation_service as user_creation_service
18
from byceps.services.user.transfer.models import User
19
from byceps.typing import UserID
20
21
from _util import call_with_app_context
22
23
24
@click.command()
25
@click.option('--screen_name', prompt=True)
26
@click.option('--email_address', prompt=True)
27
@click.option('--password', prompt=True, hide_input=True)
28
def execute(screen_name, email_address, password) -> None:
29
    click.echo(f'Creating user "{screen_name}" ... ', nl=False)
30
    user = _create_user(screen_name, email_address, password)
31
    click.secho('done.', fg='green')
32
33
    click.echo(f'Initializing user "{screen_name}" ... ', nl=False)
34
    user_command_service.initialize_account(user.id)
35
    click.secho('done.', fg='green')
36
37
    role_ids = _get_role_ids()
38
    click.echo(
39
        f'Assigning {len(role_ids)} roles to user "{screen_name}" ... ', nl=False
40
    )
41
    _assign_roles_to_user(role_ids, user.id)
42
    click.secho('done.', fg='green')
43
44
45
def _create_user(screen_name: str, email_address: str, password: str) -> User:
46
    try:
47
        user, event = user_creation_service.create_user(
48
            screen_name, email_address, password
49
        )
50
        return user
51
    except ValueError as e:
52
        raise click.UsageError('User creation failed: {e}')
53
54
55
def _get_role_ids() -> set[RoleID]:
56
    return authorization_service.get_all_role_ids()
57
58
59
def _assign_roles_to_user(role_ids: set[RoleID], user_id: UserID) -> None:
60
    for role_id in role_ids:
61
        authorization_service.assign_role_to_user(role_id, user_id)
62
63
64
if __name__ == '__main__':
65
    call_with_app_context(execute)
66