-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.py
More file actions
189 lines (145 loc) · 4.63 KB
/
auth.py
File metadata and controls
189 lines (145 loc) · 4.63 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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
"""
Authentication utilities for secure user management.
Handles password hashing, JWT tokens, and user verification.
"""
import os
from datetime import datetime, timedelta, timezone
from typing import Any, Optional
from dotenv import load_dotenv
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from jose import JWTError, jwt
from passlib.context import CryptContext
from sqlalchemy.orm import Session
from database import User, get_db
load_dotenv()
# Security configuration
SECRET_KEY: str = os.getenv("SECRET_KEY", "your-secret-key-change-in-production")
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
# Password hashing context
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
# HTTP Bearer for token authentication
security = HTTPBearer()
def hash_password(password: str) -> str:
"""
Hash a plain password using bcrypt.
Args:
password: Plain text password
Returns:
Hashed password string
"""
return pwd_context.hash(password)
def verify_password(plain_password: str, hashed_password: str) -> bool:
"""
Verify a plain password against its hash.
Args:
plain_password: Plain text password
hashed_password: Hashed password from database
Returns:
True if password matches, False otherwise
"""
return pwd_context.verify(plain_password, hashed_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 expiration time delta
Returns:
Encoded JWT token
"""
to_encode: dict[str, Any] = data.copy()
if expires_delta:
expire: datetime = datetime.now(timezone.utc) + expires_delta
else:
expire = datetime.now(timezone.utc) + timedelta(
minutes=ACCESS_TOKEN_EXPIRE_MINUTES
)
to_encode.update({"exp": expire})
encoded_jwt: str = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
def verify_token(token: str) -> Optional[str]:
"""
Verify and decode a JWT token.
Args:
token: JWT token string
Returns:
Email from token if valid, None otherwise
"""
try:
payload: dict[str, Any] = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
email: Optional[str] = payload.get("sub")
if email is None:
return None
return email
except JWTError:
return None
def get_user_by_email(db: Session, email: str) -> Optional[User]:
"""
Get user by email from database.
Args:
db: Database session
email: User email
Returns:
User object if found, None otherwise
"""
return db.query(User).filter(User.email == email).first()
def get_user_by_username(db: Session, username: str) -> Optional[User]:
"""
Get user by username from database.
Args:
db: Database session
username: Username
Returns:
User object if found, None otherwise
"""
return db.query(User).filter(User.username == username).first()
def authenticate_user(db: Session, email: str, password: str) -> Optional[User]:
"""
Authenticate user with email and password.
Args:
db: Database session
email: User email
password: Plain text password
Returns:
User object if authentication successful, None otherwise
"""
user: User | None = get_user_by_email(db, email)
if not user:
return None
if not verify_password(password, str(user.hashed_password)):
return None
return user
def get_current_user(
credentials: HTTPAuthorizationCredentials = Depends(security),
db: Session = Depends(get_db),
) -> User:
"""
Get current authenticated user from JWT token.
Args:
credentials: HTTP Bearer credentials
db: Database session
Returns:
Current authenticated user
Raises:
HTTPException: If authentication fails
"""
token: str = credentials.credentials
email: str | None = verify_token(token)
if email is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
user: User | None = get_user_by_email(db, email)
if user is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="User not found",
headers={"WWW-Authenticate": "Bearer"},
)
return user