Spaces:
Sleeping
Sleeping
Download build/lib/core/security.py from hashir-qt/tasklert-api: direct link, hf CLI and curl.
- Browser
- Download file 2.06 kB
-
https://huggingface.co/spaces/hashir-qt/tasklert-api/resolve/main/build/lib/core/security.py
- Command line
-
hf download hf://spaces/hashir-qt/tasklert-api/build/lib/core/security.py
-
curl -L -o security.py https://huggingface.co/spaces/hashir-qt/tasklert-api/resolve/main/build/lib/core/security.py
2.06 kB
| from datetime import datetime, timedelta, timezone | |
| from typing import Annotated | |
| import bcrypt | |
| import jwt | |
| from fastapi import Depends, HTTPException, status | |
| from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer | |
| from sqlalchemy.ext.asyncio import AsyncSession | |
| from sqlmodel import select | |
| from .config import settings | |
| from .database import get_session | |
| bearer_scheme = HTTPBearer() | |
| def hash_password(password: str) -> str: | |
| return bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode() | |
| def verify_password(plain: str, hashed: str) -> bool: | |
| return bcrypt.checkpw(plain.encode(), hashed.encode()) | |
| def create_access_token(user_id: int) -> str: | |
| payload = { | |
| "sub": str(user_id), | |
| "exp": datetime.now(timezone.utc) | |
| + timedelta(minutes=settings.access_token_expire_minutes), | |
| } | |
| return jwt.encode(payload, settings.secret_key, algorithm=settings.algorithm) | |
| def decode_token(token: str) -> dict: | |
| try: | |
| return jwt.decode(token, settings.secret_key, algorithms=[settings.algorithm]) | |
| except jwt.ExpiredSignatureError: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, detail="Token expired" | |
| ) | |
| except jwt.InvalidTokenError: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token" | |
| ) | |
| async def get_current_user( | |
| credentials: Annotated[HTTPAuthorizationCredentials, Depends(bearer_scheme)], | |
| session: Annotated[AsyncSession, Depends(get_session)], | |
| ): | |
| from ..models.user import User | |
| payload = decode_token(credentials.credentials) | |
| user_id = payload.get("sub") | |
| if not user_id: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token" | |
| ) | |
| result = await session.execute(select(User).where(User.id == int(user_id))) | |
| user = result.scalar_one_or_none() | |
| if not user: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found" | |
| ) | |
| return user | |