Chandima Prabhath commited on
Commit ·
8ea6426
1
Parent(s): 0678429
Refactor authentication logic to utilize OAuth2PasswordBearer for token extraction and improve code readability
Browse files
main.py
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
-
from fastapi import FastAPI, HTTPException, Depends, status, APIRouter
|
| 2 |
-
from fastapi.security import OAuth2PasswordRequestForm
|
| 3 |
from fastapi.middleware.cors import CORSMiddleware
|
| 4 |
from datetime import datetime, timedelta, timezone
|
| 5 |
from passlib.context import CryptContext
|
|
@@ -24,6 +24,9 @@ app = FastAPI()
|
|
| 24 |
# allow_headers=["*"],
|
| 25 |
# )
|
| 26 |
|
|
|
|
|
|
|
|
|
|
| 27 |
# Password hashing utilities
|
| 28 |
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
| 29 |
|
|
@@ -219,16 +222,8 @@ def create_access_token(data: dict, expires_delta: timedelta = None):
|
|
| 219 |
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
|
| 220 |
return encoded_jwt
|
| 221 |
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
if not auth_header:
|
| 225 |
-
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authenticated")
|
| 226 |
-
|
| 227 |
-
parts = auth_header.split()
|
| 228 |
-
if len(parts) != 2 or parts[0].lower() != "bearer":
|
| 229 |
-
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid authorization header format")
|
| 230 |
-
|
| 231 |
-
token = parts[1]
|
| 232 |
try:
|
| 233 |
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
| 234 |
username: str = payload.get("sub")
|
|
@@ -313,9 +308,16 @@ def update_existing_user(user_id: int, user_update: UserUpdate, current_user: di
|
|
| 313 |
new_username = user_update.username if user_update.username else None
|
| 314 |
new_email = user_update.email if user_update.email else None
|
| 315 |
new_password_hash = hash_password(user_update.password) if user_update.password else None
|
| 316 |
-
database.update_user(
|
| 317 |
-
|
| 318 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 319 |
updated_user = database.get_user_by_id(user_id)
|
| 320 |
return updated_user
|
| 321 |
|
|
@@ -336,7 +338,7 @@ def login(form_data: OAuth2PasswordRequestForm = Depends()):
|
|
| 336 |
if not user:
|
| 337 |
raise HTTPException(status_code=400, detail="Incorrect username or password")
|
| 338 |
access_token = create_access_token(data={"sub": user["username"]})
|
| 339 |
-
#
|
| 340 |
return {"access_token": access_token, "token_type": "bearer"}
|
| 341 |
|
| 342 |
@auth_router.get("/me", response_model=UserOut)
|
|
|
|
| 1 |
+
from fastapi import FastAPI, HTTPException, Depends, status, APIRouter
|
| 2 |
+
from fastapi.security import OAuth2PasswordRequestForm, OAuth2PasswordBearer
|
| 3 |
from fastapi.middleware.cors import CORSMiddleware
|
| 4 |
from datetime import datetime, timedelta, timezone
|
| 5 |
from passlib.context import CryptContext
|
|
|
|
| 24 |
# allow_headers=["*"],
|
| 25 |
# )
|
| 26 |
|
| 27 |
+
# Define the OAuth2 scheme for OpenAPI docs.
|
| 28 |
+
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/v1/auth/login")
|
| 29 |
+
|
| 30 |
# Password hashing utilities
|
| 31 |
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
| 32 |
|
|
|
|
| 222 |
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
|
| 223 |
return encoded_jwt
|
| 224 |
|
| 225 |
+
# Updated get_current_user now uses OAuth2PasswordBearer for token extraction.
|
| 226 |
+
async def get_current_user(token: str = Depends(oauth2_scheme)):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 227 |
try:
|
| 228 |
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
| 229 |
username: str = payload.get("sub")
|
|
|
|
| 308 |
new_username = user_update.username if user_update.username else None
|
| 309 |
new_email = user_update.email if user_update.email else None
|
| 310 |
new_password_hash = hash_password(user_update.password) if user_update.password else None
|
| 311 |
+
database.update_user(
|
| 312 |
+
user_id,
|
| 313 |
+
username=new_username,
|
| 314 |
+
email=new_email,
|
| 315 |
+
password_hash=new_password_hash,
|
| 316 |
+
first_name=user_update.first_name,
|
| 317 |
+
last_name=user_update.last_name,
|
| 318 |
+
bio=user_update.bio,
|
| 319 |
+
profile_picture=user_update.profile_picture
|
| 320 |
+
)
|
| 321 |
updated_user = database.get_user_by_id(user_id)
|
| 322 |
return updated_user
|
| 323 |
|
|
|
|
| 338 |
if not user:
|
| 339 |
raise HTTPException(status_code=400, detail="Incorrect username or password")
|
| 340 |
access_token = create_access_token(data={"sub": user["username"]})
|
| 341 |
+
# Return the token so clients can include it in the "Authorization" header.
|
| 342 |
return {"access_token": access_token, "token_type": "bearer"}
|
| 343 |
|
| 344 |
@auth_router.get("/me", response_model=UserOut)
|