summaryrefslogtreecommitdiffstats
path: root/girok/api/auth.py
blob: 221d5a27cb581563423c09c7d8156c987a3ab548 (plain)
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
from urllib.parse import urljoin

import requests
from requests import HTTPError

from girok.api.entity import APIResponse
from girok.constants import BASE_URL


def verify_access_token(access_token: str) -> bool:
    resp = requests.get(
        url=urljoin(BASE_URL, "auth/verify/access-token"),
        headers={"Authorization": "Bearer " + access_token},
    )
    return resp.status_code == 200


def send_verification_code(email: str) -> APIResponse:
    resp = requests.post(
        url=urljoin(BASE_URL, "auth/verification-code"), json={"email": email}
    )

    try:
        resp.raise_for_status()
        return APIResponse(is_success=True)
    except HTTPError as e:
        error_body = resp.json()
        error_message = error_body["message"]
        return APIResponse(is_success=False, error_message=error_message)


def verify_verification_code(email: str, verification_code: str) -> APIResponse:
    resp = requests.post(
        url=urljoin(BASE_URL, "auth/verification-code/check"),
        json={"email": email, "verificationCode": verification_code},
    )

    try:
        resp.raise_for_status()
        return APIResponse(is_success=True)
    except HTTPError as e:
        error_body = resp.json()
        error_message = error_body["message"]
        return APIResponse(is_success=False, error_message=error_message)


def register(email: str, verification_code: str, password: str) -> APIResponse:
    resp = requests.post(
        url=urljoin(BASE_URL, "sign-up"),
        json={
            "email": email,
            "verificationCode": verification_code,
            "password": password,
        },
    )

    try:
        resp.raise_for_status()
        return APIResponse(is_success=True)
    except HTTPError as e:
        try:
            error_body = resp.json()
            error_message = error_body["message"]
        except:
            error_message = "Registration failed"

        return APIResponse(is_success=False, error_message=error_message)


def login(email: str, password: str) -> APIResponse:
    resp = requests.post(
        url=urljoin(BASE_URL, "login"), json={"email": email, "password": password}
    )

    try:
        resp.raise_for_status()
        return APIResponse(is_success=True, body=resp.json())
    except HTTPError as e:
        try:
            error_body = resp.json()
            error_message = error_body["message"]
        except:
            error_message = "Login failed"

        return APIResponse(is_success=False, error_message=error_message)