users.py 7.34 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

12
13
14
15
16
17
18
from apps.webui.models.users import (
    UserModel,
    UserUpdateForm,
    UserRoleUpdateForm,
    UserSettings,
    Users,
)
19
20
from apps.webui.models.auths import Auths
from apps.webui.models.chats import Chats
Timothy J. Baek's avatar
Timothy J. Baek committed
21

22
23
24
25
26
27
from utils.utils import (
    get_verified_user,
    get_password_hash,
    get_current_user,
    get_admin_user,
)
Timothy J. Baek's avatar
Timothy J. Baek committed
28
29
from constants import ERROR_MESSAGES

30
from config import SRC_LOG_LEVELS
Timothy J. Baek's avatar
Timothy J. Baek committed
31

32
33
34
log = logging.getLogger(__name__)
log.setLevel(SRC_LOG_LEVELS["MODELS"])

Timothy J. Baek's avatar
Timothy J. Baek committed
35
36
37
38
39
40
41
42
router = APIRouter()

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


@router.get("/", response_model=List[UserModel])
43
async def get_users(
44
    skip: int = 0, limit: int = 50, user=Depends(get_admin_user)
45
):
46
    return Users.get_users(skip, limit)
Timothy J. Baek's avatar
Timothy J. Baek committed
47
48


Timothy J. Baek's avatar
Timothy J. Baek committed
49
50
51
52
53
54
55
############################
# User Permissions
############################


@router.get("/permissions/user")
async def get_user_permissions(request: Request, user=Depends(get_admin_user)):
56
    return request.app.state.config.USER_PERMISSIONS
Timothy J. Baek's avatar
Timothy J. Baek committed
57
58
59
60
61
62


@router.post("/permissions/user")
async def update_user_permissions(
    request: Request, form_data: dict, user=Depends(get_admin_user)
):
63
64
    request.app.state.config.USER_PERMISSIONS = form_data
    return request.app.state.config.USER_PERMISSIONS
Timothy J. Baek's avatar
Timothy J. Baek committed
65
66


Timothy J. Baek's avatar
Timothy J. Baek committed
67
68
69
70
71
72
############################
# UpdateUserRole
############################


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

77
78
    if user.id != form_data.id and form_data.id != Users.get_first_user().id:
        return Users.update_user_role_by_id(form_data.id, form_data.role)
79
80
81
82
83

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


86
87
88
89
90
91
############################
# GetUserSettingsBySessionUser
############################


@router.get("/user/settings", response_model=Optional[UserSettings])
92
async def get_user_settings_by_session_user(
93
    user=Depends(get_verified_user)
94
):
95
    user = Users.get_user_by_id(user.id)
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
    if user:
        return user.settings
    else:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=ERROR_MESSAGES.USER_NOT_FOUND,
        )


############################
# UpdateUserSettingsBySessionUser
############################


@router.post("/user/settings/update", response_model=UserSettings)
async def update_user_settings_by_session_user(
112
    form_data: UserSettings, user=Depends(get_verified_user)
113
):
114
    user = Users.update_user_by_id(user.id, {"settings": form_data.model_dump()})
115
116
117
118
119
120
121
122
123
    if user:
        return user.settings
    else:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=ERROR_MESSAGES.USER_NOT_FOUND,
        )


Timothy J. Baek's avatar
Timothy J. Baek committed
124
125
126
127
128
129
############################
# GetUserInfoBySessionUser
############################


@router.get("/user/info", response_model=Optional[dict])
130
async def get_user_info_by_session_user(
131
    user=Depends(get_verified_user)
132
):
133
    user = Users.get_user_by_id(user.id)
Timothy J. Baek's avatar
Timothy J. Baek committed
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
    if user:
        return user.info
    else:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=ERROR_MESSAGES.USER_NOT_FOUND,
        )


############################
# UpdateUserInfoBySessionUser
############################


@router.post("/user/info/update", response_model=Optional[dict])
149
async def update_user_info_by_session_user(
150
    form_data: dict, user=Depends(get_verified_user)
Timothy J. Baek's avatar
Timothy J. Baek committed
151
):
152
    user = Users.get_user_by_id(user.id)
Timothy J. Baek's avatar
Timothy J. Baek committed
153
154
155
156
    if user:
        if user.info is None:
            user.info = {}

157
        user = Users.update_user_by_id(
158
            user.id, {"info": {**user.info, **form_data}}
159
        )
