Spaces:
Paused
Paused
Download app/core/security.py from Jetsada117/backend_project: direct link, hf CLI and curl.
- Browser
- Download file 2.01 kB
-
https://huggingface.co/spaces/Jetsada117/backend_project/resolve/main/app/core/security.py
- Command line
-
hf download hf://spaces/Jetsada117/backend_project/app/core/security.py
-
curl -L -o security.py https://huggingface.co/spaces/Jetsada117/backend_project/resolve/main/app/core/security.py
2.01 kB
| from datetime import datetime, timedelta, 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: | |
| """ | |
| สร้าง JWT Access Token พร้อมกำหนดเวลาหมดอายุ | |
| """ | |
| 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: | |
| """ | |
| สร้าง JWT Refresh Token พร้อมกำหนดเวลาหมดอายุ | |
| """ | |
| 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: | |
| """ | |
| ตรวจสอบความถูกต้องของ Password เทียบกับ Hashed Password | |
| """ | |
| return bcrypt.checkpw( | |
| plain_password.encode("utf-8"), hashed_password.encode("utf-8") | |
| ) | |
| def get_password_hash(password: str) -> str: | |
| """ | |
| แปลง Password เป็น Bcrypt Hash | |
| """ | |
| return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8") | |