예제 #1
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')
예제 #2
0
    def games_history(self, request):
        """
        JWT required. Retrieves user's completed games starting from the provided offset, or 0. Limit 10
        """
        offset = request.offset
        payload = token.decode_jwt(request.jwt_token)

        try:
            user_key = Key(urlsafe=payload.get('user_key'))
        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 retrieve user\'s games')

        try:
            games = Game.query(
                AND(
                    OR(Game.player_one == user_key,
                       Game.player_two == user_key), Game.game_completed ==
                    True)).order(-Game.date_created).fetch(offset=offset,
                                                           limit=10)
            return UserGamesHistoryResponseForm(games=[
                GamesHistory(player_one=game.player_one_name,
                             player_two=game.player_two_name,
                             game_key=game.key.urlsafe()) for game in games
            ])
        except Exception as e:
            raise endpoints.InternalServerErrorException(
                'An error occurred while retrieving completed games')
    def addSessionToWishlist(self, request):
        """Add the session to the user's wishlist of sessions they are interested in attending"""
        #get session key
        sessionKey = request.sessionKey
        # get session object
        session = ndb.Key(urlsafe=sessionKey).get()
        # check that session exists or not
        if not session:
            raise endpoints.NotFoundException(
                'No session found with key: %s' % sessionKey)

        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

        profile = self._getProfileFromUser()
        if not profile:
            raise endpoints.BadRequestException('Profile does not exist for user')
        # check if key and Session
        if not type(ndb.Key(urlsafe=sessionKey).get()) == Session:
            raise endpoints.NotFoundException('This key is not a Session instance')
        # add session to wishlist
        if sessionKey not in profile.sessionKeysInWishlist:
            try:
                profile.sessionKeysInWishlist.append(sessionKey)
                profile.put()
            except Exception:
                raise endpoints.InternalServerErrorException('Error in storing the wishlist')
        return self._copySessionToForm(session)
예제 #4
0
    def retrieve_game(self, request):
        """
        JWT required. Retrieves the game matching the provided key, and returns the game details
        """
        game_key = request.game_key
        payload = token.decode_jwt(request.jwt_token)

        try:
            user = Key(urlsafe=payload.get('user_key'))
            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 occrurred while retrieving game details')

        if game is None:
            raise endpoints.BadRequestException('That game does not exist')

        # k the game exists let's make sure it's the user's game
        if game.player_one != user and game.player_two != user:
            raise endpoints.UnauthorizedException(
                'You are not authorized to view other players games')

        return ViewGameResponseForm(game_key=game_key, game=game.to_form())
예제 #5
0
    def retrieve_invite(self, request):
        """
        JWT required. Retrieve the next 10 invites associated with the user starting from the provided offset, or 0
        """
        offset = request.offset
        payload = token.decode_jwt(request.jwt_token)

        try:
            user = Key(urlsafe=payload.get('user_key'))
        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')

        # user is here let's get their invites
        invites = Invite.query(Invite.to_player == user,
                               Invite.rejected == False,
                               Invite.accepted == False).fetch(limit=10, offset=offset)
        return RetrieveInviteResponseForm(
            invites=[InviteForm(
                inviter=invite.from_player.urlsafe(),
                inviter_name=invite.from_player_name
            ) for invite in invites]
        )
 def selfRegistration(self, request):
     user = endpoints.get_current_user()
     user_id = helper.getUserId()
     registeredUser = helper.getRegisteredUser()
     token = Token()
     if not registeredUser:
         registeredUser = RegisteredUsers()
         if request.orgKey:
             registeredUser.orgKey = ndb.Key(Organization, request.orgKey)
         else:
             raise endpoints.NotFoundException(
                 'Please give Organization key')
     else:
         raise endpoints.InternalServerErrorException(
             "User Already Registered")
     if request.studentKey:
         registeredUser.studentKey = ndb.Key(Student, request.studentKey)
         token.tokenNumber = random.randint(10000, 99999)
         token.studentKey = registeredUser.studentKey
     elif request.empKey:
         registeredUser.employeeKey = ndb.Key(Employee, request.empKey)
         token.tokenNumber = random.randint(10000, 99999)
         token.employeeKey = registeredUser.employeeKey
     registeredUser.key = ndb.Key(RegisteredUsers, user_id)
     print registeredUser
     registeredUser.put()
     token.put()
     return message_types.VoidMessage()
