Spaces:
Runtime error
Runtime error
| from fastapi import HTTPException, status | |
| from fastapi.security import HTTPBearer | |
| from datetime import datetime, timedelta | |
| from jose import JWTError, jwt | |
| import bcrypt | |
| security = HTTPBearer() | |
| # Secret key for JWT token | |
| SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7" | |
| ALGORITHM = "HS256" | |
| ACCESS_TOKEN_EXPIRE_MINUTES = 180 | |
| # Function to generate JWT token | |
| def create_access_token(data: dict): | |
| to_encode = data.copy() | |
| expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) | |
| to_encode.update({"exp": expire}) | |
| encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) | |
| return encoded_jwt | |
| # Function to hash a password | |
| def hash_password(password: str) -> str: | |
| hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()) | |
| return hashed_password | |
| # Function to verify a password | |
| def verify_password(plain_password: str, hashed_password: bytes) -> bool: | |
| return bcrypt.checkpw(plain_password.encode('utf-8'), hashed_password) | |
| def verify_token(token: str): | |
| try: | |
| payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) | |
| return payload | |
| except JWTError: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Invalid or expired token" | |
| ) |