users.py 3.85 KB
Newer Older
Timothy J. Baek's avatar
Timothy J. Baek committed
1
from fastapi import Response, Request
Timothy J. Baek's avatar
Timothy J. Baek committed
2
3
4
5
6
7
8
9
from fastapi import Depends, FastAPI, HTTPException, status
from datetime import datetime, timedelta
from typing import List, Union, Optional

from fastapi import APIRouter
from pydantic import BaseModel
import time
import uuid
10
import logging
Timothy J. Baek's avatar
Timothy J. Baek committed
11

Timothy J. Baek's avatar
Timothy J. Baek committed
12
from apps.web.models.users import UserModel, UserUpdateForm, UserRoleUpdateForm, Users
Timothy J. Baek's avatar
Timothy J. Baek committed
13
14
from apps.web.models.auths import Auths

15
from utils.utils import get_current_user, get_password_hash, get_admin_user
Timothy J. Baek's avatar
Timothy J. Baek committed
16
17
from constants import ERROR_MESSAGES

18
19
20
21
from config import SRC_LOG_LEVELS
log = logging.getLogger(__name__)
log.setLevel(SRC_LOG_LEVELS["MODELS"])

Timothy J. Baek's avatar
Timothy J. Baek committed
22
23
24
25
26
27
28
29
router = APIRouter()

############################
# GetUsers
############################


@router.get("/", response_model=List[UserModel])
30
async def get_users(skip: int = 0, limit: int = 50, user=Depends(get_admin_user)):
31
    return Users.get_users(skip, limit)
Timothy J. Baek's avatar
Timothy J. Baek committed
32
33


Timothy J. Baek's avatar
Timothy J. Baek committed
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
############################
# User Permissions
############################


@router.get("/permissions/user")
async def get_user_permissions(request: Request, user=Depends(get_admin_user)):
    return request.app.state.USER_PERMISSIONS


@router.post("/permissions/user")
async def update_user_permissions(
    request: Request, form_data: dict, user=Depends(get_admin_user)
):
    request.app.state.USER_PERMISSIONS = form_data
    return request.app.state.USER_PERMISSIONS


Timothy J. Baek's avatar
Timothy J. Baek committed
52
53
54
55
56
57
############################
# UpdateUserRole
############################


@router.post("/update/role", response_model=Optional[UserModel])
Timothy J. Baek's avatar
Timothy J. Baek committed
58
59
async def update_user_role(form_data: UserRoleUpdateForm, user=Depends(get_admin_user)):

Timothy J. Baek's avatar
Timothy J. Baek committed
60
61
    if user.id != form_data.id:
        return Users.update_user_role_by_id(form_data.id, form_data.role)
62
63
64
65
66

    raise HTTPException(
        status_code=status.HTTP_403_FORBIDDEN,
        detail=ERROR_MESSAGES.ACTION_PROHIBITED,
    )
Timothy J. Baek's avatar
Timothy J. Baek committed
67
68


Timothy J. Baek's avatar
Timothy J. Baek committed
69
############################
Timothy J. Baek's avatar
Timothy J. Baek committed
70
# UpdateUserById
Timothy J. Baek's avatar
Timothy J. Baek committed
71
72
73
############################


Timothy J. Baek's avatar
Timothy J. Baek committed
74
75
@router.post("/{user_id}/update", response_model=Optional[UserModel])
async def update_user_by_id(
76
    user_id: str, form_data: UserUpdateForm, session_user=Depends(get_admin_user)
Timothy J. Baek's avatar
Timothy J. Baek committed
77
78
79
80
):
    user = Users.get_user_by_id(user_id)

    if user:
Timothy J. Baek's avatar
Timothy J. Baek committed
81
82
        if form_data.email.lower() != user.email:
            email_user = Users.get_user_by_email(form_data.email.lower())
Timothy J. Baek's avatar
Timothy J. Baek committed
83
84
85
86
87
88
89
90
            if email_user:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail=ERROR_MESSAGES.EMAIL_TAKEN,
                )

        if form_data.password:
            hashed = get_password_hash(form_data.password)
91
            log.debug(f"hashed: {hashed}")
Timothy J. Baek's avatar
Timothy J. Baek committed
92
93
            Auths.update_user_password_by_id(user_id, hashed)

Timothy J. Baek's avatar
Timothy J. Baek committed
94
        Auths.update_email_by_id(user_id, form_data.email.lower())
Timothy J. Baek's avatar
Timothy J. Baek committed
95
96
97
98
        updated_user = Users.update_user_by_id(
            user_id,
            {
                "name": form_data.name,
Timothy J. Baek's avatar
Timothy J. Baek committed
99
                "email": form_data.email.lower(),
Timothy J. Baek's avatar
Timothy J. Baek committed
100
101
102
103
104
105
106
                "profile_image_url": form_data.profile_image_url,
            },
        )

        if updated_user:
            return updated_user

Timothy J. Baek's avatar
Timothy J. Baek committed
107
        raise HTTPException(
Timothy J. Baek's avatar
Timothy J. Baek committed
108
            status_code=status.HTTP_400_BAD_REQUEST,
109
            detail=ERROR_MESSAGES.DEFAULT(),
Timothy J. Baek's avatar
Timothy J. Baek committed
110
        )
111

112
113
114
115
116
    raise HTTPException(
        status_code=status.HTTP_400_BAD_REQUEST,
        detail=ERROR_MESSAGES.USER_NOT_FOUND,
    )

117
118

############################
Timothy J. Baek's avatar
Timothy J. Baek committed
119
# DeleteUserById
120
121
122
123
############################


@router.delete("/{user_id}", response_model=bool)
124
125
126
127
128
129
130
async def delete_user_by_id(user_id: str, user=Depends(get_admin_user)):
    if user.id != user_id:
        result = Auths.delete_auth_by_id(user_id)

        if result:
            return True

131
        raise HTTPException(
132
133
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=ERROR_MESSAGES.DELETE_USER_ERROR,
134
        )
135
136
137
138
139

    raise HTTPException(
        status_code=status.HTTP_403_FORBIDDEN,
        detail=ERROR_MESSAGES.ACTION_PROHIBITED,
    )