예제 #7
0
    def finish_upload(self, request):
        """Finishes pending upload or queries its status.

    Client should finalize Google Storage upload session first. Once GS upload
    is finalized and 'finishUpload' is called, the server starts hash
    verification. Uploading client will get 'VERIFYING' status response. It
    can continue polling on this method until server returns 'PUBLISHED' status.

    upload_session_id implicitly authorizes the request.
    """
        service = impl.get_cas_service()
        if service is None:
            raise endpoints.InternalServerErrorException(
                'Service is not configured')

        # Verify the signature if upload_session_id and grab the session. Broken
        # or expired signatures are treated in same way as missing upload sessions.
        # No need to provide more hits to the malicious caller.
        upload_session = service.fetch_upload_session(
            request.upload_session_id, auth.get_current_identity())
        if upload_session is None:
            return FinishUploadResponse(
                status=FinishUploadResponse.Status.MISSING)

        # Start object verification task if necessary, returns updated copy of
        # |upload_session| entity.
        upload_session = service.maybe_finish_upload(upload_session)

        response = FinishUploadResponse(
            status=_UPLOAD_STATUS_MAPPING[upload_session.status])
        if upload_session.status == impl.UploadSession.STATUS_ERROR:
            response.error_message = upload_session.error_message or 'Unknown error'
        return response
예제 #8
0
 def _get_token_info_url(self):
     config = self._get_open_id_config()
     if "token_endpoint" in config:
         return self._get_open_id_config()["token_endpoint"]
     else:
         raise endpoints.InternalServerErrorException(
             "token_endpoint not found in openid config: " +
             self.open_id_config_url)
예제 #9
0
 def service(self):
   """Returns configured impl.RepoService."""
   if self._service is None:
     self._service = impl.get_repo_service()
     if self._service is None or not self._service.is_fetch_configured():
       raise endpoints.InternalServerErrorException(
           'Service is not configured')
   return self._service
예제 #10
0
 def revoke_refresh_token(self, refresh_token):
     result = urlfetch.fetch(url=self.revoke_url,
                             method=urlfetch.POST,
                             payload=refresh_token)
     if result.status_code // 100 != 2:
         raise endpoints.InternalServerErrorException(
             "fence status code {}, error body {}".format(
                 result.status_code, result.content))
예제 #11
0
    def _deleteBook(self, request):
        book = get_entity_by_websafeKey_key(request.websafeKey)

        try:
            book.key.delete()
            return BooleanMessage(data=True)

        except Exception, e:
            raise endpoints.InternalServerErrorException(e.message)
예제 #12
0
def check_task_cancel_acl(task_request):
    """Checks if the caller is allowed to cancel the task.

  Checks if the caller has global permission using acl.can_edit_task().

  If the caller doesn't have any global permissions,
    Checks if the caller has either of 'swarming.pools.cancelTask' or
    'swarming.tasks.cancel' permission.

  Args:
    task_request: An instance of TaskRequest.

  Returns:
    None

  Raises:
    auth.AuthorizationError: if the caller is not allowed.
  """

    # check global permission.
    if acl.can_edit_task(task_request):
        return

    # check 'swarming.pools.cancelTask' permission of the pool in task dimensions.
    if task_request.pool:
        pool_cfg = pools_config.get_pool_config(task_request.pool)
        if not pool_cfg:
            raise endpoints.InternalServerErrorException(
                'Pool cfg not found. pool: %s' % task_request.pool)
        if pool_cfg.realm and auth.has_permission(
                get_permission(realms_pb2.REALM_PERMISSION_POOLS_CANCEL_TASK),
            [pool_cfg.realm]):
            return

    # check 'swarming.pools.cancelTask' permission of the pool in bot dimensions.
    if task_request.bot_id:
        pools = bot_management.get_pools_from_dimensions_flat(
            _retrieve_bot_dimensions(task_request.bot_id))
        pool_realms = [
            p.realm for p in map(pools_config.get_pool_config, pools)
            if p.realm
        ]
        if pool_realms and auth.has_permission(
                get_permission(realms_pb2.REALM_PERMISSION_POOLS_CANCEL_TASK),
                pool_realms):
            return

    # check 'swarming.tasks.cancel' permission.
    task_realm = task_request.realm
    if task_realm and auth.has_permission(
            get_permission(realms_pb2.REALM_PERMISSION_TASKS_CANCEL),
        [task_realm]):
        return

    raise auth.AuthorizationError('Task "%s" is not accessible' %
                                  task_request.task_id)
