1
|
|
|
""" |
2
|
|
|
byceps.services.user.import_service |
3
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
4
|
|
|
|
5
|
|
|
:Copyright: 2006-2021 Jochen Kupperschmidt |
6
|
|
|
:License: Revised BSD (see `LICENSE` file for details) |
7
|
|
|
""" |
8
|
|
|
|
9
|
|
|
from __future__ import annotations |
10
|
|
|
import json |
11
|
|
|
from io import TextIOBase |
12
|
|
|
import secrets |
13
|
|
|
from typing import Iterator |
14
|
|
|
|
15
|
|
|
from marshmallow import fields, Schema, ValidationError |
16
|
|
|
|
17
|
|
|
from . import creation_service |
18
|
|
|
from .transfer.models import User |
19
|
|
|
|
20
|
|
|
|
21
|
|
|
class UserImportSchema(Schema): |
22
|
|
|
screen_name = fields.Str(required=True) |
23
|
|
|
email_address = fields.Str(required=False) |
24
|
|
|
first_names = fields.Str(required=False) |
25
|
|
|
last_name = fields.Str(required=False) |
26
|
|
|
|
27
|
|
|
|
28
|
|
|
def parse_lines(lines: TextIOBase) -> Iterator[str]: |
29
|
|
|
for line in lines: |
30
|
|
|
yield line.strip() |
31
|
|
|
|
32
|
|
|
|
33
|
|
|
def parse_user_json(json_data: str) -> dict[str, str]: |
34
|
|
|
data_dict = json.loads(json_data) |
35
|
|
|
|
36
|
|
|
schema = UserImportSchema() |
37
|
|
|
try: |
38
|
|
|
return schema.load(data_dict) |
39
|
|
|
except ValidationError as e: |
40
|
|
|
raise Exception(str(e.normalized_messages())) |
41
|
|
|
|
42
|
|
|
|
43
|
|
|
def create_user(user_dict) -> User: |
44
|
|
|
password = secrets.token_urlsafe(24) |
45
|
|
|
|
46
|
|
|
user, _ = creation_service.create_basic_user( |
47
|
|
|
user_dict['screen_name'], |
48
|
|
|
user_dict.get('email_address'), |
49
|
|
|
password, |
50
|
|
|
first_names=user_dict.get('first_names'), |
51
|
|
|
last_name=user_dict.get('last_name'), |
52
|
|
|
) |
53
|
|
|
|
54
|
|
|
return user |
55
|
|
|
|