auths.py 4.94 KB
Newer Older
1
from pydantic import BaseModel
2
from typing import Optional
3
import uuid
4
import logging
5
6
from sqlalchemy import String, Column, Boolean
from sqlalchemy.orm import Session
7

8
from apps.webui.models.users import UserModel, Users
Tim Farrell's avatar
Tim Farrell committed
9
from utils.utils import verify_password
10

11
from apps.webui.internal.db import Base, get_session
12

13
from config import SRC_LOG_LEVELS
Timothy J. Baek's avatar
Timothy J. Baek committed
14

15
16
17
log = logging.getLogger(__name__)
log.setLevel(SRC_LOG_LEVELS["MODELS"])

18
19
20
21
22
####################
# DB MODEL
####################


23
24
class Auth(Base):
    __tablename__ = "auth"
Timothy J. Baek's avatar
Timothy J. Baek committed
25

26
27
28
29
    id = Column(String, primary_key=True)
    email = Column(String)
    password = Column(String)
    active = Column(Boolean)
Timothy J. Baek's avatar
Timothy J. Baek committed
30
31


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class AuthModel(BaseModel):
    id: str
    email: str
    password: str
    active: bool = True


####################
# Forms
####################


class Token(BaseModel):
    token: str
    token_type: str

Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
48

liu.vaayne's avatar
liu.vaayne committed
49
50
class ApiKey(BaseModel):
    api_key: Optional[str] = None
51

Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
52

53
54
55
56
57
class UserResponse(BaseModel):
    id: str
    email: str
    name: str
    role: str
Timothy J. Baek's avatar
Timothy J. Baek committed
58
    profile_image_url: str
59
60
61
62
63
64
65
66
67
68
69


class SigninResponse(Token, UserResponse):
    pass


class SigninForm(BaseModel):
    email: str
    password: str


70
71
72
73
class ProfileImageUrlForm(BaseModel):
    profile_image_url: str


74
75
76
77
78
class UpdateProfileForm(BaseModel):
    profile_image_url: str
    name: str


79
80
81
82
83
class UpdatePasswordForm(BaseModel):
    password: str
    new_password: str


84
85
86
87
class SignupForm(BaseModel):
    name: str
    email: str
    password: str
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
88
    profile_image_url: Optional[str] = "/user.png"
89
90


Timothy J. Baek's avatar
Timothy J. Baek committed
91
class AddUserForm(SignupForm):
92
    role: Optional[str] = "pending"
Timothy J. Baek's avatar
Timothy J. Baek committed
93
94


95
96
class AuthsTable:

Timothy J. Baek's avatar
Timothy J. Baek committed
97
    def insert_new_auth(
Danny Liu's avatar
Danny Liu committed
98
99
100
101
        self,
        email: str,
        password: str,
        name: str,
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
102
        profile_image_url: str = "/user.png",
Danny Liu's avatar
Danny Liu committed
103
        role: str = "pending",
104
        oauth_sub: Optional[str] = None,
Timothy J. Baek's avatar
Timothy J. Baek committed
105
    ) -> Optional[UserModel]:
106
107
        with get_session() as db:
            log.info("insert_new_auth")
108

109
            id = str(uuid.uuid4())
110

111
112
113
114
115
            auth = AuthModel(
                **{"id": id, "email": email, "password": password, "active": True}
            )
            result = Auth(**auth.model_dump())
            db.add(result)
Timothy J. Baek's avatar
Timothy J. Baek committed
116

117
118
119
            user = Users.insert_new_user(
                id, name, email, profile_image_url, role, oauth_sub
            )
120

121
122
            db.commit()
            db.refresh(result)
123

124
125
126
127
            if result and user:
                return user
            else:
                return None
128

129
    def authenticate_user(self, email: str, password: str) -> Optional[UserModel]:
130
        log.info(f"authenticate_user: {email}")
131
132
133
134
135
136
137
138
139
        with get_session() as db:
            try:
                auth = db.query(Auth).filter_by(email=email, active=True).first()
                if auth:
                    if verify_password(password, auth.password):
                        user = Users.get_user_by_id(auth.id)
                        return user
                    else:
                        return None
Timothy J. Baek's avatar
Timothy J. Baek committed
140
141
                else:
                    return None
142
            except:
143
144
                return None

145
    def authenticate_user_by_api_key(self, api_key: str) -> Optional[UserModel]:
liu.vaayne's avatar
liu.vaayne committed
146
        log.info(f"authenticate_user_by_api_key: {api_key}")
147
148
149
150
        with get_session() as db:
            # if no api_key, return None
            if not api_key:
                return None
Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
151

152
153
154
155
156
            try:
                user = Users.get_user_by_api_key(api_key)
                return user if user else None
            except:
                return False
Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
157

158
    def authenticate_user_by_trusted_header(self, email: str) -> Optional[UserModel]:
159
        log.info(f"authenticate_user_by_trusted_header: {email}")
160
161
162
163
164
165
166
167
        with get_session() as db:
            try:
                auth = db.query(Auth).filter(email=email, active=True).first()
                if auth:
                    user = Users.get_user_by_id(auth.id)
                    return user
            except:
                return None
liu.vaayne's avatar
liu.vaayne committed
168

169
    def update_user_password_by_id(self, id: str, new_password: str) -> bool:
170
171
        with get_session() as db:
            try:
172
173
174
                result = (
                    db.query(Auth).filter_by(id=id).update({"password": new_password})
                )
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
                return True if result == 1 else False
            except:
                return False

    def update_email_by_id(self, id: str, email: str) -> bool:
        with get_session() as db:
            try:
                result = db.query(Auth).filter_by(id=id).update({"email": email})
                return True if result == 1 else False
            except:
                return False

    def delete_auth_by_id(self, id: str) -> bool:
        with get_session() as db:
            try:
                # Delete User
                result = Users.delete_user_by_id(id)

                if result:
                    db.query(Auth).filter_by(id=id).delete()

                    return True
                else:
                    return False
            except:
Timothy J. Baek's avatar
Timothy J. Baek committed
200
201
                return False

202

203
Auths = AuthsTable()