84 lines
2.2 KiB
Python
84 lines
2.2 KiB
Python
"""Utility helpers module"""
|
|
import shortuuid
|
|
import hashlib
|
|
from datetime import datetime, timedelta
|
|
from typing import Dict, Any, Optional
|
|
|
|
from luxx.config import config
|
|
|
|
|
|
def generate_id(prefix: str = "") -> str:
|
|
"""Generate unique ID"""
|
|
unique_id = shortuuid.uuid()
|
|
if prefix:
|
|
return f"{prefix}_{unique_id}"
|
|
return unique_id
|
|
|
|
|
|
def hash_password(password: str) -> str:
|
|
"""Hash password"""
|
|
import bcrypt
|
|
return bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode()
|
|
|
|
|
|
def verify_password(password: str, hashed: str) -> bool:
|
|
"""Verify password"""
|
|
import bcrypt
|
|
return bcrypt.checkpw(password.encode(), hashed.encode())
|
|
|
|
|
|
def create_access_token(data: Dict[str, Any], expires_delta: Optional[timedelta] = None) -> str:
|
|
"""Create JWT access token"""
|
|
from jose import jwt
|
|
to_encode = data.copy()
|
|
if expires_delta:
|
|
expire = datetime.utcnow() + expires_delta
|
|
else:
|
|
expire = datetime.utcnow() + timedelta(hours=24)
|
|
to_encode.update({"exp": expire})
|
|
encoded_jwt = jwt.encode(to_encode, config.secret_key, algorithm="HS256")
|
|
return encoded_jwt
|
|
|
|
|
|
def decode_access_token(token: str) -> Optional[Dict[str, Any]]:
|
|
"""Decode JWT token"""
|
|
try:
|
|
from jose import jwt
|
|
payload = jwt.decode(token, config.secret_key, algorithms=["HS256"])
|
|
return payload
|
|
except Exception:
|
|
return None
|
|
|
|
|
|
def success_response(data: Any = None, message: str = "Success") -> Dict[str, Any]:
|
|
"""Success response wrapper"""
|
|
return {
|
|
"success": True,
|
|
"message": message,
|
|
"data": data
|
|
}
|
|
|
|
|
|
def error_response(message: str, code: int = 400, errors: Any = None) -> Dict[str, Any]:
|
|
"""Error response wrapper"""
|
|
response = {
|
|
"success": False,
|
|
"message": message,
|
|
"code": code
|
|
}
|
|
if errors:
|
|
response["errors"] = errors
|
|
return response
|
|
|
|
|
|
def paginate(query, page: int = 1, page_size: int = 20):
|
|
"""Pagination helper"""
|
|
total = query.count()
|
|
items = query.offset((page - 1) * page_size).limit(page_size).all()
|
|
return {
|
|
"total": total,
|
|
"page": page,
|
|
"page_size": page_size,
|
|
"items": items
|
|
}
|