예제 #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
예제 #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))
예제 #3
0
            def _decorate(*args, **kwargs):

                if auth:
                    if not auth_is_valid():
                        return abort(401)

                if auth and right:
                    if not user_has_right(right):
                        if excepted:
                            with current_app.app_context():
                                user_manager = UserManager(
                                    current_app.database_manager)

                            token = parse_authorization_header(
                                request.headers['Authorization'])
                            try:
                                decrypted_token = TokenValidator(
                                    current_app.database_manager).decode_token(
                                        token)
                            except ValidationError as err:
                                return abort(401)
                            try:
                                user_id = decrypted_token['DATAGERRY'][
                                    'value']['user']['public_id']
                                user_dict: dict = UserModel.to_dict(
                                    user_manager.get(user_id))

                                if excepted:
                                    for exe_key, exe_value in excepted.items():
                                        try:
                                            route_parameter = kwargs[exe_value]
                                        except KeyError:
                                            return abort(
                                                403,
                                                f'User has not the required right {right}'
                                            )

                                        if exe_key not in user_dict.keys():
                                            return abort(
                                                403,
                                                f'User has not the required right {right}'
                                            )

                                        if user_dict[
                                                exe_key] == route_parameter:
                                            return f(*args, **kwargs)
                            except ManagerGetError:
                                return abort(404)
                        return abort(
                            403, f'User has not the required right {right}')

                return f(*args, **kwargs)
예제 #4
0
def user_has_right(required_right: str) -> bool:
    from flask import request, current_app
    with current_app.app_context():
        user_manager = current_app.user_manager

    token = parse_authorization_header(request.headers['Authorization'])
    try:
        decrypted_token = TokenValidator().decode_token(token)
    except ValidationError as err:
        return abort(401)
    try:
        user_id = decrypted_token['DATAGERRY']['value']['user']['public_id']
        user = user_manager.get_user(user_id)
        return user_manager.group_has_right(user.get_group(), required_right)
    except UserManagerGetError:
        return False
예제 #5
0
    def get_request_user(*args, **kwargs):
        from flask import request, current_app
        with current_app.app_context():
            user_manager = current_app.user_manager

        token = parse_authorization_header(request.headers['Authorization'])
        try:
            decrypted_token = TokenValidator().decode_token(token)
        except ValidationError as err:
            return abort(401)
        try:
            user_id = decrypted_token['DATAGERRY']['value']['user']['public_id']
        except ValueError:
            return abort(401)
        user = user_manager.get_user(user_id)
        kwargs.update({'request_user': user})
        return func(*args, **kwargs)
예제 #6
0
def user_has_right(required_right: str) -> bool:
    """Check if a user has a specific right"""
    from flask import request, current_app
    with current_app.app_context():
        user_manager = UserManager(current_app.database_manager)
        group_manager = GroupManager(current_app.database_manager, RightManager(rights))

    token = parse_authorization_header(request.headers['Authorization'])
    try:
        decrypted_token = TokenValidator(database_manager=current_app.database_manager).decode_token(token)
    except ValidationError as err:
        return abort(401)
    try:
        user_id = decrypted_token['DATAGERRY']['value']['user']['public_id']
        user = user_manager.get(user_id)
        group = group_manager.get(user.group_id)
        right_status = group.has_right(right_name=required_right)
        if not right_status:
            right_status = group.has_extended_right(right_name=required_right)
        return right_status
    except ManagerGetError:
        return False