from typing import Optional from sqlmodel import Field, SQLModel, Session, select from db.DB import DB, DBException from sqlalchemy import exc import hashlib, uuid, base64 class User(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: Optional[str] = None login: str = Field(max_length=255) email: str = Field(sa_column_kwargs={'unique': True}) age: Optional[int] = None password_hash: str = Field(max_length=255) status: Optional[int] = Field(default=0) def create(self): db = DB() session = Session(db.get_engine()) self.password_hash = self.create_password_hash(self.password_hash) session.add(self) try: session.commit() session.refresh(self) except exc.SQLAlchemyError as sqla_error: return DBException(sqla_error) session.close() return self @staticmethod def get_by_id(user_id): db = DB() with Session(db.get_engine()) as s: statement = select(User).where(User.id == user_id) res = s.exec(statement) return res.first() @staticmethod def create_password_hash(password): salt = "5gz" # Adding salt at the last of the password data_base_password = password + salt # Encoding the password hashed = hashlib.md5(data_base_password.encode()) return hashed.hexdigest()