users.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435
  1. from sqlalchemy.orm import Session
  2. from .schemas import UserInDB
  3. from .db import Base
  4. from passlib.context import CryptContext
  5. from sqlalchemy import Column, Integer, String
  6. # Password hashing configuration
  7. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  8. class UserModel(Base):
  9. __tablename__ = "users"
  10. id = Column(Integer, primary_key=True, index=True)
  11. username = Column(String, unique=True, index=True)
  12. email = Column(String, unique=True, index=True)
  13. hashed_password = Column(String)
  14. def get_password_hash(password: str) -> str:
  15. return pwd_context.hash(password)
  16. def verify_password(plain_password: str, hashed_password: str) -> bool:
  17. return pwd_context.verify(plain_password, hashed_password)
  18. def authenticate_user(db: Session, username: str, password: str) -> UserInDB | None:
  19. user = get_by_username(db, username)
  20. if not user or not verify_password(password, user.hashed_password):
  21. return None
  22. return user
  23. def get_by_username(db: Session, username: str) -> UserInDB | None:
  24. return db.query(UserModel).filter(UserModel.username == username).first()