49 lines
1.3 KiB
Python
49 lines
1.3 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""Login-Endpoint – liefert JWT Token für Desktop + Web Clients."""
|
||
|
||
from pydantic import BaseModel
|
||
from fastapi import APIRouter, Depends, HTTPException
|
||
from sqlalchemy.orm import Session
|
||
|
||
from ..database import get_db
|
||
from ..core.models import Employee
|
||
from .auth import verify_password, create_access_token
|
||
from ..core.schemas import EmployeeRead
|
||
|
||
import datetime
|
||
|
||
router = APIRouter(prefix="/auth", tags=["Authentifizierung"])
|
||
|
||
|
||
class LoginRequest(BaseModel):
|
||
email: str
|
||
password: str
|
||
|
||
|
||
class LoginResponse(BaseModel):
|
||
access_token: str
|
||
token_type: str = "bearer"
|
||
employee: EmployeeRead
|
||
|
||
|
||
@router.post("/login", response_model=LoginResponse)
|
||
def login(data: LoginRequest, db: Session = Depends(get_db)):
|
||
emp = db.query(Employee).filter(Employee.email == data.email).first()
|
||
if not emp or not emp.password_hash:
|
||
raise HTTPException(401, "E-Mail oder Passwort falsch")
|
||
|
||
if not verify_password(data.password, emp.password_hash):
|
||
raise HTTPException(401, "E-Mail oder Passwort falsch")
|
||
|
||
if not emp.is_active:
|
||
raise HTTPException(403, "Konto deaktiviert")
|
||
|
||
emp.last_login = datetime.datetime.utcnow()
|
||
db.commit()
|
||
|
||
token = create_access_token(emp.id, emp.role.value)
|
||
return LoginResponse(
|
||
access_token=token,
|
||
employee=EmployeeRead.model_validate(emp),
|
||
)
|