
- Set up project structure with FastAPI and dependency files - Configure SQLAlchemy with SQLite database - Implement user authentication using JWT tokens - Create comprehensive API routes for user management - Add health check endpoint for application monitoring - Set up Alembic for database migrations - Add detailed documentation in README.md
63 lines
1.6 KiB
Python
63 lines
1.6 KiB
Python
from datetime import datetime, timedelta
|
|
from typing import Any, Optional, Union
|
|
|
|
from jose import jwt
|
|
from passlib.context import CryptContext
|
|
|
|
from app.core.config import settings
|
|
|
|
# Password hashing context
|
|
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
|
|
|
|
|
def create_access_token(
|
|
subject: Union[str, Any], expires_delta: Optional[timedelta] = None
|
|
) -> str:
|
|
"""
|
|
Create a JWT access token.
|
|
|
|
Args:
|
|
subject: The subject of the token, typically the user ID.
|
|
expires_delta: Optional timedelta for token expiration.
|
|
|
|
Returns:
|
|
Encoded JWT token as a string.
|
|
"""
|
|
if expires_delta:
|
|
expire = datetime.utcnow() + expires_delta
|
|
else:
|
|
expire = datetime.utcnow() + timedelta(
|
|
minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES
|
|
)
|
|
|
|
to_encode = {"exp": expire, "sub": str(subject)}
|
|
|
|
return jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
|
|
|
|
|
|
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
|
"""
|
|
Verify if a plain password matches a hashed password.
|
|
|
|
Args:
|
|
plain_password: The plain text password.
|
|
hashed_password: The hashed password from the database.
|
|
|
|
Returns:
|
|
True if passwords match, False otherwise.
|
|
"""
|
|
return pwd_context.verify(plain_password, hashed_password)
|
|
|
|
|
|
def get_password_hash(password: str) -> str:
|
|
"""
|
|
Hash a password using the configured password hashing algorithm.
|
|
|
|
Args:
|
|
password: The plain text password to hash.
|
|
|
|
Returns:
|
|
A hashed password string.
|
|
"""
|
|
return pwd_context.hash(password)
|