auths.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. from pydantic import BaseModel
  2. from typing import List, Union, Optional
  3. import time
  4. import uuid
  5. from peewee import *
  6. from apps.web.models.users import UserModel, Users
  7. from utils.utils import (
  8. verify_password,
  9. get_password_hash,
  10. bearer_scheme,
  11. create_token,
  12. )
  13. from apps.web.internal.db import DB
  14. ####################
  15. # DB MODEL
  16. ####################
  17. class Auth(Model):
  18. id = CharField(unique=True)
  19. email = CharField()
  20. password = CharField()
  21. active = BooleanField()
  22. class Meta:
  23. database = DB
  24. class AuthModel(BaseModel):
  25. id: str
  26. email: str
  27. password: str
  28. active: bool = True
  29. ####################
  30. # Forms
  31. ####################
  32. class Token(BaseModel):
  33. token: str
  34. token_type: str
  35. class UserResponse(BaseModel):
  36. id: str
  37. email: str
  38. name: str
  39. role: str
  40. profile_image_url: str
  41. class SigninResponse(Token, UserResponse):
  42. pass
  43. class SigninForm(BaseModel):
  44. email: str
  45. password: str
  46. class SignupForm(BaseModel):
  47. name: str
  48. email: str
  49. password: str
  50. class AuthsTable:
  51. def __init__(self, db):
  52. self.db = db
  53. self.db.create_tables([Auth])
  54. def insert_new_auth(
  55. self, email: str, password: str, name: str, role: str = "pending"
  56. ) -> Optional[UserModel]:
  57. print("insert_new_auth")
  58. id = str(uuid.uuid4())
  59. auth = AuthModel(
  60. **{"id": id, "email": email, "password": password, "active": True}
  61. )
  62. result = Auth.create(**auth.model_dump())
  63. print(result)
  64. user = Users.insert_new_user(id, name, email, role)
  65. print(result, user)
  66. if result and user:
  67. return user
  68. else:
  69. return None
  70. def authenticate_user(self, email: str, password: str) -> Optional[UserModel]:
  71. print("authenticate_user", email)
  72. try:
  73. auth = Auth.get(Auth.email == email, Auth.active == True)
  74. print(auth.email)
  75. if auth:
  76. print(password, str(auth.password))
  77. print(verify_password(password, str(auth.password)))
  78. if verify_password(password, auth.password):
  79. user = Users.get_user_by_id(auth.id)
  80. print(user)
  81. return user
  82. else:
  83. return None
  84. else:
  85. return None
  86. except:
  87. return None
  88. Auths = AuthsTable(DB)