Spaces:
Runtime error
Runtime error
File size: 1,355 Bytes
cc15101 807c135 cc15101 807c135 cc15101 807c135 cc15101 807c135 cc15101 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | import os
from datetime import datetime, timedelta
import bcrypt
from jose import JWTError, jwt
# Accept SECRET_KEY (what DEPLOY.md documents) or the older ABYSS_JWT_SECRET,
# with a dev fallback so local runs still work.
SECRET_KEY = (
os.environ.get("SECRET_KEY")
or os.environ.get("ABYSS_JWT_SECRET")
or "change-me-in-production"
)
ALGORITHM = "HS256"
TOKEN_EXPIRE_DAYS = 30
def hash_password(password: str) -> str:
# Call bcrypt directly — passlib 1.7.x raises against modern bcrypt releases.
# bcrypt only uses the first 72 bytes, so truncate to avoid a hard error.
pw = password.encode("utf-8")[:72]
return bcrypt.hashpw(pw, bcrypt.gensalt()).decode("utf-8")
def verify_password(plain: str, hashed: str) -> bool:
try:
return bcrypt.checkpw(plain.encode("utf-8")[:72], hashed.encode("utf-8"))
except (ValueError, TypeError):
return False
def create_access_token(user_id: str) -> str:
expire = datetime.utcnow() + timedelta(days=TOKEN_EXPIRE_DAYS)
return jwt.encode({"sub": user_id, "exp": expire}, SECRET_KEY, algorithm=ALGORITHM)
def decode_access_token(token: str) -> str | None:
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
return payload.get("sub")
except JWTError:
return None |