
- Set up FastAPI application with CORS and proper structure - Created User model with SQLAlchemy and SQLite database - Implemented JWT-based authentication with bcrypt password hashing - Added user registration, login, and profile endpoints - Created health check endpoint for monitoring - Set up Alembic for database migrations - Added comprehensive API documentation - Configured proper project structure with separate modules - Updated README with complete setup and usage instructions
91 lines
3.3 KiB
Python
91 lines
3.3 KiB
Python
from datetime import timedelta
|
|
from fastapi import APIRouter, Depends, HTTPException, status
|
|
from fastapi.security import OAuth2PasswordRequestForm
|
|
from sqlalchemy.orm import Session
|
|
from app.db.session import get_db
|
|
from app.models.user import User
|
|
from app.schemas.user import UserCreate, UserResponse, UserLogin, Token
|
|
from app.core.security import verify_password, get_password_hash, create_access_token, ACCESS_TOKEN_EXPIRE_MINUTES
|
|
from app.utils.auth import get_current_active_user
|
|
|
|
router = APIRouter()
|
|
|
|
@router.post("/register", response_model=UserResponse, status_code=status.HTTP_201_CREATED)
|
|
async def register_user(user: UserCreate, db: Session = Depends(get_db)):
|
|
# Check if user already exists
|
|
db_user = db.query(User).filter(User.email == user.email).first()
|
|
if db_user:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="Email already registered"
|
|
)
|
|
|
|
# Create new user
|
|
hashed_password = get_password_hash(user.password)
|
|
db_user = User(
|
|
email=user.email,
|
|
hashed_password=hashed_password
|
|
)
|
|
db.add(db_user)
|
|
db.commit()
|
|
db.refresh(db_user)
|
|
|
|
return db_user
|
|
|
|
@router.post("/login", response_model=Token)
|
|
async def login_user(user_credentials: UserLogin, db: Session = Depends(get_db)):
|
|
user = db.query(User).filter(User.email == user_credentials.email).first()
|
|
|
|
if not user or not verify_password(user_credentials.password, user.hashed_password):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Incorrect email or password",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
|
|
if not user.is_active:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="Inactive user"
|
|
)
|
|
|
|
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
|
|
access_token = create_access_token(
|
|
data={"sub": user.email}, expires_delta=access_token_expires
|
|
)
|
|
return {"access_token": access_token, "token_type": "bearer"}
|
|
|
|
@router.post("/token", response_model=Token)
|
|
async def login_for_access_token(
|
|
form_data: OAuth2PasswordRequestForm = Depends(),
|
|
db: Session = Depends(get_db)
|
|
):
|
|
user = db.query(User).filter(User.email == form_data.username).first()
|
|
|
|
if not user or not verify_password(form_data.password, user.hashed_password):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Incorrect email or password",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
|
|
if not user.is_active:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="Inactive user"
|
|
)
|
|
|
|
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
|
|
access_token = create_access_token(
|
|
data={"sub": user.email}, expires_delta=access_token_expires
|
|
)
|
|
return {"access_token": access_token, "token_type": "bearer"}
|
|
|
|
@router.get("/me", response_model=UserResponse)
|
|
async def read_users_me(current_user: User = Depends(get_current_active_user)):
|
|
return current_user
|
|
|
|
@router.post("/logout")
|
|
async def logout_user():
|
|
# In a stateless JWT system, logout is handled client-side by discarding the token
|
|
return {"message": "Successfully logged out"} |