Repository navigation
Expand file tree
/
Copy pathutils.py
More file actions
70 lines (53 loc) · 2.75 KB
/
Copy pathutils.py
File metadata and controls
70 lines (53 loc) · 2.75 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# blog-api/utils.py
from datetime import datetime, timedelta
from typing import Annotated, Any
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt
from passlib.context import CryptContext
# NOT: schemas.py dosyanızın aynı klasörde olması gerekir
# from schemas import User # Şu anlık bu import'a gerek yok, payload'ı döndüreceğiz.
# --- KONFİGÜRASYON ---
# ÖNEMLİ: Gerçek uygulamalarda bu anahtarın çevresel değişkenlerde saklanması gerekir!
SECRET_KEY = "supersecretkey"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
# Şifre Hashing Ayarı
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
# FastAPI güvenlik şeması (Token'ı nerede arayacağını ve login endpoint'ini belirtir)
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
# --- ŞİFRELEME FONKSİYONLARI ---
def verify_password(plain_password: str, hashed_password: str) -> bool:
"""Verilen düz metin şifreyi hashlenmiş şifreyle karşılaştırır."""
return pwd_context.verify(plain_password, hashed_password)
def get_password_hash(password: str) -> str:
"""Verilen şifrenin hashlenmiş halini döndürür."""
return pwd_context.hash(password)
# --- JWT TOKEN FONKSİYONLARI ---
def create_access_token(data: dict, expires_delta: timedelta | None = None) -> str:
"""Erişim token'ı (JWT) oluşturur."""
to_encode = data.copy()
expire = datetime.utcnow() + (expires_delta or timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES))
to_encode.update({"exp": expire.timestamp()})
return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
# --- GÜVENLİK BAĞIMLILIĞI (GÜN 4) ---
def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]) -> Any:
"""
Gelen isteğin 'Authorization' başlığındaki JWT token'ını doğrular.
Geçersizse 401 hatası fırlatır, geçerliyse token içindeki kullanıcı bilgisini döndürür.
"""
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authentication credentials", # Geçersiz kimlik doğrulama bilgileri
headers={"WWW-Authenticate": "Bearer"},
)
try:
# Token'ı SECRET_KEY ile çözme
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
username: str = payload.get("sub") # 'sub' (subject) alanında kullanıcı adı beklenir
if username is None:
raise credentials_exception
# Eğer DB'den kullanıcı detaylarını çekmeyeceksek, payload'ı döndürebiliriz.
return {"username": username}
except JWTError:
raise credentials_exception