Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
| from datetime import datetime, timedelta, timezone # ใช้ timezone เพื่อความแม่นยำ | |
| from typing import Any, Union | |
| from jose import jwt | |
| import bcrypt | |
| from app.core.config import settings | |
| def create_access_token( | |
| subject: Union[str, Any], | |
| role: str, | |
| expires_delta: timedelta = None, | |
| ) -> str: | |
| 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 = { | |
| "exp": expire, | |
| "sub": str(subject), | |
| "role": str(role), | |
| "type": "access", | |
| } | |
| encoded_jwt = jwt.encode( | |
| to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM | |
| ) | |
| return encoded_jwt | |
| def create_refresh_token( | |
| subject: Union[str, Any], expires_delta: timedelta = None | |
| ) -> str: | |
| if expires_delta: | |
| expire = datetime.now(timezone.utc) + expires_delta | |
| else: | |
| expire = datetime.now(timezone.utc) + timedelta( | |
| days=settings.REFRESH_TOKEN_EXPIRE_DAYS | |
| ) | |
| to_encode = {"exp": expire, "sub": str(subject), "type": "refresh"} | |
| encoded_jwt = jwt.encode( | |
| to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM | |
| ) | |
| return encoded_jwt | |
| def verify_password(plain_password: str, hashed_password: str) -> bool: | |
| return bcrypt.checkpw( | |
| plain_password.encode("utf-8"), hashed_password.encode("utf-8") | |
| ) | |
| def get_password_hash(password: str) -> str: | |
| return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8") | |