Ejemplo n.º 1
0
def parse_authorization_header(header):
    """
    Parses the HTTP Auth Header to a JWT Token
    Args:
        header: Authorization header of the HTTP Request
    Examples:
        request.headers['Authorization'] or something same
    Returns:
        Valid JWT token
    """
    if not header:
        return None
    value = wsgi_to_bytes(header)
    try:
        auth_type, auth_info = value.split(None, 1)
        auth_type = auth_type.lower()
    except ValueError:
        # Fallback for old versions
        auth_type = b"bearer"
        auth_info = value

    if auth_type == b"basic":
        try:
            username, password = base64.b64decode(auth_info).split(b":", 1)

            with current_app.app_context():
                username = to_unicode(username, "utf-8")
                password = to_unicode(password, "utf-8")

                user_manager: UserManager = UserManager(
                    current_app.database_manager)
                auth_module = AuthModule(
                    SystemSettingsReader(current_app.database_manager))

                try:
                    user_instance = auth_module.login(user_manager, username,
                                                      password)
                except Exception as e:
                    return None
                if user_instance:
                    tg = TokenGenerator(current_app.database_manager)
                    return tg.generate_token(payload={
                        'user': {
                            'public_id': user_instance.get_public_id()
                        }
                    })
                else:
                    return None
        except Exception:
            return None

    if auth_type == b"bearer":
        try:
            tv = TokenValidator()
            decoded_token = tv.decode_token(auth_info)
            tv.validate_token(decoded_token)
            return auth_info
        except Exception:
            return None
    return None
Ejemplo n.º 2
0
 def test_token_generation(self):
     from cmdb.security.token.generator import TokenGenerator
     from cmdb.security.token.validator import TokenValidator
     token_gen = TokenGenerator()
     token_validator = TokenValidator()
     token = token_gen.generate_token(payload={'test': 'test'})
     print(token_validator.decode_token(token))