80 lines
2.7 KiB
Python
80 lines
2.7 KiB
Python
from fastapi import APIRouter, Depends, HTTPException, status
|
|
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
|
|
from sqlalchemy.orm import Session
|
|
from datetime import datetime, timedelta
|
|
from jose import JWTError, jwt
|
|
from passlib.context import CryptContext
|
|
from .. import schemas, models, database
|
|
from ..config import settings
|
|
|
|
router = APIRouter(tags=["auth"])
|
|
|
|
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
|
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
|
|
|
|
|
|
def verify_password(plain_password: str, hashed_password: str):
|
|
return pwd_context.verify(plain_password, hashed_password)
|
|
|
|
|
|
def get_password_hash(password: str):
|
|
return pwd_context.hash(password)
|
|
|
|
|
|
def create_access_token(data: dict, expires_delta: timedelta | None = None):
|
|
to_encode = data.copy()
|
|
if expires_delta:
|
|
expire = datetime.utcnow() + expires_delta
|
|
else:
|
|
expire = datetime.utcnow() + timedelta(minutes=15)
|
|
to_encode.update({"exp": expire})
|
|
encoded_jwt = jwt.encode(
|
|
to_encode, settings.secret_key, algorithm=settings.algorithm
|
|
)
|
|
return encoded_jwt
|
|
|
|
|
|
async def get_current_user(
|
|
token: str = Depends(oauth2_scheme), db: Session = Depends(database.get_db)
|
|
):
|
|
credentials_exception = HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Could not validate credentials",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
try:
|
|
payload = jwt.decode(
|
|
token, settings.secret_key, algorithms=[settings.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 = db.query(models.User).filter(models.User.email == token_data.email).first()
|
|
if user is None:
|
|
raise credentials_exception
|
|
return user
|
|
|
|
|
|
@router.post("/token", response_model=schemas.Token)
|
|
async def login_for_access_token(
|
|
form_data: OAuth2PasswordRequestForm = Depends(),
|
|
db: Session = Depends(database.get_db),
|
|
):
|
|
user = db.query(models.User).filter(models.User.email == form_data.username).first()
|
|
if not user or not verify_password(form_data.password, user.hashed_password):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Incorrect username or password",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
|
|
access_token_expires = timedelta(minutes=settings.access_token_expire_minutes)
|
|
access_token = create_access_token(
|
|
data={"sub": user.email}, expires_delta=access_token_expires
|
|
)
|
|
return {"access_token": access_token, "token_type": "bearer"}
|