예제 #13
0
def _token_info(token):
    result = urlfetch.fetch('{}?{}'.format(
        _TOKENINFO_URL, urllib.urlencode({'access_token': token})))
    if result.status_code == 400:
        raise endpoints.UnauthorizedException("Invalid authorization token")
    if result.status_code != 200:
        raise endpoints.InternalServerErrorException(
            message='Token info endpoint returned status {}: {}'.format(
                result.status_code, result.content))
    return result.content
예제 #14
0
def checkAccountAccess(user, account_id, scope=settings.READ_SCOPE):
    profile = userProfile(user)
    account = Account.get(account_id)

    if profile.ownsAccount(account):
        return True

    if profile.editorOfAccount(account, scope):
        return True

    raise endpoints.InternalServerErrorException("{} tried to access account id {} with scope {}.".format(profile.email, account_id, scope))
예제 #15
0
파일: auth.py 프로젝트: winnie-lam/loaner
def _is_maintenance_mode():
    """Checks to see if the application is under maintenance.

  Raises:
    endpoints.InternalServerErrorException: If the application is currently
        under maintenance.
  """
    if (constants.MAINTENANCE
            or not config_model.Config.get('bootstrap_completed')):
        raise endpoints.InternalServerErrorException(
            'The application is currently undergoing maintenance.')
예제 #16
0
def initialize_request_auth(remote_address, headers):
    """Grabs caller identity and initializes request local authentication context.

  Called before executing a cloud endpoints method. May raise AuthorizationError
  or AuthenticationError exceptions.
  """
    config.ensure_configured()
    auth_context = api.reinitialize_request_cache()

    # Verify the validity of the token (including client_id check), if given.
    if headers.get('Authorization'):
        identity = api.check_oauth_access_token(headers)
    else:
        # Cloud Endpoints support more authentication methods than we do. Make sure
        # to fail the request if one of such methods is used.
        if endpoints.get_current_user() is not None:
            raise api.AuthenticationError('Unsupported authentication method')
        identity = model.Anonymous

    assert remote_address
    ip = ipaddr.ip_from_string(remote_address)

    # Hack to allow pure IP-whitelist based authentication for bots, until they
    # are switched to use something better.
    #
    # TODO(vadimsh): Get rid of this. Blocked on Swarming and Isolate switching
    # to service accounts.
    assert identity is not None
    if (identity.is_anonymous
            and api.is_in_ip_whitelist(model.BOTS_IP_WHITELIST, ip)):
        identity = model.IP_WHITELISTED_BOT_ID

    auth_context.peer_ip = ip
    auth_context.peer_identity = identity

    # Verify the caller is allowed to make calls from the given IP. It raises
    # AuthorizationError if IP is not allowed.
    api.verify_ip_whitelisted(identity, ip)

    # Parse delegation token, if given, to deduce end-user identity.
    delegation_tok = headers.get(delegation.HTTP_HEADER)
    if delegation_tok:
        try:
            auth_context.current_identity = delegation.check_bearer_delegation_token(
                delegation_tok, auth_context.peer_identity)
        except delegation.BadTokenError as exc:
            raise api.AuthorizationError('Bad delegation token: %s' % exc)
        except delegation.TransientError as exc:
            msg = 'Transient error while validating delegation token.\n%s' % exc
            logging.error(msg)
            raise endpoints.InternalServerErrorException(msg)
    else:
        auth_context.current_identity = auth_context.peer_identity
