%PDF- %PDF-
Mini Shell

Mini Shell

Direktori : /proc/3/root/opt/imunify360/venv/lib64/python3.8/site-packages/defence360agent/api/
Upload File :
Create Path :
Current File : //proc/3/root/opt/imunify360/venv/lib64/python3.8/site-packages/defence360agent/api/jwt_issuer.py

"""
This program is free software: you can redistribute it and/or modify it under 
the terms of the GNU General Public License as published by 
the Free Software Foundation, either version 3 of the License, 
or (at your option) any later version.


This program is distributed in the hope that it will be useful, 
but WITHOUT ANY WARRANTY; without even the implied warranty of 
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
See the GNU General Public License for more details.


You should have received a copy of the GNU General Public License
 along with this program.  If not, see <https://www.gnu.org/licenses/>.

Copyright © 2019 Cloud Linux Software Inc.

This software is also available under ImunifyAV commercial license,
see <https://www.imunify360.com/legal/eula>
"""
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"]],
        }

Zerion Mini Shell 1.0