~homeworkprod/byceps

ref: 4237b3ec9496efe95dcce82bea3207ab9de4d520 byceps/byceps/services/authentication/service.py -rw-r--r-- 1.7 KiB
4237b3ec — Jochen Kupperschmidt Move ticketing blueprint into `site` subpackage 1 year, 11 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
"""
byceps.services.authentication.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

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

from typing import Optional

from ..user import service as user_service
from ..user.transfer.models import User

from .exceptions import AuthenticationFailed
from .password import service as password_service


def authenticate(screen_name_or_email_address: str, password: str) -> User:
    """Try to authenticate the user.

    Return the user object on success, or raise an exception on failure.
    """
    # Look up user.
    user = _find_user_by_screen_name_or_email_address(
        screen_name_or_email_address
    )
    if user is None:
        # Screen name/email address is unknown.
        raise AuthenticationFailed()

    _require_user_account_is_active(user)

    # Verify credentials.
    if not password_service.is_password_valid_for_user(user.id, password):
        # Password does not match.
        raise AuthenticationFailed()

    return user.to_dto()


def _find_user_by_screen_name_or_email_address(
    screen_name_or_email_address: str,
) -> Optional[User]:
    if '@' in screen_name_or_email_address:
        return user_service.find_user_by_email_address(
            screen_name_or_email_address
        )
    else:
        return user_service.find_user_by_screen_name(
            screen_name_or_email_address, case_insensitive=True
        )


def _require_user_account_is_active(user: User) -> None:
    """Raise exception if user account has not been initialized, is
    suspended, or has been deleted.
    """
    if (not user.initialized) or user.suspended or user.deleted:
        raise AuthenticationFailed()