feat(auth): implement JWT authentication with secure password hashing
This commit is contained in:
parent
6656a8782c
commit
56df3228a4
7 changed files with 146 additions and 74 deletions
43
backend/hermes/app/api/auth.py
Normal file
43
backend/hermes/app/api/auth.py
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
from fastapi import APIRouter, Depends, HTTPException, Response
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.security import create_access_token, verify_password
|
||||
from app.db.database import get_db
|
||||
from app.models.user import User
|
||||
from app.schemas.user import LoginRequest
|
||||
|
||||
router = APIRouter(
|
||||
prefix="/auth",
|
||||
tags=["Authentication"],
|
||||
)
|
||||
|
||||
|
||||
@router.post("/login")
|
||||
def login(
|
||||
login: LoginRequest,
|
||||
response: Response,
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
user = db.query(User).filter(User.username == login.username).first()
|
||||
|
||||
if not user:
|
||||
raise HTTPException(status_code=401, detail="Ungültige Anmeldedaten")
|
||||
|
||||
if not verify_password(login.password, user.password_hash):
|
||||
raise HTTPException(status_code=401, detail="Ungültige Anmeldedaten")
|
||||
|
||||
token = create_access_token(user.username)
|
||||
|
||||
response.set_cookie(
|
||||
key="access_token",
|
||||
value=token,
|
||||
httponly=True,
|
||||
secure=True,
|
||||
samesite="lax",
|
||||
max_age=3600,
|
||||
)
|
||||
|
||||
return {
|
||||
"message": "Login erfolgreich",
|
||||
"user": user.username,
|
||||
}
|
||||
29
backend/hermes/app/core/security.py
Normal file
29
backend/hermes/app/core/security.py
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
from datetime import UTC, datetime, timedelta
|
||||
|
||||
from jose import jwt
|
||||
from pwdlib import PasswordHash
|
||||
|
||||
password_hash = PasswordHash.recommended()
|
||||
|
||||
SECRET_KEY = "CHANGE_ME"
|
||||
ALGORITHM = "HS256"
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES = 60
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return password_hash.hash(password)
|
||||
|
||||
|
||||
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
||||
return password_hash.verify(plain_password, hashed_password)
|
||||
|
||||
|
||||
def create_access_token(subject: str) -> str:
|
||||
expire = datetime.now(UTC) + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
|
||||
|
||||
payload = {
|
||||
"sub": subject,
|
||||
"exp": expire,
|
||||
}
|
||||
|
||||
return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)
|
||||
|
|
@ -1,26 +1,29 @@
|
|||
from fastapi import FastAPI
|
||||
from app.api.users import router as users_router
|
||||
|
||||
from app.db.health import check_database
|
||||
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from app.api.auth import router as auth_router
|
||||
from app.api.users import router as users_router
|
||||
from app.db.health import check_database
|
||||
|
||||
app = FastAPI(
|
||||
title="Hermes API",
|
||||
version="0.1.0",
|
||||
description="Backend von Olympus"
|
||||
description="Backend von Olympus",
|
||||
)
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=[
|
||||
"http://localhost:3000",
|
||||
"http://127.0.0.1:3000",
|
||||
"https://crm.funktechnik-schubert.de",
|
||||
],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
app.include_router(auth_router)
|
||||
app.include_router(users_router)
|
||||
|
||||
|
||||
|
|
@ -28,7 +31,7 @@ app.include_router(users_router)
|
|||
def root():
|
||||
return {
|
||||
"service": "Hermes",
|
||||
"status": "running"
|
||||
"status": "running",
|
||||
}
|
||||
|
||||
|
||||
|
|
@ -36,5 +39,5 @@ def root():
|
|||
def health():
|
||||
return {
|
||||
"status": "healthy",
|
||||
"database": check_database()
|
||||
"database": check_database(),
|
||||
}
|
||||
|
|
@ -2,6 +2,7 @@ from sqlalchemy.orm import Session
|
|||
|
||||
from app.models.user import User
|
||||
from app.schemas.user import UserCreate
|
||||
from app.core.security import hash_password
|
||||
|
||||
|
||||
class UserRepository:
|
||||
|
|
@ -14,10 +15,10 @@ class UserRepository:
|
|||
def create(db: Session, user: UserCreate):
|
||||
|
||||
db_user = User(
|
||||
username=user.username,
|
||||
email=user.email,
|
||||
password_hash=user.password
|
||||
)
|
||||
username=user.username,
|
||||
email=user.email,
|
||||
password_hash=hash_password(user.password),
|
||||
)
|
||||
|
||||
db.add(db_user)
|
||||
db.commit()
|
||||
|
|
|
|||
|
|
@ -6,6 +6,10 @@ class UserCreate(BaseModel):
|
|||
email: EmailStr
|
||||
password: str
|
||||
|
||||
class LoginRequest(BaseModel):
|
||||
username: str
|
||||
password: str
|
||||
|
||||
|
||||
class UserResponse(BaseModel):
|
||||
id: int
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue