37 lines
975 B
Python
37 lines
975 B
Python
from jose import jwt
|
|
|
|
from sqlalchemy.orm import Session
|
|
from fastapi import Depends, HTTPException, status
|
|
from fastapi.security import OAuth2PasswordBearer
|
|
|
|
from app import models, schemas, crud
|
|
from app.utils.encrypt import decode_token
|
|
from app.database import SessionLocal
|
|
|
|
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/auth/token")
|
|
|
|
|
|
def get_db():
|
|
try:
|
|
db = SessionLocal()
|
|
yield db
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
def get_current_user(
|
|
db: Session = Depends(get_db), token: str = Depends(oauth2_scheme)
|
|
) -> models.User:
|
|
try:
|
|
payload = decode_token(token)
|
|
print(payload)
|
|
except Exception as e:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail="Could not validate credentials",
|
|
)
|
|
user = crud.crud_user.get_user(db, username=payload.get("username"))
|
|
if not user:
|
|
raise HTTPException(status_code=404, detail="User not found")
|
|
return user
|