예제 #1
0
파일: api.py 프로젝트: jerrayl/Plutus
 def signup(self, request):
     models.User(age=request.age,
                 income=request.income,
                 is_income_stable=request.is_income_stable,
                 balance=request.balance).put()
     functions.add_goals()
     return message_types.VoidMessage()
예제 #2
0
    def __request_message_descriptor(self, request_kind, message_type,
                                     method_id, path):
        """Describes the parameters and body of the request.

    Args:
      request_kind: The type of request being made.
      message_type: messages.Message or ResourceContainer class. The message to
          describe.
      method_id: string, Unique method identifier (e.g. 'myapi.items.method')
      path: string, HTTP path to method.

    Returns:
      Dictionary describing the request.

    Raises:
      ValueError: if the method path and request required fields do not match
    """
        if isinstance(message_type, resource_container.ResourceContainer):
            base_message_type = message_type.body_message_class()
        else:
            base_message_type = message_type

        if (request_kind != self.__NO_BODY
                and base_message_type != message_types.VoidMessage()):
            self.__request_schema[method_id] = self.__parser.add_message(
                base_message_type.__class__)

        params = self.__params_descriptor(message_type, request_kind, path,
                                          method_id)

        return params
예제 #3
0
    def __response_message_descriptor(self, message_type, method_id):
        """Describes the response.

    Args:
      message_type: messages.Message class, The message to describe.
      method_id: string, Unique method identifier (e.g. 'myapi.items.method')

    Returns:
      Dictionary describing the response.
    """

        # Skeleton response descriptor, common to all response objects
        descriptor = {'200': {'description': 'A successful response'}}

        if message_type != message_types.VoidMessage():
            self.__parser.add_message(message_type.__class__)
            self.__response_schema[
                method_id] = self.__parser.ref_for_message_type(
                    message_type.__class__)
            descriptor['200']['schema'] = {
                '$ref':
                '#/definitions/{0}'.format(self.__response_schema[method_id])
            }

        return dict(descriptor)
예제 #4
0
  def components_delete(self, request):
    """Delete a component."""
    mar = self.mar_factory(request)
    config = self._services.config.GetProjectConfig(mar.cnxn, mar.project_id)
    component_path = request.componentPath
    component_def = tracker_bizobj.FindComponentDef(
        component_path, config)
    if not component_def:
      raise config_svc.NoSuchComponentException(
          'The component %s does not exist.' % component_path)
    if not permissions.CanViewComponentDef(
        mar.auth.effective_ids, mar.perms, mar.project, component_def):
      raise permissions.PermissionException(
          'User is not allowed to view this component %s' % component_path)
    if not permissions.CanEditComponentDef(
        mar.auth.effective_ids, mar.perms, mar.project, component_def, config):
      raise permissions.PermissionException(
          'User is not allowed to delete this component %s' % component_path)

    allow_delete = not tracker_bizobj.FindDescendantComponents(
        config, component_def)
    if not allow_delete:
      raise permissions.PermissionException(
          'User tried to delete component that had subcomponents')

    self._services.issue.DeleteComponentReferences(
        mar.cnxn, component_def.component_id)
    self._services.config.DeleteComponentDef(
        mar.cnxn, mar.project_id, component_def.component_id)
    return message_types.VoidMessage()
예제 #5
0
  def testMaybeSetVarsWithActualRequestAccessToken(self, mock_local, mock_get_client_id, mock_get_authorized_scopes):
    dummy_scope = 'scope'
    dummy_token = 'dummy_token'
    dummy_email = '*****@*****.**'
    dummy_client_id = self._SAMPLE_ALLOWED_CLIENT_IDS[0]

    @api_config.api('testapi', 'v1',
                    allowed_client_ids=self._SAMPLE_ALLOWED_CLIENT_IDS,
                    scopes=[dummy_scope])
    class TestApiScopes(remote.Service):
      """Describes TestApiScopes."""

      # pylint: disable=g-bad-name
      @api_config.method(message_types.VoidMessage, message_types.VoidMessage)
      def method(self, request):
        return request

    # users_id_token._get_id_token_user and time.time don't need to be stubbed
    # because the scopes used will not be [EMAIL_SCOPE] hence _get_id_token_user
    # will never be attempted

    mock_local.return_value = False
    mock_get_client_id.return_value = dummy_client_id
    mock_get_authorized_scopes.return_value = [dummy_scope]

    api_instance = TestApiScopes()
    os.environ['HTTP_AUTHORIZATION'] = 'Bearer ' + dummy_token
    api_instance.method(message_types.VoidMessage())
    assert os.getenv('ENDPOINTS_USE_OAUTH_SCOPE') == dummy_scope
    mock_local.assert_has_calls([mock.call(), mock.call()])
    mock_get_client_id.assert_called_once_with([dummy_scope])
    mock_get_authorized_scopes.assert_called_once_with([dummy_scope])
