auths.py 3.63 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
from fastapi import Response
from fastapi import Depends, FastAPI, HTTPException, status
from datetime import datetime, timedelta
from typing import List, Union

from fastapi import APIRouter
from pydantic import BaseModel
import time
import uuid

from apps.web.models.auths import (
    SigninForm,
    SignupForm,
14
    UpdatePasswordForm,
15
16
17
18
19
20
21
    UserResponse,
    SigninResponse,
    Auths,
)
from apps.web.models.users import Users


Timothy J. Baek's avatar
Timothy J. Baek committed
22
23
from utils.utils import (
    get_password_hash,
24
    get_current_user,
Timothy J. Baek's avatar
Timothy J. Baek committed
25
    create_token,
Anuraag Jain's avatar
Anuraag Jain committed
26
    verify_auth_token,
Timothy J. Baek's avatar
Timothy J. Baek committed
27
28
29
)
from utils.misc import get_gravatar_url
from constants import ERROR_MESSAGES
30
31


Timothy J. Baek's avatar
Timothy J. Baek committed
32
33
router = APIRouter()

34
35
36
37
38
############################
# GetSessionUser
############################


Anuraag Jain's avatar
Anuraag Jain committed
39
@router.get("/", response_model=UserResponse, dependencies=[Depends(verify_auth_token)])
40
41
42
43
44
45
46
47
async def get_session_user(user=Depends(get_current_user)):
    return {
        "id": user.id,
        "email": user.email,
        "name": user.name,
        "role": user.role,
        "profile_image_url": user.profile_image_url,
    }
48
49


50
51
52
53
54
############################
# Update Password
############################


Anuraag Jain's avatar
Anuraag Jain committed
55
56
57
58
59
60
@router.post(
    "/update/password", response_model=bool, dependencies=[Depends(verify_auth_token)]
)
async def update_password(
    form_data: UpdatePasswordForm, session_user=Depends(get_current_user)
):
61
62
    if session_user:
        user = Auths.authenticate_user(session_user.email, form_data.password)
63

64
65
        if user:
            hashed = get_password_hash(form_data.new_password)
Timothy J. Baek's avatar
Timothy J. Baek committed
66
            return Auths.update_user_password_by_id(user.id, hashed)
67
68
        else:
            raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_PASSWORD)
69
70
71
72
    else:
        raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)


73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
############################
# SignIn
############################


@router.post("/signin", response_model=SigninResponse)
async def signin(form_data: SigninForm):
    user = Auths.authenticate_user(form_data.email.lower(), form_data.password)
    if user:
        token = create_token(data={"email": user.email})

        return {
            "token": token,
            "token_type": "Bearer",
            "id": user.id,
            "email": user.email,
            "name": user.name,
            "role": user.role,
Timothy J. Baek's avatar
Timothy J. Baek committed
91
            "profile_image_url": user.profile_image_url,
92
93
        }
    else:
Timothy J. Baek's avatar
Timothy J. Baek committed
94
        raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
95
96
97
98
99
100
101
102
103
104
105


############################
# SignUp
############################


@router.post("/signup", response_model=SigninResponse)
async def signup(form_data: SignupForm):
    if not Users.get_user_by_email(form_data.email.lower()):
        try:
106
            role = "admin" if Users.get_num_users() == 0 else "pending"
107
            hashed = get_password_hash(form_data.password)
Timothy J. Baek's avatar
Timothy J. Baek committed
108
109
110
            user = Auths.insert_new_auth(
                form_data.email.lower(), hashed, form_data.name, role
            )
111
112
113
114
115
116
117
118
119
120
121
122

            if user:
                token = create_token(data={"email": user.email})
                # response.set_cookie(key='token', value=token, httponly=True)

                return {
                    "token": token,
                    "token_type": "Bearer",
                    "id": user.id,
                    "email": user.email,
                    "name": user.name,
                    "role": user.role,
Timothy J. Baek's avatar
Timothy J. Baek committed
123
                    "profile_image_url": user.profile_image_url,
124
125
                }
            else:
126
                raise HTTPException(500, detail=ERROR_MESSAGES.CREATE_USER_ERROR)
127
128
129
        except Exception as err:
            raise HTTPException(500, detail=ERROR_MESSAGES.DEFAULT(err))
    else:
Timothy J. Baek's avatar
Timothy J. Baek committed
130
        raise HTTPException(400, detail=ERROR_MESSAGES.EMAIL_TAKEN)