Introduces schemas for user management, token handling, and password hashing. Implements routes for user registration, login, token refresh, and user info retrieval. Sets up authentication dependencies and integrates the API router with the application.
66 lines
1.9 KiB
Python
66 lines
1.9 KiB
Python
from typing import Optional
|
|
from uuid import UUID
|
|
from pydantic import BaseModel, EmailStr, Field, field_validator
|
|
from datetime import datetime
|
|
from passlib.hash import bcrypt
|
|
|
|
|
|
# Base schema with shared user attributes
|
|
class UserBase(BaseModel):
|
|
"""Base schema with common user attributes."""
|
|
email: EmailStr
|
|
first_name: str
|
|
last_name: str
|
|
|
|
|
|
# Schema for creating a new user
|
|
class UserCreate(UserBase):
|
|
"""Schema for user registration."""
|
|
password: str = Field(
|
|
...,
|
|
min_length=8,
|
|
description="Password must be at least 8 characters"
|
|
)
|
|
|
|
@field_validator('password')
|
|
def password_strength(cls, v):
|
|
# Add more complex password validation if needed
|
|
if len(v) < 8:
|
|
raise ValueError('Password must be at least 8 characters')
|
|
return v
|
|
|
|
def hash_password(self) -> str:
|
|
"""Hash the password before saving it to the database."""
|
|
return bcrypt.hash(self.password)
|
|
|
|
|
|
# Schema for updating user details
|
|
class UserUpdate(BaseModel):
|
|
"""Schema for updating user information."""
|
|
email: Optional[EmailStr] = None
|
|
first_name: Optional[str] = None
|
|
last_name: Optional[str] = None
|
|
phone_number: Optional[str] = None
|
|
is_active: Optional[bool] = None
|
|
preferences: Optional[dict] = None # Provide preferences support
|
|
|
|
|
|
# Schema for user responses (read-only fields)
|
|
class UserResponse(UserBase):
|
|
"""Schema for user responses in API."""
|
|
id: UUID
|
|
is_active: bool
|
|
is_superuser: bool # Include roles or superuser flags if needed
|
|
preferences: Optional[dict] = None # Include preferences in response
|
|
created_at: datetime
|
|
updated_at: Optional[datetime] = None
|
|
|
|
class Config:
|
|
orm_mode = True # Enable mapping SQLAlchemy models to this schema
|
|
|
|
|
|
# Schema for user authentication (e.g., login requests)
|
|
class UserAuth(BaseModel):
|
|
"""Schema for user authentication."""
|
|
email: EmailStr
|
|
password: str |