Spaces:
Sleeping
Sleeping
File size: 1,200 Bytes
4aae53a |
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 43 44 |
import jwt
import bcrypt
from datetime import datetime, timedelta
import os
import dotenv
dotenv.load_dotenv()
AUTH_SECRET = os.getenv("AUTH_KEY")
AUTH_TTL = int(os.getenv("AUTH_TTL"))
def create_session(data: dict) -> str:
"""
Create a JWT token with expiration.
"""
expires_at = datetime.now() + timedelta(minutes=AUTH_TTL)
token = jwt.encode({"exp": expires_at, **data}, AUTH_SECRET, algorithm="HS256")
return token
def check_session(token: str) -> dict:
"""
Verify the JWT token and return the decoded data.
"""
try:
decoded = jwt.decode(token, AUTH_SECRET, algorithms=["HS256"])
return decoded
except jwt.ExpiredSignatureError:
raise ValueError("Token has expired")
except jwt.InvalidTokenError:
raise ValueError("Invalid token")
def hide_pass(password: str) -> str:
"""
Hash the password using bcrypt.
"""
hashed = bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt())
return hashed.decode("utf-8")
def check_pass(password: str, hashed: str) -> bool:
"""
Compare the password with its hash.
"""
return bcrypt.checkpw(password.encode("utf-8"), hashed.encode("utf-8"))
|