File size: 1,549 Bytes
71a3948
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93cf1dc
71a3948
93cf1dc
71a3948
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from sqlmodel import Session
from datetime import timedelta

from src.database import get_session
from src.auth import authenticate_user, create_access_token
from src.models import Token
from src.config import settings

router = APIRouter(tags=["Authentication"])

@router.post("/token", response_model=Token)
async def login_for_access_token(
    form_data: OAuth2PasswordRequestForm = Depends(), 
    db: Session = Depends(get_session)
):
    """
    Provides a JWT access token for a valid user (student or staff).
    
    This is the primary login endpoint. It uses the standard OAuth2
    password flow. The client sends 'username' and 'password' in a
    form-data body.
    """
    # The authenticate_user function will check both Student and User tables
    user = authenticate_user(db, form_data.username, form_data.password)
    
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect username or password",
            headers={"WWW-Authenticate": "Bearer"},
        )
        
    # Create the JWT token
    access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
    # FIX: Use username instead of email
    access_token = create_access_token(
        data={"sub": user.username}, expires_delta=access_token_expires  # CHANGED from user.email
    )
    
    return {"access_token": access_token, "token_type": "bearer"}