File size: 1,209 Bytes
80cb726
 
 
 
 
 
1c61a98
 
80cb726
 
1c61a98
 
 
 
 
 
 
80cb726
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
from datetime import date, datetime, timedelta, timezone
from typing import Any, Generic, Optional, TypeVar

from dotenv import load_dotenv
from jose import jwt
from pydantic import BaseModel

load_dotenv()

T = TypeVar("T")

class CommonResponse(BaseModel, Generic[T]):
    success: bool=True
    data: Optional[T] = None
    msg: str = ""


def _json_default(value: Any):
    if isinstance(value, (datetime, date)):
        return value.isoformat()
    raise TypeError(f"{type(value).__name__} is not JSON serializable")


def _json_safe_dict(data: dict) -> dict:
    return {
        key: _json_default(value) if isinstance(value, (datetime, date)) else value
        for key, value in data.items()
    }

#                                                   = 60분 * 24시간 * 7일
def create_jwt_token(data: dict, expires_minutes: int = 60 * 24 * 365) -> str:
    secret_key = os.getenv("JWT_SECRET_KEY", "change-this-jwt-secret-key")
    algorithm = "HS256"
    now = datetime.now(timezone.utc)

    payload = {
        **_json_safe_dict(data),
        "iat": now,
        "exp": now + timedelta(minutes=expires_minutes),
    }
    return jwt.encode(payload, secret_key, algorithm=algorithm)