Passed
Push — master ( bbf1d4...4d0d43 )
by Jochen
02:09
created

byceps.services.authentication.service._find_user_by_screen_name_or_email_address()   A

Complexity

Conditions 2

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 7
nop 1
dl 0
loc 10
rs 10
c 0
b 0
f 0
1
"""
2
byceps.services.authentication.service
3
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
5
:Copyright: 2006-2020 Jochen Kupperschmidt
6
:License: Modified BSD, see LICENSE for details.
7
"""
8
9
from typing import Optional
10
11
from ..user import service as user_service
12
from ..user.transfer.models import User
13
14
from .exceptions import AuthenticationFailed
15
from .password import service as password_service
16
17
18
def authenticate(screen_name_or_email_address: str, password: str) -> User:
19
    """Try to authenticate the user.
20
21
    Return the user object on success, or raise an exception on failure.
22
    """
23
    # Look up user.
24
    user = _find_user_by_screen_name_or_email_address(
25
        screen_name_or_email_address
26
    )
27
    if user is None:
28
        # Screen name/email address is unknown.
29
        raise AuthenticationFailed()
30
31
    # Account must be initialized.
32
    if not user.initialized:
33
        # User account is not initialized.
34
        raise AuthenticationFailed()
35
36
    # Account must not be suspended.
37
    if user.suspended:
38
        # User account is suspended.
39
        raise AuthenticationFailed()
40
41
    # Account must not be deleted.
42
    if user.deleted:
43
        # User account has been deleted.
44
        raise AuthenticationFailed()
45
46
    # Verify credentials.
47
    if not password_service.is_password_valid_for_user(user.id, password):
48
        # Password does not match.
49
        raise AuthenticationFailed()
50
51
    return user.to_dto()
52
53
54
def _find_user_by_screen_name_or_email_address(
55
    screen_name_or_email_address: str
56
) -> Optional[User]:
57
    if '@' in screen_name_or_email_address:
58
        return user_service.find_user_by_email_address(
59
            screen_name_or_email_address
60
        )
61
    else:
62
        return user_service.find_user_by_screen_name(
63
            screen_name_or_email_address, case_insensitive=True
64
        )
65