コード例 #1
0
    async def login_user(self, password, **kwds):
        """
            This function handles the registration of the given user credentials in the database
        """
        # find the matching user with the given email
        user_data = (await self._get_matching_user(fields=list(kwds.keys()),
                                                   **kwds))['data']
        try:
            # look for a matching entry in the local database
            passwordEntry = self.model.select().where(
                self.model.user == user_data[root_query()][0]['pk'])[0]
        # if we couldn't acess the id of the result
        except (KeyError, IndexError) as e:
            # yell loudly
            raise RuntimeError('Could not find matching registered user')

        # if the given password matches the stored hash
        if passwordEntry and passwordEntry.password == password:
            # the remote entry for the user
            user = user_data[root_query()][0]
            # then return a dictionary with the user and sessionToken
            return {
                'user': user,
                'sessionToken': self._user_session_token(user)
            }

        # otherwise the passwords don't match
        raise RuntimeError("Incorrect credentials")
コード例 #2
0
ファイル: apiGateway.py プロジェクト: nautilus/nautilus
    async def login_user(self, password, **kwds):
        """
            This function handles the registration of the given user credentials in the database
        """
        # find the matching user with the given email
        user_data = (await self._get_matching_user(fields=list(kwds.keys()), **kwds))['data']
        try:
            # look for a matching entry in the local database
            passwordEntry = self.model.select().where(
                self.model.user == user_data[root_query()][0]['pk']
            )[0]
        # if we couldn't acess the id of the result
        except (KeyError, IndexError) as e:
            # yell loudly
            raise RuntimeError('Could not find matching registered user')


        # if the given password matches the stored hash
        if passwordEntry and passwordEntry.password == password:
            # the remote entry for the user
            user = user_data[root_query()][0]
            # then return a dictionary with the user and sessionToken
            return {
                'user': user,
                'sessionToken': self._user_session_token(user)
            }

        # otherwise the passwords don't match
        raise RuntimeError("Incorrect credentials")
コード例 #3
0
    def test_root_query(self):
        # import the utility
        from nautilus.conventions.api import root_query

        # save the model to the test suite
        assert isinstance(root_query(),
                          str), ("Could not a root query string for schema")
コード例 #4
0
ファイル: test_api.py プロジェクト: nautilus/nautilus
    def test_root_query(self):
        # import the utility
        from nautilus.conventions.api import root_query

        # save the model to the test suite
        assert isinstance(root_query(), str), (
            "Could not a root query string for schema"
        )
コード例 #5
0
    async def _check_for_matching_user(self, **user_filters):
        """
            This function checks if there is a user with the same uid in the
            remote user service
            Args:
                **kwds : the filters of the user to check for
            Returns:
                (bool): wether or not there is a matching user
        """
        # there is a matching user if there are no errors and no results from
        user_data = self._get_matching_user(user_filters)

        # return true if there were no errors and at lease one  result
        return not user_data['errors'] and len(user_data['data'][root_query()])
コード例 #6
0
ファイル: apiGateway.py プロジェクト: nautilus/nautilus
    async def _check_for_matching_user(self, **user_filters):
        """
            This function checks if there is a user with the same uid in the
            remote user service
            Args:
                **kwds : the filters of the user to check for
            Returns:
                (bool): wether or not there is a matching user
        """
        # there is a matching user if there are no errors and no results from
        user_data = self._get_matching_user(user_filters)

        # return true if there were no errors and at lease one  result
        return not user_data['errors'] and len(user_data['data'][root_query()])
コード例 #7
0
    async def _get_matching_user(self, fields=[], **filters):
        # the action type for a remote query
        read_action = get_crud_action(method='read', model='user')
        # the fields of the user to ask for
        user_fields = ['pk'] + fields

        # the query for matching entries
        payload = """
            query {
                %s(%s) {
                    %s
                }
            }
        """ % (root_query(), arg_string_from_dict(filters),
               '\n'.join(user_fields))

        # perform the query and return the result
        return json.loads(await self.event_broker.ask(action_type=read_action,
                                                      payload=payload))
コード例 #8
0
ファイル: apiGateway.py プロジェクト: nautilus/nautilus
    async def _get_matching_user(self, fields=[], **filters):
        # the action type for a remote query
        read_action = get_crud_action(method='read', model='user')
        # the fields of the user to ask for
        user_fields = ['pk'] + fields

        # the query for matching entries
        payload = """
            query {
                %s(%s) {
                    %s
                }
            }
        """ % (root_query(), arg_string_from_dict(filters), '\n'.join(user_fields))

        # perform the query and return the result
        return json.loads(await self.event_broker.ask(
            action_type=read_action,
            payload=payload
        ))