예제 #6
0
    def audit(self, request):
        """Performs an audit on a shelf based on location."""
        self.check_xsrf_token(self.request_state)
        shelf = get_shelf(request.shelf_request)
        user_email = user.get_user_email()
        devices_on_shelf = []
        shelf_string_query = 'shelf: {}'.format(shelf.key.urlsafe())
        devices_retrieved_on_shelf = device_model.Device.search(
            shelf_string_query)
        for device_identifier in request.device_identifiers:
            device = device_model.Device.get(
                unknown_identifier=device_identifier)
            if not device:
                raise endpoints.NotFoundException(_DEVICE_DOES_NOT_EXIST_MSG %
                                                  device_identifier)
            if device.shelf:
                if device.shelf == shelf.key:
                    devices_on_shelf.append(device.key.urlsafe())
                    logging.info('Device %s is already on shelf.',
                                 device.serial_number)
                    continue
            try:
                device.move_to_shelf(shelf=shelf, user_email=user_email)
                devices_on_shelf.append(device.key)
            except device_model.UnableToMoveToShelfError as err:
                raise endpoints.BadRequestException(str(err))
        for device in devices_retrieved_on_shelf.results:
            if device.doc_id not in devices_on_shelf:
                api_utils.get_ndb_key(device.doc_id).get().remove_from_shelf(
                    shelf=shelf, user_email=user_email)
        shelf.audit(user_email=user_email)

        return message_types.VoidMessage()
예제 #7
0
    def __params_descriptor_without_container(self, message_type, request_kind,
                                              method_id, path):
        """Describe parameters of a method which does not use a ResourceContainer.

    Makes sure that the path parameters are included in the message definition
    and adds any required fields and URL query parameters.

    This method is to preserve backwards compatibility and will be removed in
    a future release.

    Args:
      message_type: messages.Message class, Message with parameters to describe.
      request_kind: The type of request being made.
      method_id: string, Unique method identifier (e.g. 'myapi.items.method')
      path: string, HTTP path to method.

    Returns:
      A list of dicts: Descriptors of the parameters
    """
        params = []

        path_parameter_dict = self.__get_path_parameters(path)
        for field in sorted(message_type.all_fields(), key=lambda f: f.number):
            matched_path_parameters = path_parameter_dict.get(field.name, [])
            self.__validate_path_parameters(field, matched_path_parameters)

            if matched_path_parameters or request_kind == self.__NO_BODY:
                self.__add_parameter(field, matched_path_parameters, params)

        # If the request has a body, add the body parameter
        if (message_type != message_types.VoidMessage()
                and request_kind == self.__HAS_BODY):
            params.append(self.__body_parameter_descriptor(method_id))

        return params
예제 #8
0
 def reindex(self, request):
     """Reindex a search index for the given type."""
     if request.model == search_messages.SearchIndexEnum.DEVICE:
         device_model.Device.index_entities_for_search()
     elif request.model == search_messages.SearchIndexEnum.SHELF:
         shelf_model.Shelf.index_entities_for_search()
     return message_types.VoidMessage()
  def BatchDeleteNotes(self, request):
    """Delete notes of a device.

    Args:
      request: an API request.
    Request Params:
      device_serial: string, the serial of a lab device.
      ids: a list of strings, the ids of notes to delete.

    Returns:
      a message_types.VoidMessage object.

    Raises:
      endpoints.BadRequestException, when request does not match existing notes.
    """
    keys = [
        ndb.Key(datastore_entities.Note, entity_id)
        for entity_id in request.ids
    ]
    note_entities = ndb.get_multi(keys)
    for key, note_entity in zip(keys, note_entities):
      if not note_entity or note_entity.device_serial != request.device_serial:
        raise endpoints.BadRequestException(
            "Note<id:{0}> does not exist under device<serial:{1}>.".format(
                key.id(), note_entity.device_serial))
    for key in keys:
      key.delete()
    return message_types.VoidMessage()
예제 #10
0
    def delete(self, request):
        """ Remove a purchase.
        """

        models.delete(request.id)

        return message_types.VoidMessage()
