Spaces:
Sleeping
Sleeping
Download backend/auth/utils.py from ashutoshneemval/CLAT_Guide: direct link, hf CLI and curl.
- Browser
- Download file 1.93 kB
-
https://huggingface.co/spaces/ashutoshneemval/CLAT_Guide/resolve/main/backend/auth/utils.py
- Command line
-
hf download hf://spaces/ashutoshneemval/CLAT_Guide/backend/auth/utils.py
-
curl -L -o utils.py https://huggingface.co/spaces/ashutoshneemval/CLAT_Guide/resolve/main/backend/auth/utils.py
1.93 kB
| from datetime import datetime, timedelta, timezone | |
| from typing import Optional, Union, Any | |
| from jose import jwt, JWTError | |
| from passlib.context import CryptContext | |
| from fastapi import Depends, HTTPException, status | |
| from fastapi.security import OAuth2PasswordBearer | |
| from sqlalchemy.orm import Session | |
| from database.connection import get_db | |
| from database.models import User | |
| from config import settings | |
| pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") | |
| oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/token") | |
| def verify_password(plain_password: str, hashed_password: str) -> bool: | |
| return pwd_context.verify(plain_password, hashed_password) | |
| def get_password_hash(password: str) -> str: | |
| return pwd_context.hash(password) | |
| def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str: | |
| to_encode = data.copy() | |
| if expires_delta: | |
| expire = datetime.now(timezone.utc) + expires_delta | |
| else: | |
| expire = datetime.now(timezone.utc) + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES) | |
| to_encode.update({"exp": expire}) | |
| encoded_jwt = jwt.encode(to_encode, settings.JWT_SECRET_KEY, algorithm=settings.JWT_ALGORITHM) | |
| return encoded_jwt | |
| async def get_current_user(token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)) -> User: | |
| credentials_exception = HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Could not validate credentials", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |
| try: | |
| payload = jwt.decode(token, settings.JWT_SECRET_KEY, algorithms=[settings.JWT_ALGORITHM]) | |
| email: str = payload.get("sub") | |
| if email is None: | |
| raise credentials_exception | |
| except JWTError: | |
| raise credentials_exception | |
| user = db.query(User).filter(User.email == email).first() | |
| if user is None: | |
| raise credentials_exception | |
| return user | |