-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.py
More file actions
157 lines (139 loc) · 5.16 KB
/
auth.py
File metadata and controls
157 lines (139 loc) · 5.16 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
from fastapi.security import OAuth2PasswordBearer
from passlib.context import CryptContext
import jwt
from datetime import datetime, timedelta
from fastapi import Depends, HTTPException, status
import os
from dotenv import load_dotenv
import logging
from typing import Optional, Dict, Any, Union
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.StreamHandler(),
logging.FileHandler("auth.log")
]
)
logger = logging.getLogger("auth")
# Load environment variables
load_dotenv()
# Constants
SECRET_KEY = os.getenv("SECRET_KEY")
ALGORITHM = os.getenv("ALGORITHM")
ACCESS_TOKEN_EXPIRE_MINUTES = int(os.getenv("ACCESS_TOKEN_EXPIRE_MINUTES", "30"))
# Verify environment variables are set
if not SECRET_KEY:
logger.error("SECRET_KEY environment variable not set")
raise ValueError("SECRET_KEY environment variable must be set")
if not ALGORITHM:
logger.error("ALGORITHM environment variable not set")
raise ValueError("ALGORITHM environment variable must be set")
# Password and token handling
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="login")
def verify_password(plain_password: str, hashed_password: str) -> bool:
"""Verify a password against a hash."""
try:
return pwd_context.verify(plain_password, hashed_password)
except Exception as e:
logger.error(f"Password verification error: {str(e)}")
return False
def get_password_hash(password: str) -> str:
"""Generate a password hash."""
try:
return pwd_context.hash(password)
except Exception as e:
logger.error(f"Password hashing error: {str(e)}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Could not process password"
)
def create_access_token(data: Dict[str, Any], expires_delta: Optional[timedelta] = None) -> str:
"""
Create a JWT access token.
Args:
data: Data to encode in the token
expires_delta: Optional custom expiration time
Returns:
Encoded JWT token as string
"""
try:
to_encode = data.copy()
expire = datetime.utcnow() + (
expires_delta if expires_delta else timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
)
to_encode.update({"exp": expire})
return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
except Exception as e:
logger.error(f"Token creation error: {str(e)}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Could not create access token"
)
def decode_token(token: str) -> Dict[str, Any]:
"""
Decode and validate a JWT token.
Args:
token: JWT token to decode
Returns:
Decoded token payload
Raises:
HTTPException: If token is invalid or expired
"""
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
return payload
except jwt.ExpiredSignatureError:
logger.warning("Expired token attempt")
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Token has expired",
headers={"WWW-Authenticate": "Bearer"},
)
except jwt.InvalidTokenError as e:
logger.warning(f"Invalid token: {str(e)}")
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authentication token",
headers={"WWW-Authenticate": "Bearer"},
)
except Exception as e:
logger.error(f"Token decode error: {str(e)}")
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
def get_current_user(token: str = Depends(oauth2_scheme)) -> str:
"""
Dependency to get the current authenticated user.
Args:
token: JWT token from authorization header
Returns:
Username extracted from the token
Raises:
HTTPException: If authentication fails
"""
try:
payload = decode_token(token)
username: str = payload.get("sub")
if username is None:
logger.warning("Token missing 'sub' claim")
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid token content",
headers={"WWW-Authenticate": "Bearer"},
)
return username
except HTTPException:
# Re-raise HTTP exceptions from decode_token
raise
except Exception as e:
logger.error(f"Unexpected authentication error: {str(e)}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Authentication system error",
headers={"WWW-Authenticate": "Bearer"},
)