61 lines
1.9 KiB
Python

from datetime import timedelta
from typing import Any
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app import crud, schemas
from app.core.config import settings
from app.core.security import create_access_token
from app.db.session import get_db
router = APIRouter()
@router.post("/login", response_model=schemas.Token)
def login_access_token(login_data: schemas.LoginRequest, db: Session = Depends(get_db)) -> Any:
"""
JSON-based token login, get an access token for future requests
"""
user = crud.user.authenticate(db, email=login_data.email, password=login_data.password)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect email or password",
headers={"WWW-Authenticate": "Bearer"},
)
elif not crud.user.is_active(user):
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Inactive user")
access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
return {
"access_token": create_access_token(user.id, expires_delta=access_token_expires),
"token_type": "bearer",
}
@router.post("/register", response_model=schemas.User)
def register_user(
*,
db: Session = Depends(get_db),
user_in: schemas.UserCreate,
) -> Any:
"""
Register a new user.
"""
user = crud.user.get_by_email(db, email=user_in.email)
if user:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="A user with this email already exists",
)
username_exists = crud.user.get_by_username(db, username=user_in.username)
if username_exists:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="A user with this username already exists",
)
user = crud.user.create(db, obj_in=user_in)
return user