
- Set up FastAPI project structure with main.py and requirements.txt - Create User model with SQLAlchemy and SQLite database - Implement JWT token-based authentication system - Add password hashing with bcrypt - Create auth endpoints: register, login, and protected /me route - Set up Alembic for database migrations - Add health check endpoint with database status - Configure CORS to allow all origins - Update README with setup instructions and environment variables
57 lines
2.0 KiB
Python
57 lines
2.0 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, UserLogin, Token, User as UserSchema
|
|
from app.core.security import verify_password, get_password_hash, create_access_token, ACCESS_TOKEN_EXPIRE_MINUTES
|
|
from app.core.auth import get_current_user
|
|
|
|
router = APIRouter()
|
|
|
|
@router.post("/register", response_model=UserSchema)
|
|
def register(user: UserCreate, db: Session = Depends(get_db)):
|
|
db_user = db.query(User).filter(User.email == user.email).first()
|
|
if db_user:
|
|
raise HTTPException(
|
|
status_code=400,
|
|
detail="Email already registered"
|
|
)
|
|
|
|
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)
|
|
def login(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.get("/me", response_model=UserSchema)
|
|
def read_users_me(current_user: User = Depends(get_current_user)):
|
|
return current_user |