예제 #17
0
 def send_email(self, request):
     # Check the request for common issues
     check_request(request)
     # Setting default value for services if it isn't set
     if not request.services or request.services is None:
         requested_services = config.enabled_services
     else:
         # Deduplicate any dups in user input data
         logging.info("Got request to process using certain services")
         requested_services = []
         for i in request.services:
             service_lower = i.lower()
             if service_lower in config.enabled_services:
                 if service_lower not in requested_services:
                     requested_services.append(service_lower)
             else:
                 logging.warning(
                     "Got requested service %s which we don't support" %
                     service_lower)
     # Add the request to the DB
     # We currently don't use this, yet...
     mail_db = add_request_to_db(request)
     # Loop through the services and try to send a message
     for service_name in requested_services:
         logging.info("Going to try and send e-mail with %s" % service_name)
         # If the user requested a service that we don't support, skip
         if not service_name in services:
             logging.warning("We don't support %s. Skipping" % service_name)
             continue
         # Get the Object we need to call
         mail_service = services[service_name]
         ret = mail_service.send_mail(sender=request.sender,
                                      to=request.to,
                                      subject=request.subject,
                                      body=request.body,
                                      cc=request.cc,
                                      bcc=request.bcc)
         if ret:
             logging.info("Successfully sent e-mail using %s" %
                          service_name)
             mail_db.sent = True
             mail_db.service = service_name
             mail_db.put()
             return SimpleResponse(message="Sent Mail",
                                   service=service_name)
         else:
             logging.warning(
                 "Couldn't send e-mail with %s. Will try with other services"
                 % service_name)
     message = "Exhausted services to send email with"
     logging.error(message)
     raise endpoints.InternalServerErrorException(message)
예제 #18
0
def user_from_token(token):
    jwt_secret = config.CFG_DB.jwt_secret
    if not jwt_secret:
        raise endpoints.InternalServerErrorException(
            'JWT configuration missed.')

    try:
        payload = jwt.decode(token, jwt_secret)
        logging.info(payload)
    except jwt.InvalidTokenError:
        raise endpoints.UnauthorizedException("Token validation failed.")

    return db.model.User.get_by_id(payload.get(u'user_id'))
예제 #19
0
        def to_message((build_id, build, ex)):
            msg = self.HeartbeatBatchResponseMessage.OneHeartbeatResult(
                build_id=build_id)
            if build:
                msg.lease_expiration_ts = utils.datetime_to_timestamp(
                    build.lease_expiration_date)
            else:
                if type(ex) not in ERROR_REASON_MAP:
                    logging.error(ex.message, exc_info=ex)
                    raise endpoints.InternalServerErrorException(ex.message)
                msg.error = exception_to_error_message(ex)

            return msg
예제 #20
0
def copyStagingFilepathsToGcs(request, account_id, bill_id, bill = None):
    filepaths = []
    for staging_filepath in request.staging_filepaths:
        filename = os.path.basename(staging_filepath.data)
        filepath = getFilepath(account_id, bill_id, filename)
        if bill and (filepath in bill.filepaths):
            raise endpoints.InternalServerErrorException("{} file already uploaded.".format(filename))
        filepaths.append(filepath)
        gcs.copy2(
                '/' + settings.STAGING_FILE_BUCKET + staging_filepath.data,
                '/' + settings.FILE_BUCKET + filepath)

    return filepaths
예제 #21
0
    def cancel_invite(self, request):
        """
        JWT required. Cancel the invite associated with the user
        """
        target_user = request.target_user
        payload = token.decode_jwt(request.jwt_token)

        try:
            user = Key(urlsafe=payload.get('user_key'))
        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 target_user is None or target_user is '':
            raise endpoints.BadRequestException('The target user was not provided')

        invite = Invite.query(Invite.from_player == user,
                               Invite.rejected == False,
                               Invite.accepted == False).get()

        if invite is None:
            invite = Invite.query(Invite.to_player == user,
                                  Invite.rejected == False,
                                  Invite.accepted == False).get()

        if invite is None:
            raise endpoints.BadRequestException('No pending invites exist for these users')

        # let's cancel the invite
        try:
            invite.rejected = True
            invite.put()
            return message_types.VoidMessage()
        except:
            raise endpoints.InternalServerErrorException('An error occurred while attempting to cancel the invite')
예제 #22
0
 def user_score(self, request):
     """
     Retrieve the 10 users with highest scores in a single game, ordered from highest to lowest
     """
     try:
         games = Game.query(Game.player_one_completed == True,
                            Game.player_two_completed == True).order(-Game.winner_score).fetch(limit=10)
         return UserHighScoreResponseForm(
             players=[UserHighScore(
                 username=game.winner_name,
                 score=game.winner_score
             ) for game in games]
         )
     except:
         raise endpoints.InternalServerErrorException('An error occurred retrieving high scores')