Timothy J. Baek's avatar
Timothy J. Baek committed
160
161
162
163
164
165
166
167
168
169
170
171
172
173
        if user:
            return user.info
        else:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=ERROR_MESSAGES.USER_NOT_FOUND,
            )
    else:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=ERROR_MESSAGES.USER_NOT_FOUND,
        )


174
175
176
177
178
179
180
181
182
183
184
############################
# GetUserById
############################


class UserResponse(BaseModel):
    name: str
    profile_image_url: str


@router.get("/{user_id}", response_model=UserResponse)
185
async def get_user_by_id(
186
    user_id: str, user=Depends(get_verified_user)
187
):
188

189
190
    # Check if user_id is a shared chat
    # If it is, get the user_id from the chat
Timothy J. Baek's avatar
Timothy J. Baek committed
191
192
    if user_id.startswith("shared-"):
        chat_id = user_id.replace("shared-", "")
193
        chat = Chats.get_chat_by_id(chat_id)
Timothy J. Baek's avatar
Timothy J. Baek committed
194
195
196
197
198
199
200
201
        if chat:
            user_id = chat.user_id
        else:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=ERROR_MESSAGES.USER_NOT_FOUND,
            )

202
    user = Users.get_user_by_id(user_id)
203
204
205
206
207
208
209
210
211
212

    if user:
        return UserResponse(name=user.name, profile_image_url=user.profile_image_url)
    else:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=ERROR_MESSAGES.USER_NOT_FOUND,
        )


Timothy J. Baek's avatar
Timothy J. Baek committed
213
############################
Timothy J. Baek's avatar
Timothy J. Baek committed
214
# UpdateUserById
Timothy J. Baek's avatar
Timothy J. Baek committed
215
216
217
############################


Timothy J. Baek's avatar
Timothy J. Baek committed
218
219
@router.post("/{user_id}/update", response_model=Optional[UserModel])
async def update_user_by_id(
220
221
222
    user_id: str,
    form_data: UserUpdateForm,
    session_user=Depends(get_admin_user),
Timothy J. Baek's avatar
Timothy J. Baek committed
223
):
224
    user = Users.get_user_by_id(user_id)
Timothy J. Baek's avatar
Timothy J. Baek committed
225
226

    if user:
Timothy J. Baek's avatar
Timothy J. Baek committed
227
        if form_data.email.lower() != user.email:
228
            email_user = Users.get_user_by_email(form_data.email.lower())
Timothy J. Baek's avatar
Timothy J. Baek committed
229
230
231
232
233
234
235
236
            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)
237
            log.debug(f"hashed: {hashed}")
238
            Auths.update_user_password_by_id(user_id, hashed)
Timothy J. Baek's avatar
Timothy J. Baek committed
239

240
        Auths.update_email_by_id(user_id, form_data.email.lower())
Timothy J. Baek's avatar
Timothy J. Baek committed
241
242
243
244
        updated_user = Users.update_user_by_id(
            user_id,
            {
                "name": form_data.name,
Timothy J. Baek's avatar
Timothy J. Baek committed
245
                "email": form_data.email.lower(),
Timothy J. Baek's avatar
Timothy J. Baek committed
246
247
248
249
250
251
252
                "profile_image_url": form_data.profile_image_url,
            },
        )

        if updated_user:
            return updated_user

Timothy J. Baek's avatar
Timothy J. Baek committed
253
        raise HTTPException(
Timothy J. Baek's avatar
Timothy J. Baek committed
254
            status_code=status.HTTP_400_BAD_REQUEST,
255
            detail=ERROR_MESSAGES.DEFAULT(),
Timothy J. Baek's avatar
Timothy J. Baek committed
256
        )
257

258
259
260
261
262
    raise HTTPException(
        status_code=status.HTTP_400_BAD_REQUEST,
        detail=ERROR_MESSAGES.USER_NOT_FOUND,
    )

263
264

############################
Timothy J. Baek's avatar
Timothy J. Baek committed
265
# DeleteUserById
266
267
268
269
############################


@router.delete("/{user_id}", response_model=bool)
270
async def delete_user_by_id(
271
    user_id: str, user=Depends(get_admin_user)
272
):
273
    if user.id != user_id:
274
        result = Auths.delete_auth_by_id(user_id)
275
276
277
278

        if result:
            return True

279
        raise HTTPException(
280
281
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=ERROR_MESSAGES.DELETE_USER_ERROR,
282
        )
283
284
285
286
287

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