auths.py 1.91 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
from pydantic import BaseModel
from typing import List, Union, Optional
import time
import uuid


from apps.web.models.users import UserModel, Users
from utils import (
    verify_password,
    get_password_hash,
    bearer_scheme,
    create_token,
)

import config

DB = config.DB

####################
# DB MODEL
####################


class AuthModel(BaseModel):
    id: str
    email: str
    password: str
    active: bool = True


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


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


class UserResponse(BaseModel):
    id: str
    email: str
    name: str
    role: str


class SigninResponse(Token, UserResponse):
    pass


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


class SignupForm(BaseModel):
    name: str
    email: str
    password: str


class AuthsTable:
    def __init__(self, db):
        self.db = db
        self.table = db.auths

    def insert_new_auth(
        self, email: str, password: str, name: str, role: str = "user"
    ) -> Optional[UserModel]:
        print("insert_new_auth")

        id = str(uuid.uuid4())

        auth = AuthModel(
            **{"id": id, "email": email, "password": password, "active": True}
        )
        result = self.table.insert_one(auth.model_dump())
        user = Users.insert_new_user(id, name, email, role)

        print(result, user)
        if result and user:
            return user
        else:
            return None

    def authenticate_user(self, email: str, password: str) -> Optional[UserModel]:
        print("authenticate_user")

        auth = self.table.find_one({"email": email, "active": True})

        if auth:
            if verify_password(password, auth["password"]):
                user = self.db.users.find_one({"id": auth["id"]})
                return UserModel(**user)
            else:
                return None
        else:
            return None


Auths = AuthsTable(DB)