75 lines
2.5 KiB
Python
75 lines
2.5 KiB
Python
from fastapi import APIRouter, HTTPException, Depends
|
|
from sqlalchemy.orm import Session
|
|
from passlib.hash import argon2
|
|
import secrets
|
|
|
|
from database import get_db
|
|
import models, validation
|
|
|
|
router = APIRouter(prefix="/api/auth", tags=["Authentication"])
|
|
|
|
|
|
@router.post("/init")
|
|
def initialize_system(request: validation.InitRequest, db: Session = Depends(get_db)):
|
|
if db.query(models.SecurityConfig).first():
|
|
raise HTTPException(status_code=400, detail="System został już zainicjowany.")
|
|
|
|
recovery_key = secrets.token_hex(16)
|
|
|
|
new_config = models.SecurityConfig(
|
|
password_hash=argon2.using(type="ID").hash(request.password),
|
|
recovery_key_hash=argon2.using(type="ID").hash(recovery_key),
|
|
)
|
|
db.add(new_config)
|
|
db.commit()
|
|
|
|
return {
|
|
"status": "success",
|
|
"message": "System zainicjowany pomyślnie.",
|
|
"recovery_key": recovery_key,
|
|
}
|
|
|
|
|
|
@router.post("/reset-password")
|
|
def reset_password(request: validation.InitRequest, db: Session = Depends(get_db)):
|
|
config = db.query(models.SecurityConfig).first()
|
|
if not config:
|
|
raise HTTPException(status_code=404, detail="System nie zainicjowany.")
|
|
|
|
config.password_hash = argon2.using(type="ID").hash(request.password)
|
|
db.commit()
|
|
return {"status": "success", "message": "Hasło zostało zmienione."}
|
|
|
|
|
|
@router.delete("/account")
|
|
def delete_account(db: Session = Depends(get_db)):
|
|
db.query(models.SecurityConfig).delete()
|
|
db.commit()
|
|
return {"status": "success", "message": "Konto zostało usunięte."}
|
|
|
|
|
|
@router.post("/login")
|
|
def login(request: validation.LoginRequest, db: Session = Depends(get_db)):
|
|
config = db.query(models.SecurityConfig).first()
|
|
if not config:
|
|
raise HTTPException(status_code=500, detail="Brak konfiguracji.")
|
|
|
|
if request.is_recovery:
|
|
if not argon2.using(type="ID").verify(
|
|
request.password, config.recovery_key_hash
|
|
):
|
|
raise HTTPException(
|
|
status_code=401, detail="Nieprawidłowy klucz przywracania."
|
|
)
|
|
return {"status": "success", "message": "Zalogowano awaryjnie."}
|
|
else:
|
|
if not argon2.using(type="ID").verify(request.password, config.password_hash):
|
|
raise HTTPException(status_code=401, detail="Nieprawidłowe hasło główne.")
|
|
return {"status": "success", "message": "Autoryzacja pomyślna."}
|
|
|
|
|
|
@router.get("/status")
|
|
def check_status(db: Session = Depends(get_db)):
|
|
is_initialized = db.query(models.SecurityConfig).first() is not None
|
|
return {"is_initialized": is_initialized}
|