Spaces:
Runtime error
Runtime error
Download security.py from cuiconnect/backend: direct link, hf CLI and curl.
- Browser
- Download file 5.44 kB
-
https://huggingface.co/spaces/cuiconnect/backend/resolve/main/security.py
- Command line
-
hf download hf://spaces/cuiconnect/backend/security.py
-
curl -L -o security.py https://huggingface.co/spaces/cuiconnect/backend/resolve/main/security.py
5.44 kB
| import os | |
| from datetime import datetime, timedelta, timezone | |
| from typing import Annotated | |
| from fastapi import Depends, HTTPException, status | |
| from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer | |
| from jose import JWTError, jwt | |
| SECRET_KEY = os.getenv("JWT_SECRET_KEY", "dev-secret-change-in-production") | |
| ALGORITHM = "HS256" | |
| ACCESS_TOKEN_EXPIRE_MINUTES = int(os.getenv("ACCESS_TOKEN_EXPIRE_MINUTES", "60")) | |
| REFRESH_TOKEN_EXPIRE_DAYS = int(os.getenv("REFRESH_TOKEN_EXPIRE_DAYS", "7")) | |
| TOKEN_TYPE_ACCESS = "access" | |
| TOKEN_TYPE_REFRESH = "refresh" | |
| TOKEN_TYPE_ADMIN_REFRESH = "admin_refresh" | |
| ROLE_ADMIN = "admin" | |
| security_scheme = HTTPBearer() | |
| def create_access_token(subject: str) -> str: | |
| expire = datetime.now(timezone.utc) + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) | |
| return jwt.encode( | |
| {"sub": subject, "exp": expire, "typ": TOKEN_TYPE_ACCESS}, | |
| SECRET_KEY, | |
| algorithm=ALGORITHM, | |
| ) | |
| def create_refresh_token(subject: str) -> str: | |
| expire = datetime.now(timezone.utc) + timedelta(days=REFRESH_TOKEN_EXPIRE_DAYS) | |
| return jwt.encode( | |
| {"sub": subject, "exp": expire, "typ": TOKEN_TYPE_REFRESH}, | |
| SECRET_KEY, | |
| algorithm=ALGORITHM, | |
| ) | |
| def create_admin_access_token(subject: str) -> str: | |
| expire = datetime.now(timezone.utc) + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) | |
| return jwt.encode( | |
| { | |
| "sub": subject, | |
| "exp": expire, | |
| "typ": TOKEN_TYPE_ACCESS, | |
| "role": ROLE_ADMIN, | |
| }, | |
| SECRET_KEY, | |
| algorithm=ALGORITHM, | |
| ) | |
| def create_admin_refresh_token(subject: str) -> str: | |
| expire = datetime.now(timezone.utc) + timedelta(days=REFRESH_TOKEN_EXPIRE_DAYS) | |
| return jwt.encode( | |
| {"sub": subject, "exp": expire, "typ": TOKEN_TYPE_ADMIN_REFRESH}, | |
| SECRET_KEY, | |
| algorithm=ALGORITHM, | |
| ) | |
| def decode_refresh_token(token: str) -> str: | |
| try: | |
| payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) | |
| except JWTError: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Invalid or expired refresh token", | |
| ) | |
| if payload.get("typ") != TOKEN_TYPE_REFRESH: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Invalid refresh token", | |
| ) | |
| sub = payload.get("sub") | |
| if not isinstance(sub, str) or not sub: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Invalid refresh token", | |
| ) | |
| return sub | |
| def decode_admin_refresh_token(token: str) -> str: | |
| try: | |
| payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) | |
| except JWTError: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Invalid or expired refresh token", | |
| ) | |
| if payload.get("typ") != TOKEN_TYPE_ADMIN_REFRESH: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Invalid refresh token", | |
| ) | |
| sub = payload.get("sub") | |
| if not isinstance(sub, str) or not sub: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Invalid refresh token", | |
| ) | |
| return sub | |
| def get_current_user_id( | |
| credentials: Annotated[HTTPAuthorizationCredentials, Depends(security_scheme)], | |
| ) -> str: | |
| credentials_exception = HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Invalid or expired token", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |
| try: | |
| payload = jwt.decode( | |
| credentials.credentials, | |
| SECRET_KEY, | |
| algorithms=[ALGORITHM], | |
| ) | |
| if payload.get("typ") == TOKEN_TYPE_REFRESH: | |
| raise credentials_exception | |
| typ = payload.get("typ") | |
| if typ is not None and typ != TOKEN_TYPE_ACCESS: | |
| raise credentials_exception | |
| sub = payload.get("sub") | |
| if not isinstance(sub, str) or not sub: | |
| raise credentials_exception | |
| if payload.get("role") == ROLE_ADMIN: | |
| raise credentials_exception | |
| return sub | |
| except JWTError: | |
| raise credentials_exception | |
| def get_current_admin_id( | |
| credentials: Annotated[HTTPAuthorizationCredentials, Depends(security_scheme)], | |
| ) -> str: | |
| credentials_exception = HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Invalid or expired token", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |
| forbidden = HTTPException( | |
| status_code=status.HTTP_403_FORBIDDEN, | |
| detail="Admin access required", | |
| ) | |
| try: | |
| payload = jwt.decode( | |
| credentials.credentials, | |
| SECRET_KEY, | |
| algorithms=[ALGORITHM], | |
| ) | |
| if payload.get("typ") == TOKEN_TYPE_REFRESH: | |
| raise credentials_exception | |
| if payload.get("typ") == TOKEN_TYPE_ADMIN_REFRESH: | |
| raise credentials_exception | |
| typ = payload.get("typ") | |
| if typ is not None and typ != TOKEN_TYPE_ACCESS: | |
| raise credentials_exception | |
| if payload.get("role") != ROLE_ADMIN: | |
| raise forbidden | |
| sub = payload.get("sub") | |
| if not isinstance(sub, str) or not sub: | |
| raise credentials_exception | |
| return sub | |
| except JWTError: | |
| raise credentials_exception | |