예제 #11
0
 def clear(self, request):
     """Clear a search index for the given type."""
     if request.model == search_messages.SearchIndexEnum.DEVICE:
         device_model.Device.clear_index()
     elif request.model == search_messages.SearchIndexEnum.SHELF:
         shelf_model.Shelf.clear_index()
     return message_types.VoidMessage()
예제 #12
0
    def deleteAllConferenceSessions(self, request):
        """Delete all sessions (by websafeConferenceKey)."""
        # preload necessary data items
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()
        # check that conference exists
        if not conf:
            raise endpoints.NotFoundException(
                'No conference found with key: %s' %
                request.websafeConferenceKey)

        # check that user is owner
        if user_id != conf.organizerUserId:
            raise endpoints.ForbiddenException(
                'Only the owner can update the conference.')

        conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()
        sessions = Session.query(ancestor=conf.key)
        for session in sessions:
            session.key.delete()
        return message_types.VoidMessage()
예제 #13
0
    def delete_shouts(self, request):

        # This sample runs it in the mappers backend, with 100 batches, the more things you do in map
        # the smaller the batch should be to avoid duplicate runs on failures
        deferred.defer(demo.DeleteAllShout().run, 100)

        return message_types.VoidMessage()
예제 #14
0
파일: api.py 프로젝트: jerrayl/Plutus
 def add_investment(self, request):
     users = models.User.query().fetch()
     user = users[0]
     if request.type == "Bond":
         user.all_investments.append(
             models.Investment(name=request.name,
                               type=request.type,
                               value=request.value,
                               date_end=request.date_end,
                               interest=request.interest,
                               period=request.period))
     elif request.type == "Stocks":
         user.all_investments.append(
             models.Investment(name=request.name,
                               type=request.type,
                               value=request.value,
                               qty=request.qty,
                               ticker=request.ticker))
     else:
         user.all_investments.append(
             models.Investment(name=request.name,
                               type=request.type,
                               value=request.value,
                               qty=request.qty))
     user.put()
     return message_types.VoidMessage()
예제 #15
0
 def update(self, request):
     """Updates a role's permissions or associated group. Cannot edit name."""
     self.check_xsrf_token(self.request_state)
     role = user_model.Role.get_by_name(request.name)
     role.update(permissions=request.permissions,
                 associated_group=request.associated_group)
     return message_types.VoidMessage()
예제 #16
0
파일: api.py 프로젝트: jerrayl/Eduto
 def add_suggestion(self, request):
     suggestions.add(text=request.text,
                     date=request.date,
                     subject=request.subject,
                     location=request.location,
                     usr=endpoints.get_current_user())
     return message_types.VoidMessage()
예제 #17
0
    def cancel_game(self, request):
        """
        JWT required. This will cancel the game associated with the provided game key.
        """
        game_key = request.game_key
        payload = token.decode_jwt(request.jwt_token)

        try:
            user = Key(urlsafe=payload.get('user_key')).get()
            game = Key(urlsafe=game_key).get()
        except TypeError:
            raise endpoints.BadRequestException(
                'key was unable to be retrieved')
        except ProtocolBufferDecodeError:
            raise endpoints.BadRequestException(
                'key was unable to be retrieved')
        except Exception as e:
            raise endpoints.InternalServerErrorException(
                'An error occurred when attempting to take the turn')

        if user is None or game is None:
            raise endpoints.BadRequestException(
                'Could not locate the user and game specified')

        try:
            if game.player_one != user.key and game.player_two != user.key:
                # this isn't even the user's game!
                raise endpoints.UnauthorizedException(
                    'Can not cancel someone else\'s game')

            if game.player_one_completed is True and game.player_two_completed is True:
                raise endpoints.BadRequestException(
                    'Can not cancel a game that has already been completed')

            if game.player_one_cancelled is True or game.player_two_cancelled is True:
                raise endpoints.BadRequestException(
                    'Game has been cancelled already')

            # game has not been completed / cancelled already
            if game.player_one == user.key:
                game.player_one_cancelled = True
                game.player_two_completed = True
                player_two = game.player_two.get()
                player_two.wins += 1
                game.put()
                player_two.put()
            elif game.player_two == user.key:
                game.player_two_cancelled = True
                game.player_one_completed = True
                player_one = game.player_one.get()
                player_one.wins += 1
                game.put()
                player_one.put()

            return message_types.VoidMessage()

        except Exception as e:
            # print e.message
            raise endpoints.InternalServerErrorException(
                'An error occurred while trying to cancel the game')
