desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Extracts the user cookie from an HTTP response and returns it if it exists, or returns None if not.'
def _GetUserCookieFromResponse(self, response):
user_cookie_header = [h for h in response.headers.get_list('Set-Cookie') if h.startswith('user=')][(-1)] return re.match('user="?([^";]*)', user_cookie_header).group(1)
'Loads a previous authorization cookie for this client from file.'
def _LoadAuthentication(self):
auth_file = self._AuthFilePath() if os.path.exists(auth_file): try: fh = open(auth_file, 'r') self._user_cookie = fh.read() except: logging.fatal('Exception loading authorization file %s', auth_file, exc_info=True) raise ScenarioLoginEr...
'Save the authorization cookie to a local file.'
def _SaveAuthentication(self):
auth_file = self._AuthFilePath() try: dir = os.path.dirname(auth_file) if (not os.path.exists(dir)): os.makedirs(dir) fh = open(auth_file, 'w') fh.write(self._user_cookie) fh.close() except: logging.fatal('Failed to save authorization f...
'Clears any existing authorization for this client.'
def _ClearAuthentication(self):
auth_file = self._AuthFilePath() if os.path.exists(auth_file): try: os.remove(auth_file) except: logging.fatal('Could not clear authorization file %s', auth_file, exc_info=True) raise ScenarioLoginError(('Error clearing auth file for...
'Test that a scenario properly handles log messages.'
def testScenario(self):
fake_device = object() def _ScenarioOne(device, logger, callback): self.assertTrue((device is fake_device)) logger.info('Info message') callback() scenario = Scenario('My Scenario', _ScenarioOne, 0.5) catcher = LogCatcher(5, self.stop) with catcher: scenario.Sta...
'Test that a scenario properly handles thrown exceptions.'
def testScenarioError(self):
fake_device = object() def _ScenarioTwo(device, logger, callback): raise ValueError('Value Error') scenario = Scenario('My Scenario', _ScenarioTwo, 0.5) catcher = LogCatcher(5, self.stop) with catcher: scenario.StartLoop(fake_device) self.wait(timeout=10) self.asser...
'Test that the formatted message for service health alerts matches the expected format.'
def testServiceHealthMessage(self):
expected = '(2 Alerts): Alert description.(2 machines), Cluster alert.(Cluster)' report = {'status': 'ALERT', 'alerts': [{'name': 'Alert1', 'count': 2, 'cluster': False, 'description': 'Alert description.'}, {'name': 'Alert2', 'count': 1, 'cluster': True, 'description': 'Cluster alert.'}...
'Begin running watchdog scenarios. The shutdown callback passed into this method should be invoked if the Watchdog\'s Stop() method is invoked.'
def Run(self, shutdown_callback):
self.shutdown_callback = shutdown_callback logging.getLogger().addHandler(self) for s in self.scenarios.values(): s.StartLoop(self.device)
'Stop this Watchdog\'s scenarios from running. This method will call the shutdown_callback provided to the Run() method.'
def Stop(self):
logging.getLogger().removeHandler(self) for s in self.scenarios.values(): s.StopLoop() self.shutdown_callback()
'The emit method is called whenever log messages of WARNING or greater level are received. The watchdog will determine if the specific message warrants the sending of an alert.'
def emit(self, record):
scenario_name = getattr(record, 'scenario', None) if (scenario_name is not None): scenario = self.scenarios[scenario_name] error_stat = self.error_stats[scenario_name] if (record.levelno >= logging.ERROR): self.Alert(scenario, self.format(record)) else: er...
'Send an SMS Alert if one has not been sent too recently.'
def Alert(self, scenario, message):
logging.info('Alert was called from scenario %s with message %s', scenario.name, message) if (self._alert_hook is not None): self._alert_hook(scenario, message) return now = time.time() if (now < (self._last_alert + MINIMUM_ALERT_SPACING)): logging.info('A...
'Load a template and return it wrapped in a tornado Template object.'
def LoadTemplate(self, name):
return self._loader.load(name)
'Load and generate the template with the given name, using the given arguments.'
def GenerateTemplate(self, name, **kwargs):
return self._loader.load(name).generate(**kwargs)
'Returns a list of asset urls for the given resource group. If --compile_assets is true, this will be the compiled output, otherwise it will return the input files directly. The returned paths should be passed through static_url() to get a full versioned url (this is done automatically for UIModules, so in a module you...
def GetAssetPaths(self, name):
urls = self._assets[name].urls() return [ResourcesManager._STATIC_URL_RE.match(url).group(1) for url in urls]
'Return path to assets to be included in user off boarding zip files'
def GetOffboardingPath(self):
return self.offboarding_path
'Get current global instance of the resource manager.'
@staticmethod def Instance():
if (not hasattr(ResourcesManager, '_instance')): ResourcesManager._instance = ResourcesManager() return ResourcesManager._instance
'Prepares a calendar for the specified \'calendar_id\'.'
def __init__(self, calendar_id):
self.calendar_id = calendar_id cal_path = os.path.dirname(__file__) path = os.path.join(cal_path, (Calendar._RESOURCES_CALENDARS_FMT % self.calendar_id)) with open(path, 'rb') as f: self._cal = vobject.readOne(f)
'Returns the events from the calendar for the year specified. In cases where the calendar does not span the requested year, throws a \'NoCalendarDataError\' exception.'
def GetEvents(self, year):
events = [] for event in self._cal.components(): if (event.name == 'VEVENT'): name = event.summary.value if event.getrruleset(): rruleset = event.getrruleset() dates = rruleset.between(datetime.datetime((year - 1), 12, 31), datetime.datetime((year ...
'Attempts to locate a cached version of \'calendar_id\'. If none is found, attempts to load from disk.'
@classmethod def GetCalendar(cls, calendar_id=None):
calendar_id = (calendar_id or Calendar._DEFAULT_CALENDAR_ID) if (not Calendar._cache.has_key(calendar_id)): cal = Calendar(calendar_id) Calendar._cache[calendar_id] = cal return Calendar._cache[calendar_id]
'Attempts to match the specified locale with a holidays calendar. Normalizes the locale by replacing \'-\' with \'_\'.'
@classmethod def GetHolidaysByLocale(cls, locale='en_US'):
locale = locale.replace('-', '_') calendar_id = (Calendar._locale_to_holiday_calendar_map.get(locale, None) or Calendar._DEFAULT_CALENDAR_ID) return Calendar.GetCalendar(calendar_id)
'Reads US holidays calendar and gets events from current year.'
def testSimple(self):
cal = Calendar.GetCalendar() year = time.gmtime().tm_year events = cal.GetEvents(year=year) for holiday in ('Halloween', 'Independence Day', 'Labor Day', 'Memorial Day', "New Year's Day", 'Christmas Day', 'Thanksgiving Day'): self.assertEqual(len([ev for ev in events if (ev[...
'Verify US holidays are default.'
def testDefault(self):
default_cal = Calendar.GetCalendar() us_holidays = Calendar.GetCalendar('USHolidays.ics') self.assertEqual(default_cal, us_holidays)
'Verifies calendar objects are cached on successive calls.'
def testCaching(self):
cal1 = Calendar.GetCalendar() cal2 = Calendar.GetCalendar() self.assertEqual(cal1, cal2)
'Verifies holiday calendars can be fetched directly by locale.'
def testByLocale(self):
def _VerifyHoliday(cal, name, start_month, start_day, end_month, end_day): 'Verifies that a holiday with the specified name and date exists.' year = datetime.date.today().year dtstart = time.mktime(datetime.datetime(year, start_month, start_day).timetuple()) ...
'Sends an email message. Invokes \'callback\' on successful completion. All Unicode strings will be encoded. Subclasses should call self._ValidateArgs.'
def SendEmail(self, callback, description=None, **kwargs):
raise NotImplementedError()
'Returns the address for system informational emails (e.g. info@mailer.viewfinder.co).'
def GetInfoAddress(self):
return ('%s@%s' % (options.options.info, options.options.mailer_domain))
'Sets a new instance for testing.'
@staticmethod def SetInstance(email_mgr):
EmailManager._instance = email_mgr
'Sends an email message through SendGrid. Returns \'callback\' on successful completion. All unicode strings are encoded before being sent to SendGrid.'
def SendEmail(self, callback, description=None, **kwargs):
self._ValidateArgs(kwargs) def _OnSend(response): 'Parses JSON response.' if response.error: raise EmailError(('SendGrid API error: %d %.1024s [%s]' % (response.code, response.error, response.body))) result = escape.json_decode(response.body) if r...
'Returns the verification status code. Status is 0 on success, or one of the error codes defined in this class.'
def GetStatus(self):
return self.response['status']
'Returns True if the receipt is properly formatted and signed. Returns False if the receipt is invalid; raises an ITunesStoreError if the validity could not be determined and will need to be retried later. Note that expired receipts are still considered "valid" by this function, so the expiration date must be checked s...
def IsValid(self):
status = self.GetStatus() if ((status == 0) or (status == VerifyResponse.EXPIRED_ERROR)): if (self.GetBundleId() != kViewfinderBundleId): logging.warning('got signed receipt for another app: %s', self.GetBundleId()) return False return True elif (sta...
'Returns the latest decoded receipt info as a dict. This may be different than the receipt originally passed in if a renewal has occurred.'
def GetLatestReceiptInfo(self):
if ('latest_receipt_info' in self.response): return self.response['latest_receipt_info'] elif ('latest_expired_receipt_info' in self.response): return self.response['latest_expired_receipt_info'] else: return self.response['receipt']
'Returns the bundle id for this subscription. Our bundle id is "co.viewfinder.Viewfinder".'
def GetBundleId(self):
return self.GetLatestReceiptInfo()['bid']
'Returns the product id for this subscription. Product ids are created via itunes connect and encapsulate both a subscription type and a billing cycle (i.e. if we offered 50 and 100GB subscriptions and a choice of monthly and yearly billing, we\'d have four product ids).'
def GetProductId(self):
return self.GetLatestReceiptInfo()['product_id']
'Returns the time at which this transaction occurred.'
def GetTransactionTime(self):
time_ms = int(self.GetLatestReceiptInfo()['purchase_date_ms']) return (float(time_ms) / 1000)
'Returns the expiration time of this subscription. Result is a python timestamp, i.e. floating-point seconds since 1970.'
def GetExpirationTime(self):
expires_ms = int(self.GetLatestReceiptInfo()['expires_date']) return (float(expires_ms) / 1000)
'Returns true if the subscription has expired.'
def IsExpired(self):
return (self.GetExpirationTime() < time.time())
'Returns true if a renewal should be scheduled after expiration.'
def IsRenewable(self):
return (self.response['status'] == 0)
'Returns a blob of receipt data to be used when this subscription is due for renewal. Present only when IsRenewable is true.'
def GetRenewalData(self):
if ('latest_receipt' in self.response): return base64.b64decode(self.response['latest_receipt']) else: return self.orig_receipt
'Returns the original transaction id for a renewing subscription. This id is constant for all renewals of a single subscription.'
def GetOriginalTransactionId(self):
return self.GetLatestReceiptInfo()['original_transaction_id']
'Returns the transaction id for the most recent renewal transaction. Will be equal to self.GetOriginalTransactionId() if no renewals have happened yet.'
def GetRenewalTransactionId(self):
return self.GetLatestReceiptInfo()['transaction_id']
'Verifies a receipt. Callback receives a VerifyResponse.'
def VerifyReceipt(self, receipt_data, callback):
def _OnFetch(response): response.rethrow() callback(VerifyResponse(receipt_data, response.body)) request = {'receipt-data': base64.b64encode(receipt_data), 'password': secrets.GetSecret('itunes_subscription_secret')} self.http_client.fetch(self._settings['verify_url'], method='POST', body=js...
'Sets a new instance for testing.'
@staticmethod def SetInstance(environment, itunes_client):
ITunesStoreClient._instance_map[environment] = itunes_client
'Removes a previously-set instance.'
@staticmethod def ClearInstance(environment):
del ITunesStoreClient._instance_map[environment]
'Resets backoff to \'reconnect_lag\' setting.'
def _ResetBackoff(self):
self._backoff = self._settings.get('reconnect_lag')
'Best guess at whether we\'ve dispatched all work. Due to the lack of response on successful requests, we can\'t actually be 100% sure.'
def IsIdle(self):
return ((len(self._write_queue) == 0) and ((self._stream is None) or (not self._stream.writing())))
'Creates a binary message from input parameters and adds it to the outgoing write queue.'
def Push(self, token, alert=None, badge=None, sound=None, expiry=None, extra=None, timestamp=None):
self._generation.value += 1 identifier = self._generation.value logging.debug(('pushing notification to APNs for token %s, badge %r, alert %s' % (token, badge, alert))) msg = CreateMessage(token, alert=alert, badge=badge, sound=sound, identifier=identifier, expiry=expiry, e...
'On connection, immediately process all enqueued push notifications.'
def _OnConnect(self):
_BaseSSLService._OnConnect(self) self._recent = deque(maxlen=100) self._ready = True while self._PushOne(): pass self._stream.read_bytes(_APNService.MESSAGE_SIZE, self._OnRead)
'If a pushed message is invalid, APNs returns an error message specifying the identifier. The connection is also closed and must be reopened.'
def _OnRead(self, data):
logging.debug(('_OnRead: %d bytes' % len(data))) try: (status, identifier, err_string) = ParseResponse(data) if (status == 0): self._stream.read_bytes(_APNService.MESSAGE_SIZE, self._OnRead) return logging.warning(('error pushing notification: %d ...
'Marks the specified token as bad. The next notification pushed to this token will activate the feedback handler.'
def MarkTokenBad(self, token):
if token.startswith(TestService.PREFIX): token = token[len(TestService.PREFIX):] self._bad_tokens.add(token)
'Returns the list of notifications which have been pushed to this token.'
def GetNotifications(self, token):
return self._notifications.get(token, [])
'If the token is bad, invokes the feedback handler. Otherwise, adds the notification to a list of notifications sent for this token.'
def Push(self, token, alert=None, badge=None, sound=None, expiry=None, extra=None, timestamp=None):
if (token in self._bad_tokens): self._feedback_handler(('%s%s' % (TestService.PREFIX, token)), time.time()) else: msg = {'alert': alert, 'badge': badge, 'sound': sound, 'expiry': expiry, 'extra': extra} if (token not in self._notifications): self._notifications[token] = list(...
'Pushes the notification specified by the supplied parameters to APNs.'
def Push(self, token, alert, badge, sound, expiry, extra, timestamp):
self._apn_service.Push(token, alert, badge, sound, expiry, extra, timestamp)
'Sets a new instance for testing.'
@staticmethod def SetInstance(environment, apns):
APNS._instance_map[environment] = apns
'Verify obviously bad inputs fail.'
@async_test def testInput(self):
self.assertRaises(TypeError, self._apns.Push, '0', None, 1, None, None, None, None) self.stop()
'Sends a bad token to apns and verifies feedback handler.'
@async_test_timeout(timeout=30) def testBadToken(self):
BAD_TOKEN = base64.b64encode(('0' * 32)) self.assertEqual(len(BAD_TOKEN), 44) def _OnFeedback(push_token): self.assertEqual(('apns-dev:%s' % BAD_TOKEN), push_token) self.stop() self._feedback.WaitForFeedback(_OnFeedback) self._apns.Push(BAD_TOKEN, None, 1, None, None, None, None)
'Verify that passing Unicode fields to CreateMessage works.'
def testUnicodeMessage(self):
CreateMessage(u'u1fGNVUPy9ZWquLzCmgBj+11SWbqHqGrICwr7rk+qWE="', alert=u'foo bar\u670b\u53cb\u4f60\u597d\xe0\xe0\xe0', badge=0, sound=u'default', extra={u'foo': u'bar'})
'Verify that long messages are truncated properly.'
def testAlertTruncation(self):
alert = '\xe6\x9c\x8b\xe5\x8f\x8b\xe4\xbd\xa0\xe5\xa5\xbd\xe6\x9c\x8b\xe5\x8f\x8b\xe4\xbd\xa0\xe5\xa5\xbd\xe6\x9c\x8b\xe5\x8f\x8b\xe4\xbd\xa0\xe5\xa5\xbd\xe6\x9c\x8b\xe5\x8f\x8b\xe4\xbd\xa0\xe5\xa5\xbd\xe6\x9c\x8b\xe5\x8f\x8b\xe4\xbd\xa0\xe5\xa5\xbd\xe6\x9c\x8b\xe5\x8f\x8b\xe4\xbd\xa0\xe5\xa5\xbd\xe6\x9c\x8b\xe5\x8...
'Unit test alert truncation.'
def testTruncateAlert(self):
from viewfinder.backend.services.apns_util import _TruncateAlert def _TestTruncate(alert, max_bytes, expected): truncated = _TruncateAlert(alert, max_bytes) truncated_json = escape.utf8(json.dumps(escape.recursive_unicode(truncated), ensure_ascii=False)[1:(-1)]) self.assertEqual(truncate...
'Unit test the sms_util.ForceUnicode function.'
def testForceUnicode(self):
self.assertFalse(ForceUnicode('')) self.assertFalse(ForceUnicode('abcXYZ123')) self.assertFalse(ForceUnicode('\xe6\x9c\x8b\xe6\x9c\x8b\xe6\x9c\x8b')) self.assertFalse(ForceUnicode('1\xe6\x9c\x8b\xc3\xa8\xe6\x9c\x8bA\xe6\x9c\x8b-')) self.assertFalse(ForceUnicode('\xe6\x9c\x8b\xce\xa3')) self.asse...
'Unit test the sms_util.IsOneSMSMessage function.'
def testIsOneSMSMessage(self):
self.assertTrue(IsOneSMSMessage('')) self.assertTrue(IsOneSMSMessage(('a' * MAX_GSM_CHARS))) self.assertFalse(IsOneSMSMessage((('a' * MAX_GSM_CHARS) + 'a'))) self.assertTrue(IsOneSMSMessage(('\xc3\x91' * MAX_GSM_CHARS))) self.assertFalse(IsOneSMSMessage((('\xc3\x91' * MAX_GSM_CHARS) + '\xc3\x91'))) ...
'Test the Twilio API.'
def testTwilioSMSManagerSend(self):
info_dict = {'Body': u'this is a test text \xc9', 'To': '+14251234567', 'From': '+12061234567'} expected_response_dict = {'account_sid': 'ACa437bddda03231c80f4c463dc51513bb', 'api_version': '2010-04-01', 'body': 'Jenny please?! I love you <3', 'date_created': 'Wed, 18 Aug ...
'Test the Twilio SMS Manager http error handling.'
def testTwilioSMSManagerSendError(self):
info_dict = {'Body': 'this is a test text', 'To': '+14251234567', 'From': '+12061234567'} sms = TwilioSMSManager() with mock.patch('tornado.httpclient.AsyncHTTPClient', MockAsyncHTTPClient()) as mock_client: _AddMockJSONResponseError(mock_client, 'https://api.twilio.com/2010-04-01/Accoun...
'Test the Clickatell SMS Manager http error handling.'
def testClickatellSMSManagerSendError(self):
info_dict = {'user': 'viewfinder-dev', 'password': 'SPAMM_5!', 'api_id': '3391545', 'to': '14257502513', 'MO': '1', 'from': '16467361610', 'text': 'this is a test text'} sms = ClickatellSMSManager() with mock.patch('tornado.httpclient.AsyncHTTPClient', MockAsyncHTTPClient()) as mock_client: ...
'Test the Clickatell API.'
def testClickatellSMSManagerSend(self):
info_dict = {'user': 'viewfinder-dev', 'password': 'SPAMM_5!', 'api_id': '3391545', 'to': '14257502513', 'MO': '1', 'from': '16467361610', 'text': 'this is a test text'} expected_response_dict = {'ID': '18af4edb086a15f7904a1584c7960c2a'} sms = ClickatellSMSManager() with mock.patch('tornado....
'Parses push notification scheme from the token prefix and muxes the notification to the appropriate service. The token is in base64 encoding ([a-zA-Z0-9+/=]). To get the default system sound, specify sound=PushNotification.DEFAULT_SOUND.'
@staticmethod def Push(token, alert=None, badge=None, sound=None, expiry=None, extra=None, timestamp=None):
token_re = re.match('(apns|gcm)-(test|dev|ent|prod):([a-zA-Z0-9+/=]+)$', token) if (not token_re): raise TypeError(('invalid token: %s' % token)) scheme = token_re.group(1) environment = token_re.group(2) push_token = token_re.group(3) if (scheme == 'apns'): APNS.Instance(e...
'Sets a new instance for testing.'
@staticmethod def SetInstance(sms_mgr):
SMSManager._instance = sms_mgr
'Sends an SMS message through the SMS gateway to \'number\' with the specified \'text\' content.'
@gen.coroutine def SendSMS(self, description=None, **kwargs):
number = kwargs['number'] text = kwargs['text'] self._ValidateArgs(number, text) args = {'Body': escape.utf8(text), 'To': number, 'From': self._api_number} http_client = httpclient.AsyncHTTPClient() response = (yield gen.Task(http_client.fetch, self._sms_gateway_api_url, method='POST', body=urll...
'Sends an SMS message through the SMS gateway to \'number\' withe specified \'text\' content.'
@gen.coroutine def SendSMS(self, description=None, **kwargs):
number = kwargs['number'] text = kwargs['text'] self._ValidateArgs(number, text) args = {'user': self._api_user, 'password': self._api_password, 'api_id': self._api_id, 'to': number, 'MO': '1', 'from': self._api_number, 'text': escape.utf8(text)} http_client = httpclient.AsyncHTTPClient() respon...
'If logged in, redirect to /view. Otherwise, render index.html content.'
def get(self):
cur_user = self.get_current_user() if ((cur_user is not None) and cur_user.IsRegistered()): self.redirect('/view') else: self.render('square.html')
'Returns a simple JSON report of the health of the cluster. This will be a simple status message of \'OK\' unless there are active alerts on the cluster. An example of an alerting status message: \'status\': \'ALERT\', \'alerts\': [ {\'name\': \'Alert1\', \'count\': 1, \'cluster\': False, \'description\': \'Alert des...
@handler.asynchronous(datastore=True) def get(self):
cluster = metric.DEFAULT_CLUSTER_NAME interval = metric.METRIC_INTERVALS[0] now = time.time() def _OnGetHealthReport(report): expiration = ((report.timestamp + interval.length) + self.COLLECTION_DELAY) cached = self._CachedReport(report, expiration) self._cachedReports[cluster] =...
'Returns true if the given viewpoint can be accessed by the current user.'
def CanViewViewpoint(self, viewpoint_id):
return ((self.viewpoint_id is None) or (self.viewpoint_id == viewpoint_id))
'Returns true if the current user session has a confirmed cookie.'
def IsConfirmedUser(self):
return www_util.IsConfirmedCookie(self.confirm_time)
'Returns true if the caller is a mobile client (as opposed to the web client).'
def IsMobileClient(self):
assert ((self.device_id is not None) and (self.user is not None)) return (self.device_id != self.user.webapp_dev_id)
'Creates a user cookie dict from the given arguments.'
def CreateUserCookieDict(self, user_id, device_id, user_name=None, viewpoint_id=None, confirm_time=None, is_session_cookie=None):
user_dict = {'user_id': user_id, 'device_id': device_id, 'server_version': self.settings['server_version']} util.SetIfNotNone(user_dict, 'name', user_name) util.SetIfNotNone(user_dict, 'viewpoint_id', viewpoint_id) util.SetIfNotNone(user_dict, 'confirm_time', confirm_time) util.SetIfNotNone(user_dic...
'Creates a secure user cookie, indicating that this user is now logged in. The cookie is a signed, json-encoded dict (obtained from CreateUserCookieDict). It can be read using GetUserCookie(). If the "is_session_cookie" field is True, then the cookie will typically expire once the user closes the browser. This is used ...
def SetUserCookie(self, user_cookie_dict):
expires_days = (None if user_cookie_dict.get('is_session_cookie', False) else _USER_COOKIE_EXPIRES_DAYS) self.set_secure_cookie(_USER_COOKIE_NAME, json.dumps(user_cookie_dict), expires_days=expires_days)
'Returns a dictionary of user attributes from the request headers. The cookie value is decrypted and json-decoded. To be valid, it must contain a \'user_id\' and have a server version with a major version number equal to the major version number of the current server.'
def GetUserCookie(self):
user_cookie = self.get_secure_cookie(_USER_COOKIE_NAME, max_age_days=_USER_COOKIE_EXPIRES_DAYS) if user_cookie: try: user_dict = json.loads(user_cookie) except ValueError: logging.warning(('user cookie is not valid JSON: %s' % user_cookie)) s...
'Clears the user cookie.'
def ClearUserCookie(self):
self.clear_cookie(_USER_COOKIE_NAME)
'Log in with the given user and cookie by setting up the current context and setting the user cookie (if "set_cookie" is true).'
def LoginUser(self, user, user_cookie, set_cookie=True):
self._current_user = user context = ViewfinderContext.current() context.user = user context.device_id = user_cookie['device_id'] context.viewpoint_id = user_cookie.get('viewpoint_id', None) context.confirm_time = user_cookie.get('confirm_time', None) if set_cookie: self.SetUserCookie...
'Returns the user db object that was set by the \'_execute\' method if the user cookie was found.'
def get_current_user(self):
return self._current_user
'Override base set_cookie to default secure and httponly to true. "secure" means HTTPS-only; "httponly" means the cookie is not accessible to javascript; "domain" allows cookie to be used with any first-level sub-domain.'
def set_cookie(self, *args, **kwargs):
kwargs.setdefault('secure', True) kwargs.setdefault('httponly', True) assert ('.' in options.options.domain), options.options.domain kwargs.setdefault('domain', ('.%s' % options.options.domain)) super(BaseHandler, self).set_cookie(*args, **kwargs)
'Override base clear_cookie to set a domain. Necessary because the base implementation of clear_cookie sets the domain to None, which conflicts with the usage of setdefault in BaseHandler.set_cookie.'
def clear_cookie(self, *args, **kwargs):
assert ('.' in options.options.domain), options.options.domain kwargs.setdefault('domain', ('.%s' % options.options.domain)) super(BaseHandler, self).clear_cookie(*args, **kwargs)
'Override default xsrf_token implementation to always use persistent cookies with the same duration as our user cookies.'
@property def xsrf_token(self):
if (not hasattr(self, '_xsrf_token')): token = self.get_cookie('_xsrf') if (not token): token = binascii.b2a_hex(uuid.uuid4().bytes) expires_days = _USER_COOKIE_EXPIRES_DAYS self.set_cookie('_xsrf', token, expires_days=expires_days) self._xsrf_token = toke...
'Checks for logout argument and clears cookie if it is present.'
def prepare(self):
self.set_header('X-Frame-Options', 'SAMEORIGIN')
'Handles presentation of an exception condition to the user, either as an HTML error page, or as a JSON error response.'
def _handle_request_exception(self, e):
try: (status, message) = www_util.HTTPInfoFromException(e) self.set_status(status) if self._IsInteractiveRequest(): title = 'Unknown Error' if (status == 500): logging.error(('failure processing %s' % getattr(self, 'api_name', None)), exc_info...
'If a user cookie is present, looks up the corresponding user object and stores it in the ViewfinderContext, along with the device_id and viewpoint_id fields of the cookie. The context is available for the execution of this request and can be retrieved by invoking the ViewfinderContext.current() method.'
def _execute(self, transforms, *args, **kwargs):
@gen.engine def _ExecuteTarget(): 'Invoked in the scope of a ViewfinderContext instance.' try: ViewfinderContext.current().connection_close_event = self._connection_close_event self._current_user = None self._transforms = transforms ...
'Returns true if this a user-level interactive request. In this case, any error should be returned as an HTML page rather than as a JSON error response.'
def _IsInteractiveRequest(self):
return (self.request.method in ['GET', 'HEAD'])
'This contains logic for potentially redirecting requests between production and staging clusters. True is returned if redirection was done. False is returned if the request processing should continue onto next step.'
def _MaybeRedirect(self):
if (self._current_user is None): return False elif ((not self._current_user.IsStaging()) and environ.ServerEnvironment.IsStaging()): redirect_host = environ.ServerEnvironment.GetRedirectHost() self.set_header('X-VF-Staging-Redirect', redirect_host) self.redirect(('%s://%s%s' % (s...
'If a user cookie exists, validates the cookie and then looks up the user id contained in that cookie. Returns the tuple (user_cookie, user), where both fields are None if the cookie doesn\'t exist or isn\'t valid.'
@gen.coroutine def _ProcessCookie(self, client):
def _ClearCookie(reason): 'Clear an invalid cookie and log the reason.' logging.warning(('found invalid cookie (%s): %s' % (reason, user_cookie_dict))) self.clear_cookie(_USER_COOKIE_NAME) raise gen.Return((None, None)) user_cookie_dict = self.Get...
'Returns the full name of the current user. If the user exists, but his/her name is not known, returns the user\'s email address. If the email address is not known, returns "Unknown". If no user is logged in, returns None.'
def _GetCurrentUserName(self):
cur_user = self.get_current_user() if (cur_user is None): return None if cur_user.name: return cur_user.name if cur_user.email: return cur_user.email return 'Unknown'
'Parse the request body as json (optionally gzipped). Returns the parsed object if successful; if unsuccessful may either write an error response and return None (in which case the caller should simply return immediately) or pass the exception through to the caller.'
def _LoadJSONRequest(self):
content_type = self.request.headers.get('Content-Type', '') if (not content_type.startswith('application/json')): self.send_error(status_code=415) return None content_encoding = self.request.headers.get('Content-Encoding') if (not content_encoding): request_body = self.request.bo...
'Validate the JSON request message according to the specified JSON schema, and then migrate the message from its original version to the latest version understood by the server. Reject any request with a version that does not meet the minimum required version. Reject any request with a version that exceeds the maximum ...
@staticmethod def _CreateRequestMessage(client, request, request_schema, callback, migrators=None, min_supported_version=message.MIN_SUPPORTED_MESSAGE_VERSION, max_supported_version=message.MAX_SUPPORTED_MESSAGE_VERSION):
def _OnMigrate(request_message): request_message.Validate(request_schema, allow_extra_fields=False) request_message.dict['headers']['original_version'] = request_message.original_version callback(request_message) request_message = message.Message(request, min_supported_version=min_suppor...
'Validate the fields of the response according to the specified JSON schema, sanitize the response, and then migrate the message from the message version currently in use by the server to the specified response version. Return the created message.'
@staticmethod def _CreateResponseMessage(client, response_dict, response_schema, response_version, callback, migrators=None):
if (not response_dict.has_key('headers')): response_dict['headers'] = dict(version=message.MAX_MESSAGE_VERSION) else: response_dict['headers']['version'] = message.MAX_MESSAGE_VERSION response_message = message.Message(response_dict) response_message.Validate(response_schema, allow_extra...
'Log count of healthz requests every _REPORT_INTERVAL_SECS.'
def log(self, path, status, base_log_func):
if (status not in (200, 304)): return base_log_func() now = time.time() if (now >= self._next_interval): for (path, count) in self._request_map.items(): logging.info(('received %d request(s) for %s since last log' % (count, path))) self._request_m...
'For admin pages, we require a a login url which prompts for username, password and OTP entry. Specify this in application setting \'admin_login_url\' to point at OTPEntryHandler instance.'
def get_login_url(self):
self.require_setting('admin_login_url', '@handler.authenticated') return self.application.settings['admin_login_url']
'Looks for and parses the admin_otp cookie. If present, it should contain a json list of auth user and expiration time. The expiration time is verified; if not expired, the user is returned. Otherwise, returns None.'
def get_current_user(self):
admin_cookie = self.get_secure_cookie(COOKIE_NAME) try: if admin_cookie: try: (user, expires) = json.loads(admin_cookie) except ValueError: self.clear_cookie(COOKIE_NAME) return None if (expires > time.time()): ...
'Enforces \'https\' and handles logout argument. Also sets self._loader to the template loader initialized in application setup.'
def prepare(self):
web.RequestHandler.prepare(self) if ((not (self.request.protocol == 'https')) and (BasicAuthHandler._HTTP_TEST_CASE == False)): logging.error('access to basic auth only available via https; specify --xheaders=False if this server is not in production') ...
'Override base set_secure_cookie to default secure and httponly to true. "secure" means HTTPS-only; "httponly" means the cookie is not accessible to javascript.'
def set_secure_cookie(self, *args, **kwargs):
if (not BasicAuthHandler._HTTP_TEST_CASE): kwargs.setdefault('secure', True) kwargs.setdefault('httponly', True) super(BasicAuthHandler, self).set_secure_cookie(*args, **kwargs)
'Currently includes all JS files used by view module.'
def javascript_files(self):
resourceManager = ResourcesManager.Instance() return (resourceManager.GetAssetPaths('view_js') + resourceManager.GetAssetPaths('auth_js'))
'Verifies user credentials and then redirects to the URL where the actual image bits are stored.'
@handler.asynchronous(datastore=True, obj_store=True) @gen.engine def get(self, episode_id, photo_id, suffix):
url = (yield PhotoStoreHandler.GetPhotoUrl(self._client, self._obj_store, episode_id, photo_id, suffix)) self.redirect(url)
'Verifies user credentials. If the user has write access to the photo, and if an \'If-None-Match\' is present, sends a HEAD request to the object store to determine asset Etag. If the Etag matches, returns a 304. Otherwise, generates an upload URL and redirects.'
@handler.asynchronous(datastore=True, obj_store=True) @gen.engine def put(self, episode_id, photo_id, suffix):
def _GetUploadUrl(photo, verified_md5): content_type = (photo.content_type or 'image/jpeg') return self._obj_store.GenerateUploadUrl((photo_id + suffix), content_type=content_type, content_md5=verified_md5) if ('Content-MD5' not in self.request.headers): raise web.HTTPError(400, 'Missing...