-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.py
More file actions
84 lines (71 loc) · 3.21 KB
/
auth.py
File metadata and controls
84 lines (71 loc) · 3.21 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
from datetime import datetime, timedelta
from typing import Optional
import os # NEW: Import os
from jose import JWTError, jwt
from passlib.context import CryptContext
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from sqlalchemy.orm import Session
from . import models, schemas
from .database import get_db
# Configuration for password hashing
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
# JWT Secret Key and Algorithm (IMPORTANT: Use a strong, random key in production)
# For development, you can generate one with: openssl rand -hex 32
SECRET_KEY = os.getenv("SECRET_KEY", "super-secret-default-key-please-change-me") # UPDATED: Load from environment variable
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
# OAuth2PasswordBearer for token extraction from request headers
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
def verify_password(plain_password: str, hashed_password: str) -> bool:
"""Verifies a plain password against a hashed password."""
return pwd_context.verify(plain_password, hashed_password)
def get_password_hash(password: str) -> str:
"""Hashes a plain password."""
return pwd_context.hash(password)
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str:
"""Creates a JWT access token."""
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
def get_user(db: Session, email: str):
"""Retrieves a user by email from the database."""
return db.query(models.User).filter(models.User.email == email).first()
def get_user_by_id(db: Session, user_id: int):
"""Retrieves a user by ID from the database."""
return db.query(models.User).filter(models.User.id == user_id).first()
async def get_current_user(token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)):
"""
FastAPI dependency to get the current authenticated user from a JWT token.
Raises HTTPException if the token is invalid or user not found.
"""
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
email: str = payload.get("sub")
if email is None:
raise credentials_exception
token_data = schemas.TokenData(email=email)
except JWTError:
raise credentials_exception
user = get_user(db, email=token_data.email)
if user is None:
raise credentials_exception
return user
async def get_current_active_user(current_user: schemas.User = Depends(get_current_user)):
"""
FastAPI dependency to get the current active authenticated user.
Raises HTTPException if the user is inactive.
"""
if not current_user.is_active:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Inactive user")
return current_user