41 lines
1.3 KiB
Python
41 lines
1.3 KiB
Python
from typing import Any
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, status
|
|
from fastapi.security import OAuth2PasswordRequestForm
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app import crud
|
|
from app.api.v1.deps import get_db
|
|
from app.core.security import create_access_token
|
|
from app.models.role import Role
|
|
from app.schemas.token import Token
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
@router.post("/login/access-token", response_model=Token)
|
|
def login_access_token(
|
|
db: Session = Depends(get_db), form_data: OAuth2PasswordRequestForm = Depends()
|
|
) -> Any:
|
|
"""
|
|
OAuth2 compatible token login, get an access token for future requests
|
|
"""
|
|
user = crud.user.authenticate(
|
|
db, username=form_data.username, password=form_data.password
|
|
)
|
|
if not user:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Incorrect username or password",
|
|
)
|
|
if not crud.user.is_active(user):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED, detail="Inactive user"
|
|
)
|
|
|
|
# Get the role name for the user
|
|
role_obj = db.query(Role).filter(Role.id == user.role_id).first()
|
|
role_name = role_obj.name if role_obj else "user"
|
|
|
|
access_token = create_access_token(user.id, role=role_name)
|
|
return {"access_token": access_token, "token_type": "bearer"} |