コード例 #9
0
    async def object_resolver(self,
                              object_name,
                              fields,
                              obey_auth=False,
                              current_user=None,
                              **filters):
        """
            This function resolves a given object in the remote backend services
        """

        try:
            # check if an object with that name has been registered
            registered = [model for model in self._external_service_data['models'] \
                                if model['name']==object_name][0]
        # if there is no connection data yet
        except AttributeError:
            raise ValueError("No objects are registered with this schema yet.")
        # if we dont recognize the model that was requested
        except IndexError:
            raise ValueError(
                "Cannot query for object {} on this service.".format(
                    object_name))

        # the valid fields for this object
        valid_fields = [field['name'] for field in registered['fields']]

        # figure out if any invalid fields were requested
        invalid_fields = [
            field for field in fields if field not in valid_fields
        ]
        try:
            # make sure we never treat pk as invalid
            invalid_fields.remove('pk')
        # if they weren't asking for pk as a field
        except ValueError:
            pass

        # if there were
        if invalid_fields:
            # yell loudly
            raise ValueError("Cannot query for fields {!r} on {}".format(
                invalid_fields, registered['name']))

        # make sure we include the id in the request
        fields.append('pk')

        # the query for model records
        query = query_for_model(fields, **filters)

        # the action type for the question
        action_type = get_crud_action('read', object_name)

        # query the appropriate stream for the information
        response = await self.event_broker.ask(action_type=action_type,
                                               payload=query)

        # treat the reply like a json object
        response_data = json.loads(response)

        # if something went wrong
        if 'errors' in response_data and response_data['errors']:
            # return an empty response
            raise ValueError(','.join(response_data['errors']))

        # grab the valid list of matches
        result = response_data['data'][root_query()]

        # grab the auth handler for the object
        auth_criteria = self.auth_criteria.get(object_name)

        # if we care about auth requirements and there is one for this object
        if obey_auth and auth_criteria:

            # build a second list of authorized entries
            authorized_results = []

            # for each query result
            for query_result in result:
                # create a graph entity for the model
                graph_entity = GraphEntity(self,
                                           model_type=object_name,
                                           id=query_result['pk'])
                # if the auth handler passes
                if await auth_criteria(model=graph_entity,
                                       user_id=current_user):
                    # add the result to the final list
                    authorized_results.append(query_result)

            # overwrite the query result
            result = authorized_results

        # apply the auth handler to the result
        return result
コード例 #10
0
ファイル: apiGateway.py プロジェクト: nautilus/nautilus
    async def object_resolver(self, object_name, fields, obey_auth=False, current_user=None, **filters):
        """
            This function resolves a given object in the remote backend services
        """

        try:
            # check if an object with that name has been registered
            registered = [model for model in self._external_service_data['models'] \
                                if model['name']==object_name][0]
        # if there is no connection data yet
        except AttributeError:
            raise ValueError("No objects are registered with this schema yet.")
        # if we dont recognize the model that was requested
        except IndexError:
            raise ValueError("Cannot query for object {} on this service.".format(object_name))

        # the valid fields for this object
        valid_fields = [field['name'] for field in registered['fields']]

        # figure out if any invalid fields were requested
        invalid_fields = [field for field in fields if field not in valid_fields]
        try:
            # make sure we never treat pk as invalid
            invalid_fields.remove('pk')
        # if they weren't asking for pk as a field
        except ValueError:
            pass

        # if there were
        if invalid_fields:
            # yell loudly
            raise ValueError("Cannot query for fields {!r} on {}".format(
                invalid_fields, registered['name']
            ))

        # make sure we include the id in the request
        fields.append('pk')

        # the query for model records
        query = query_for_model(fields, **filters)

        # the action type for the question
        action_type = get_crud_action('read', object_name)

        # query the appropriate stream for the information
        response = await self.event_broker.ask(
            action_type=action_type,
            payload=query
        )

        # treat the reply like a json object
        response_data = json.loads(response)

        # if something went wrong
        if 'errors' in response_data and response_data['errors']:
            # return an empty response
            raise ValueError(','.join(response_data['errors']))

        # grab the valid list of matches
        result = response_data['data'][root_query()]

        # grab the auth handler for the object
        auth_criteria = self.auth_criteria.get(object_name)

        # if we care about auth requirements and there is one for this object
        if obey_auth and auth_criteria:

            # build a second list of authorized entries
            authorized_results = []

            # for each query result
            for query_result in result:
                # create a graph entity for the model
                graph_entity = GraphEntity(self, model_type=object_name, id=query_result['pk'])
                # if the auth handler passes
                if await auth_criteria(model=graph_entity, user_id=current_user):
                    # add the result to the final list
                    authorized_results.append(query_result)

            # overwrite the query result
            result = authorized_results

        # apply the auth handler to the result
        return result