Spaces:
Build error
Build error
Hkoradiya123
feat: Initialize frontend with Zustand for state management, Tailwind CSS for styling, and TypeScript for type safety
4854e2b Download backend/app/core/security.py from jinksQspider/fmproService: direct link, hf CLI and curl.
- Browser
- Download file 3.46 kB
-
https://huggingface.co/spaces/jinksQspider/fmproService/resolve/main/backend/app/core/security.py
- Command line
-
hf download hf://spaces/jinksQspider/fmproService/backend/app/core/security.py
-
curl -L -o security.py https://huggingface.co/spaces/jinksQspider/fmproService/resolve/main/backend/app/core/security.py
3.46 kB
| """Security utilities - JWT, hashing, tenant isolation""" | |
| from datetime import datetime, timedelta, timezone | |
| from typing import Optional, Dict, Any | |
| import jwt | |
| from passlib.context import CryptContext | |
| from fastapi import HTTPException, status, Depends | |
| from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials | |
| import logging | |
| from app.core.config import settings | |
| logger = logging.getLogger(__name__) | |
| # Password hashing | |
| pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") | |
| # Bearer token | |
| security = HTTPBearer() | |
| def hash_password(password: str) -> str: | |
| """Hash password using bcrypt""" | |
| return pwd_context.hash(password) | |
| def verify_password(plain_password: str, hashed_password: str) -> bool: | |
| """Verify password against hash""" | |
| return pwd_context.verify(plain_password, hashed_password) | |
| def create_access_token( | |
| data: Dict[str, Any], | |
| expires_delta: Optional[timedelta] = None | |
| ) -> str: | |
| """Create JWT access token""" | |
| 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.SECRET_KEY, | |
| algorithm=settings.ALGORITHM | |
| ) | |
| return encoded_jwt | |
| def create_refresh_token(user_id: str, tenant_id: str) -> str: | |
| """Create JWT refresh token (longer expiry)""" | |
| expire = datetime.now(timezone.utc) + timedelta( | |
| days=settings.REFRESH_TOKEN_EXPIRE_DAYS | |
| ) | |
| data = { | |
| "sub": user_id, | |
| "tenant_id": tenant_id, | |
| "exp": expire, | |
| "type": "refresh" | |
| } | |
| return jwt.encode( | |
| data, | |
| settings.SECRET_KEY, | |
| algorithm=settings.ALGORITHM | |
| ) | |
| def decode_token(token: str) -> Dict[str, Any]: | |
| """Decode and validate JWT token""" | |
| try: | |
| payload = jwt.decode( | |
| token, | |
| settings.SECRET_KEY, | |
| algorithms=[settings.ALGORITHM] | |
| ) | |
| return payload | |
| except jwt.ExpiredSignatureError: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Token has expired" | |
| ) | |
| except jwt.InvalidTokenError: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Invalid token" | |
| ) | |
| async def get_current_user_token( | |
| credentials: HTTPAuthorizationCredentials = Depends(security) | |
| ) -> Dict[str, Any]: | |
| """Extract and validate token from Authorization header""" | |
| token = credentials.credentials | |
| return decode_token(token) | |
| async def get_current_tenant_id( | |
| token: Dict[str, Any] = Depends(get_current_user_token) | |
| ) -> str: | |
| """Extract tenant_id from token - used for multi-tenant isolation""" | |
| tenant_id = token.get("tenant_id") | |
| if not tenant_id: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Tenant ID not found in token" | |
| ) | |
| return tenant_id | |
| async def get_current_user_id( | |
| token: Dict[str, Any] = Depends(get_current_user_token) | |
| ) -> str: | |
| """Extract user_id from token""" | |
| user_id = token.get("sub") | |
| if not user_id: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="User ID not found in token" | |
| ) | |
| return user_id | |