Automated Action 794d172f85 Add user authentication system with login, signup, and JWT tokens
- Added user model and schema definitions
- Implemented JWT token authentication
- Created endpoints for user registration and login
- Added secure password hashing with bcrypt
- Set up SQLite database with SQLAlchemy
- Created Alembic migrations
- Added user management endpoints
- Included health check endpoint

generated with BackendIM... (backend.im)
2025-05-11 22:51:17 +00:00

37 lines
1.3 KiB
Python

from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session
from app.db.database import get_db
from app.schemas.user import UserCreate, User, Token
from app.services.auth_service import auth_service
router = APIRouter()
@router.post("/register", response_model=User, status_code=status.HTTP_201_CREATED)
def register(user_in: UserCreate, db: Session = Depends(get_db)):
"""
Register a new user.
"""
return auth_service.register_user(db, user_in)
@router.post("/login", response_model=Token)
def login(form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)):
"""
OAuth2 compatible token login, get an access token for future requests.
"""
user = auth_service.authenticate_user(db, form_data.username, form_data.password)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect email or password",
headers={"WWW-Authenticate": "Bearer"},
)
return auth_service.create_token(user)
@router.get("/me", response_model=User)
def read_users_me(current_user: User = Depends(auth_service.get_current_user)):
"""
Get current user information.
"""
return current_user