auths.py 4.87 KB
Newer Older
1
2
3
4
from pydantic import BaseModel
from typing import List, Union, Optional
import time
import uuid
5
import logging
Timothy J. Baek's avatar
Timothy J. Baek committed
6
from peewee import *
7
8

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

Timothy J. Baek's avatar
Timothy J. Baek committed
11
from apps.web.internal.db import DB
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
####################


Timothy J. Baek's avatar
Timothy J. Baek committed
23
24
25
26
27
class Auth(Model):
    id = CharField(unique=True)
    email = CharField()
    password = CharField()
    active = BooleanField()
liu.vaayne's avatar
liu.vaayne committed
28
    api_key = CharField(null=True, unique=True)
Timothy J. Baek's avatar
Timothy J. Baek committed
29
30
31
32
33

    class Meta:
        database = DB


34
35
36
37
38
class AuthModel(BaseModel):
    id: str
    email: str
    password: str
    active: bool = True
liu.vaayne's avatar
liu.vaayne committed
39
    api_key: Optional[str] = None
40
41
42
43
44
45
46
47
48
49
50


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


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

liu.vaayne's avatar
liu.vaayne committed
51
52
class ApiKey(BaseModel):
    api_key: Optional[str] = None
53
54
55
56
57
58

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


class SigninResponse(Token, UserResponse):
    pass


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


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


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


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


85
86
87
88
89
90
91
92
93
class SignupForm(BaseModel):
    name: str
    email: str
    password: str


class AuthsTable:
    def __init__(self, db):
        self.db = db
Timothy J. Baek's avatar
Timothy J. Baek committed
94
        self.db.create_tables([Auth])
95

Timothy J. Baek's avatar
Timothy J. Baek committed
96
97
98
    def insert_new_auth(
        self, email: str, password: str, name: str, role: str = "pending"
    ) -> Optional[UserModel]:
99
        log.info("insert_new_auth")
100
101
102

        id = str(uuid.uuid4())

Timothy J. Baek's avatar
Timothy J. Baek committed
103
104
105
        auth = AuthModel(
            **{"id": id, "email": email, "password": password, "active": True}
        )
Timothy J. Baek's avatar
Timothy J. Baek committed
106
107
        result = Auth.create(**auth.model_dump())

108
109
110
111
112
113
114
        user = Users.insert_new_user(id, name, email, role)

        if result and user:
            return user
        else:
            return None

Timothy J. Baek's avatar
Timothy J. Baek committed
115
    def authenticate_user(self, email: str, password: str) -> Optional[UserModel]:
116
        log.info(f"authenticate_user: {email}")
Timothy J. Baek's avatar
Timothy J. Baek committed
117
118
119
120
121
122
123
124
        try:
            auth = Auth.get(Auth.email == email, Auth.active == True)
            if auth:
                if verify_password(password, auth.password):
                    user = Users.get_user_by_id(auth.id)
                    return user
                else:
                    return None
125
126
            else:
                return None
Timothy J. Baek's avatar
Timothy J. Baek committed
127
        except:
128
129
            return None

liu.vaayne's avatar
liu.vaayne committed
130
131
132
133
134
135
136
137
138
139
140
141
    def authenticate_user_by_api_key(self, api_key: str) -> Optional[UserModel]:
        log.info(f"authenticate_user_by_api_key: {api_key}")
        # if no api_key, return None
        if not api_key:
            return None
        try:
            auth = Auth.get(Auth.api_key == api_key, Auth.active == True)
            if auth:
                user = Users.get_user_by_id(auth.id)
                return user
            else:
                return None
142

Jun Siang Cheah's avatar
Jun Siang Cheah committed
143
    def authenticate_user_by_trusted_header(self, email: str) -> Optional[UserModel]:
144
145
146
147
148
149
        log.info(f"authenticate_user_by_trusted_header: {email}")
        try:
            auth = Auth.get(Auth.email == email, Auth.active == True)
            if auth:
                user = Users.get_user_by_id(auth.id)
                return user
liu.vaayne's avatar
liu.vaayne committed
150
151
152
        except:
            return None

Timothy J. Baek's avatar
Timothy J. Baek committed
153
    def update_user_password_by_id(self, id: str, new_password: str) -> bool:
154
        try:
Timothy J. Baek's avatar
Timothy J. Baek committed
155
156
            query = Auth.update(password=new_password).where(Auth.id == id)
            result = query.execute()
Timothy J. Baek's avatar
Timothy J. Baek committed
157
158

            return True if result == 1 else False
159
160
161
        except:
            return False

Timothy J. Baek's avatar
Timothy J. Baek committed
162
163
164
165
166
167
168
169
170
    def update_email_by_id(self, id: str, email: str) -> bool:
        try:
            query = Auth.update(email=email).where(Auth.id == id)
            result = query.execute()

            return True if result == 1 else False
        except:
            return False

liu.vaayne's avatar
liu.vaayne committed
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
    def update_api_key_by_id(self, id: str, api_key: str) -> str:
        try:
            query = Auth.update(api_key=api_key).where(Auth.id == id)
            result = query.execute()

            return True if result == 1 else False
        except:
            return False

    def get_api_key_by_id(self, id: str) -> Optional[str]:
        try:
            auth = Auth.get(Auth.id == id)
            return auth.api_key
        except:
            return None

187
    def delete_auth_by_id(self, id: str) -> bool:
Timothy J. Baek's avatar
Timothy J. Baek committed
188
189
190
191
192
193
194
        try:
            # Delete User
            result = Users.delete_user_by_id(id)

            if result:
                # Delete Auth
                query = Auth.delete().where(Auth.id == id)
Timothy J. Baek's avatar
Timothy J. Baek committed
195
                query.execute()  # Remove the rows, return number of rows removed.
Timothy J. Baek's avatar
Timothy J. Baek committed
196
197
198
199
200
201
202

                return True
            else:
                return False
        except:
            return False

203
204

Auths = AuthsTable(DB)