def check(self): api_key = None api_key_text = self.request.GET.get('key', None) if api_key_text is None: self.log_count('{view_name}.no_api_key') if self.error_on_invalidkey: return self.invalid_api_key() try: api_key = ApiKey.getkey(self.request.db_ro_session, api_key_text) except Exception: # pragma: no cover # if we cannot connect to backend DB, skip api key check self.raven_client.captureException() if api_key is not None: self.log_count('{view_name}.api_key.{api_key}', api_key=api_key.name) rate_key = 'apilimit:{key}:{time}'.format( key=api_key_text, time=util.utcnow().strftime('%Y%m%d') ) should_limit = rate_limit( self.redis_client, rate_key, maxreq=api_key.maxreq ) if should_limit: return self.forbidden() else: if api_key_text is not None: self.log_count('{view_name}.unknown_api_key') if self.error_on_invalidkey: return self.invalid_api_key() # If we failed to look up an ApiKey, create an empty one # rather than passing None through api_key = api_key or ApiKey(valid_key=None) return self.view(api_key)
def closure(request, *args, **kwargs): raven_client = request.registry.raven_client stats_client = request.registry.stats_client api_key = None api_key_text = request.GET.get('key', None) if api_key_text is None: stats_client.incr('%s.no_api_key' % func_name) if error_on_invalidkey: return invalid_api_key_response() try: api_key = ApiKey.getkey(request.db_ro_session, api_key_text) except Exception: # pragma: no cover # if we cannot connect to backend DB, skip api key check raven_client.captureException() stats_client.incr('%s.dbfailure_skip_api_key' % func_name) if api_key is not None: stats_client.incr('%s.api_key.%s' % (func_name, api_key.name)) should_limit = rate_limit(request.registry.redis_client, api_key_text, maxreq=api_key.maxreq) if should_limit: response = HTTPForbidden() response.content_type = 'application/json' response.body = DAILY_LIMIT return response elif should_limit is None: # pragma: no cover # We couldn't connect to Redis stats_client.incr('%s.redisfailure_skip_limit' % func_name) else: stats_client.incr('%s.unknown_api_key' % func_name) if error_on_invalidkey: return invalid_api_key_response() # If we failed to look up an ApiKey, create an empty one # rather than passing None through api_key = api_key or ApiKey() return func(request, api_key, *args, **kwargs)