Exemplo 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
Exemplo 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))
Exemplo n.º 3
0
    def __init__(self, *args, **kwargs):
        self.database_manager = kwargs.pop('database_manager')
        self._token_generator = TokenGenerator(self.database_manager)

        token = None
        if kwargs.get('default_auth_user', None):
            default_auth_user = kwargs.pop('default_auth_user')
            token = self._token_generator.generate_token(payload={
                'user': {
                    'public_id': default_auth_user.public_id
                }
            }).decode('UTF-8')
        super(RestAPITestClient, self).__init__(*args, **kwargs)
        if token:
            self.environ_base['HTTP_AUTHORIZATION'] = f'Bearer {token}'
        self.content_type = 'application/json'
Exemplo n.º 4
0
def post_login():
    user_manager: UserManager = UserManager(current_app.database_manager)
    group_manager: GroupManager = GroupManager(
        current_app.database_manager, right_manager=RightManager(rights))
    security_manager: SecurityManager = SecurityManager(
        current_app.database_manager)
    login_data = request.json
    if not request.json:
        return abort(400, 'No valid JSON data was provided')

    request_user_name = login_data['user_name']
    request_password = login_data['password']

    auth_module = AuthModule(
        system_settings_reader.get_all_values_from_section(
            'auth', default=AuthModule.__DEFAULT_SETTINGS__),
        user_manager=user_manager,
        group_manager=group_manager,
        security_manager=security_manager)
    user_instance = None
    try:
        user_instance = auth_module.login(request_user_name, request_password)
    except (AuthenticationProviderNotExistsError,
            AuthenticationProviderNotActivated) as err:
        return abort(503, err.message)
    except Exception as e:
        return abort(401)
    finally:
        # If login success generate user instance with token
        if user_instance:
            tg = TokenGenerator()
            token: bytes = tg.generate_token(
                payload={'user': {
                    'public_id': user_instance.get_public_id()
                }})
            token_issued_at = int(datetime.now().timestamp())
            token_expire = int(tg.get_expire_time().timestamp())

            login_response = LoginResponse(user_instance, token,
                                           token_issued_at, token_expire)

            return login_response.make_response()

        # Login not success
        else:
            return abort(401, 'Could not login')
Exemplo n.º 5
0
def post_login():
    login_data = request.json
    if not request.json:
        return abort(400, 'No valid JSON data was provided')

    request_user_name = login_data['user_name']
    request_password = login_data['password']

    auth_module = AuthModule(system_settings_reader)
    user_instance = None
    try:
        user_instance = auth_module.login(user_manager, request_user_name,
                                          request_password)
    except (AuthenticationProviderNotExistsError,
            AuthenticationProviderNotActivated) as err:
        return abort(503, err.message)
    except Exception as e:
        return abort(401)
    finally:
        # If login success generate user instance with token
        if user_instance:
            tg = TokenGenerator()
            token: bytes = tg.generate_token(
                payload={'user': {
                    'public_id': user_instance.get_public_id()
                }})
            token_issued_at = int(datetime.now().timestamp())
            token_expire = int(tg.get_expire_time().timestamp())

            login_response = LoginResponse(user_instance, token,
                                           token_issued_at, token_expire)

            return login_response.make_response()

        # Login not success
        else:
            return abort(401, 'Could not login')
Exemplo n.º 6
0
class RestAPITestClient(FlaskClient):
    def __init__(self, *args, **kwargs):
        self.database_manager = kwargs.pop('database_manager')
        self._token_generator = TokenGenerator(self.database_manager)

        token = None
        if kwargs.get('default_auth_user', None):
            default_auth_user = kwargs.pop('default_auth_user')
            token = self._token_generator.generate_token(payload={
                'user': {
                    'public_id': default_auth_user.public_id
                }
            }).decode('UTF-8')
        super(RestAPITestClient, self).__init__(*args, **kwargs)
        if token:
            self.environ_base['HTTP_AUTHORIZATION'] = f'Bearer {token}'
        self.content_type = 'application/json'

    def inject_auth(self, kwargs: dict) -> dict:
        if kwargs.get('unauthorized', None):
            kwargs['environ_overrides'] = {'HTTP_AUTHORIZATION': ''}
            kwargs.pop('unauthorized')
        elif kwargs.get('user', None):
            token = self._token_generator.generate_token(payload={
                'user': {
                    'public_id': kwargs.pop('user').public_id
                }
            }).decode('UTF-8')
            kwargs['environ_overrides'] = {
                'HTTP_AUTHORIZATION': f'Bearer {token}'
            }
        return kwargs

    def get(self, *args, **kw):
        kw['method'] = 'GET'
        if not kw.get('content_type', None):
            kw['content_type'] = 'application/json'
        kw = self.inject_auth(kw)
        return super(RestAPITestClient, self).open(*args, **kw)

    def patch(self, *args, **kw):
        kw['method'] = 'PATCH'
        if not kw.get('content_type', None):
            kw['content_type'] = 'application/json'
        kw = self.inject_auth(kw)
        return super(RestAPITestClient, self).open(*args, **kw)

    def post(self, *args, **kw):
        kw['method'] = 'POST'
        if not kw.get('content_type', None):
            kw['content_type'] = 'application/json'
        kw = self.inject_auth(kw)
        return super(RestAPITestClient, self).open(*args, **kw)

    def head(self, *args, **kw):
        kw['method'] = 'HEAD'
        if not kw.get('content_type', None):
            kw['content_type'] = 'application/json'
        kw = self.inject_auth(kw)
        return super(RestAPITestClient, self).open(*args, **kw)

    def put(self, *args, **kw):
        kw['method'] = 'PUT'
        if not kw.get('content_type', None):
            kw['content_type'] = 'application/json'
        kw = self.inject_auth(kw)
        return super(RestAPITestClient, self).open(*args, **kw)

    def delete(self, *args, **kw):
        kw['method'] = 'DELETE'
        if not kw.get('content_type', None):
            kw['content_type'] = 'application/json'
        kw = self.inject_auth(kw)
        return super(RestAPITestClient, self).open(*args, **kw)

    def options(self, *args, **kw):
        kw['method'] = 'OPTIONS'
        if not kw.get('content_type', None):
            kw['content_type'] = 'application/json'
        kw = self.inject_auth(kw)
        return super(RestAPITestClient, self).open(*args, **kw)