예제 #23
0
 def user_rank(self, request):
     """
     Retrieve the 10 users with the most wins, ordered from highest to lowest
     """
     try:
         users = User.query().order(-User.wins).fetch(limit=10)
         return UserRankResponseForm(
             players=[UserRank(
                 username=user.username,
                 wins=user.wins
             ) for user in users]
         )
     except Exception as e:
         print e.message
         raise endpoints.InternalServerErrorException('An error occurred retrieving user ranks')
예제 #24
0
 def enable_guest_mode(self, request):
     """Enables Guest Mode for a given device."""
     self.check_xsrf_token(self.request_state)
     device = _get_device(request)
     user_email = user_lib.get_user_email()
     try:
         device.enable_guest_mode(user_email)
     except device_model.EnableGuestError as err:
         raise endpoints.InternalServerErrorException(str(err))
     except (device_model.UnassignedDeviceError,
             device_model.GuestNotAllowedError,
             device_model.UnauthorizedError) as err:
         raise endpoints.UnauthorizedException(str(err))
     else:
         return message_types.VoidMessage()
예제 #25
0
 def delete_credentials_google(self, access_token, key_id):
     """
     Calls fence DELETE /user/credentials/google/key_id api
     :param access_token: oauth access token
     :param key_id: key_id to delete
     :return: service account key json
     """
     headers = {'Authorization': 'Bearer ' + access_token}
     result = urlfetch.fetch(url=self.delete_service_account_url + key_id,
                             headers=headers,
                             method=urlfetch.DELETE)
     if result.status_code // 100 != 2:
         raise endpoints.InternalServerErrorException(
             "fence status code {}, error body {}".format(
                 result.status_code, result.content))
예제 #26
0
파일: api.py 프로젝트: onecityuni/luci-py
 def reimport(self, request):
     """Reimports a config set."""
     if not auth.is_admin():
         raise endpoints.ForbiddenException(
             'Only admins are allowed to do this')
     # Assume it is Gitiles.
     try:
         gitiles_import.import_config_set(request.config_set)
         return message_types.VoidMessage()
     except gitiles_import.NotFoundError as e:
         raise endpoints.NotFoundException(e.message)
     except ValueError as e:
         raise endpoints.BadRequestException(e.message)
     except gitiles_import.Error as e:
         raise endpoints.InternalServerErrorException(e.message)
예제 #27
0
 def status(self, request):
     subsystems = self.status_service.get()
     ok = all(subsystem["ok"] for subsystem in subsystems)
     response = StatusResponse(ok=ok,
                               subsystems=[
                                   SubSystemStatusResponse(
                                       ok=subsystem["ok"],
                                       message=subsystem["message"],
                                       subsystem=subsystem["subsystem"])
                                   for subsystem in subsystems
                               ])
     if ok:
         return response
     else:
         raise endpoints.InternalServerErrorException(response)
예제 #28
0
 def cancel_game(self,request):
     """Cancel unfinished game"""
     game = get_by_urlsafe(request.urlsafe_game_key, Game)
     if game:
         if game.game_over:
             return Message(message = "Completed Game cannot be deleted.")
         else:
             try:
                 game.key.delete()
             except Exception:
                 raise endpoints.InternalServerErrorException(
                     'Error in cencelling the game')
         return Message(message = "Game Deleted")
     else:
         raise endpoints.NotFoundException('Game not found!')
예제 #29
0
 def get_credentials_google(self, access_token):
     """
     Calls fence POST /user/credentials/google api
     :param access_token: oauth access token
     :return: service account key json
     """
     headers = {'Authorization': 'Bearer ' + access_token}
     result = urlfetch.fetch(url=self.credentials_google_url,
                             headers=headers,
                             method=urlfetch.POST)
     if result.status_code // 100 == 2:
         return result.content
     else:
         raise endpoints.InternalServerErrorException(
             "fence status code {}, error body {}".format(
                 result.status_code, result.content))
예제 #30
0
    def retrieve_users(self, request):
        """
        Return 10 users starting from the provided offset, or 0
        """
        offset = request.offset

        try:
            users = User.query().fetch(offset=offset, limit=10)
            return UserAllResponseForm(users=[
                UserForm(username=user.username, user_key=user.key.urlsafe())
                for user in users
            ])
        except Exception as e:
            print e.message
            raise endpoints.InternalServerErrorException(
                'An error occurred while retrieving users')