예제 #18
0
파일: api.py 프로젝트: jerrayl/Eduto
 def add_task(self, request):
     task.add(subject=request.subject,
              cls=request.cls,
              title=request.title,
              due_date=request.due_date,
              usr=endpoints.get_current_user())
     return message_types.VoidMessage()
 def update_rating(self, request):
     #First query the companionship rating
     companion_ship_rating = ndb.Key(urlsafe=request.key).get()
     #Now update the rating
     companion_ship_rating.rating = request.rating
     companion_ship_rating.put()
     return message_types.VoidMessage()
예제 #20
0
 def create(self, request):
     """Creates a new role."""
     self.check_xsrf_token(self.request_state)
     user_model.Role.create(name=request.name,
                            role_permissions=request.permissions,
                            associated_group=request.associated_group)
     return message_types.VoidMessage()
예제 #21
0
    def SubmitHostEvents(self, request):
        """Submit a bundle of cluster host events for processing.

    Args:
      request: a HostEventList
    Returns:
      a VoidMessage
    """
        # Convert the request message to json for the taskqueue payload
        encoded_message = protojson.encode_message(request)  # pytype: disable=module-attr
        json_message = json.loads(encoded_message)
        host_events = json_message.get("host_events")
        if not host_events:
            raise endpoints.BadRequestException("Request has no host_events.")
        logging.info(
            "Submitting host event message with size %d and %d events",
            len(encoded_message), len(host_events))
        for event_chunk in chunks(host_events, CHUNK_SIZE):
            logging.info("Queuing host event chunk of size %d",
                         len(event_chunk))
            task_scheduler.AddCallableTask(
                self._ProcessHostEventWithNDB,
                event_chunk,
                _queue=host_event.HOST_EVENT_QUEUE_NDB,
                _target="%s.%s" %
                (common.GetServiceVersion(), common.GetServiceName()))
        logging.debug("Submitted host event message.")
        return message_types.VoidMessage()
예제 #22
0
  def disable(self, request):
    """Disable a shelf by its location."""
    self.check_xsrf_token(self.request_state)
    user_email = user.get_user_email()
    shelf = get_shelf(request)
    shelf.disable(user_email)

    return message_types.VoidMessage()
예제 #23
0
    def test_get__superadmin(self):
        self.login_admin_endpoints_user()

        response = self.service.get(message_types.VoidMessage())

        self.assertCountEqual(response.permissions,
                              user_api.permissions.Permissions.ALL)
        self.assertTrue(response.superadmin)
예제 #24
0
 def mark_lost(self, request):
     """Mark that a device is lost."""
     self.check_xsrf_token(self.request_state)
     device = _get_device(request)
     user_email = user_lib.get_user_email()
     _confirm_user_action(user_email, device)
     device.mark_lost(user_email=user_lib.get_user_email())
     return message_types.VoidMessage()
예제 #25
0
 def update(self, request):
   """Get a shelf using location to update its properties."""
   self.check_xsrf_token(self.request_state)
   user_email = user.get_user_email()
   shelf = get_shelf(request.shelf_request)
   kwargs = api_utils.to_dict(request, shelf_model.Shelf)
   shelf.edit(user_email=user_email, **kwargs)
   return message_types.VoidMessage()
예제 #26
0
 def generate_data(self, request):
     """
     Exposes an API endpoint to generate a random data set for testing.
     Only run once.
     Data set parameters adjustable in the backend
     """
     generate_sample_data()
     return message_types.VoidMessage()
예제 #27
0
 def logout(self, instance):
     """
     :param instance:
     :return no-content:
     """
     logging.info(instance)
     User.delete_auth_token(self.user.get_id(), self.token)
     return message_types.VoidMessage()
예제 #28
0
    def delete(self, request):
        """Remove uma compra relaizada.
		"""

        #Removendo purchase
        models.delete(request.id)

        return message_types.VoidMessage()
예제 #29
0
  def enable(self, request):
    """Enable a shelf based on its location."""
    self.check_xsrf_token(self.request_state)
    user_email = user.get_user_email()
    shelf = get_shelf(location=request.location)
    shelf.enable(user_email)

    return message_types.VoidMessage()
예제 #30
0
  def testRunServicesWithOutRegistry(self):
    request = Request1(string_field='request value')

    status, response = self.DoRequest('/protorpc.services',
                                      message_types.VoidMessage(),
                                      registry.ServicesResponse,
                                      reg_path=None)
    self.assertEquals('Status: 404 Not Found', status)