desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Checks that the current user (in Viewfinder context) is authorized to get the specified photo, and returns a signed S3 URL for the photo if so.'
@classmethod @gen.coroutine def GetPhotoUrl(cls, client, obj_store, episode_id, photo_id, suffix):
(yield gen.Task(PhotoStoreHandler._AuthorizeUser, client, episode_id, photo_id, write_access=False)) raise gen.Return(GeneratePhotoUrl(obj_store, photo_id, suffix))
'Checks that the current user (in Viewfinder context) user is authorized to access the given photo: 1. The photo must exist, and be in the given episode 2. The photo must not be unshared 3. If uploading the photo, the user must be the episode owner 4. A prospective user has access only to photos in the viewpoint specif...
@classmethod @gen.coroutine def _AuthorizeUser(cls, client, episode_id, photo_id, write_access):
context = base.ViewfinderContext.current() if ((context is None) or (context.user is None)): raise web.HTTPError(401, 'You are not logged in. Only users that have logged in can access this URL.') user_id = context.user.user_id post_id = Post.ConstructPos...
'Always returns false, as this API is accessed programatically.'
def _IsInteractiveRequest(self):
return False
'Parses the JSON request body, validates it, and invokes the method as specified in the request URI. On completion, the response is returned as a JSON-encoded HTTP response body.'
@handler.authenticated(allow_prospective=True) @handler.asynchronous(datastore=True, obj_store=True) def post(self, method_name):
def _OnSuccess(method, start_time, user, device_id, response_dict): self.set_status(200) self.set_header('Content-Type', 'application/json; charset=UTF-8') self.write(json.dumps(response_dict)) request_time = (time.time() - start_time) _avg_req_time.add(request_time) ...
'Need to override to increment _fail_per_min counter.'
def _handle_request_exception(self, e):
_fail_per_min.increment() super(ServiceHandler, self)._handle_request_exception(e)
'Validates the JSON request body and invokes the method as specified in the request URI. On completion, the response is returned as a JSON-encoded response dictionary.'
@staticmethod @gen.coroutine def InvokeService(client, obj_store, method_name, user_id, device_id, json_request):
method = ServiceHandler.SERVICE_MAP[method_name] if ((not base.ViewfinderContext.current().user.IsRegistered()) and (not method.allow_prospective)): raise web.HTTPError(403, 'Permission denied; user account is not registered.') try: request_message = (yield gen.Task(base.Ba...
'Invoked when a user follows a prospective user invitation URL. Sets a prospective user cookie that identifies the user and restricts access to a single viewpoint. Typically redirects the user to the corresponding website conversation page.'
@gen.engine def _HandleGet(self, short_url, identity_key, viewpoint_id, default_url, is_sms=False, is_first_click=True):
identity = (yield gen.Task(Identity.Query, self._client, identity_key, None, must_exist=False)) if ((identity is None) or (identity.user_id is None)): raise ExpiredError('The requested link has expired and can no longer be used.') next_url = self.get_argument('next', de...
'Validates the request using the specified schema, and saves the message object as self._request_message. A call to this method is matched by a later call to _FinishJSONRequest.'
@gen.coroutine def _StartJSONRequest(self, action, request, schema, migrators=None):
try: self.api_name = action self._action = action self._request_message = (yield gen.Task(base.BaseHandler._CreateRequestMessage, self._client, self._LoadJSONRequest(), schema, migrators=migrators)) except Exception as e: logging.warning(('invalid authentication request:\n%...
'Finishes an authentication request by a mobile client and sends back the specified response as JSON.'
@gen.engine def _FinishJSONRequest(self, op, response_dict, schema):
if (op is not None): scratch_response_dict = deepcopy(response_dict) scratch_response_dict['headers'] = {'op_id': op.operation_id, 'op_timestamp': op.timestamp} else: scratch_response_dict = response_dict self.set_header('Content-Type', 'application/json; charset=UTF-8') respo...
'Called when an interactive requester has started the authentication process. Enables HTML exceptions.'
def _StartInteractiveRequest(self, action):
self._action = action
'Called when an interactive requester has been authenticated as a Viewfinder user. Sets the user cookie and redirects the user to either the original URL that was requested, or to the user\'s photo view.'
def _FinishInteractiveRequest(self):
next = self.get_argument('next', None) if (next is not None): self.redirect(next) else: self.redirect('/view')
'Validates incoming user, identity, and device information in preparation for login, register, or link action. Derives user id and name and sets them into the user dict.'
@gen.coroutine def _PrepareAuthUser(self, user_dict, ident_dict, device_dict):
ident_dict['json_attrs'] = user_dict identity = (yield gen.Task(Identity.Query, self._client, ident_dict['key'], None, must_exist=False)) current_user = self.get_current_user() if (self._action in ['login', 'login_reset']): if ((identity is not None) and (identity.user_id is not None)): ...
'Called when a requester has been authenticated as a Viewfinder user by a trusted authority that provides additional information about the user, such as name, email, gender, etc. At this point, we can trust that the identity key provided in "ident_dict" is controlled by the calling user. Completes the authentication ac...
@gen.engine def _AuthUser(self, user_dict, ident_dict, device_dict, confirmed=False):
before_user = (yield gen.Task(self._PrepareAuthUser, user_dict, ident_dict, device_dict)) scratch_user_dict = {'user_id': user_dict['user_id']} for (k, v) in user_dict.items(): user_key = AuthHandler._AUTH_ATTRIBUTE_MAP.get(k, None) if (user_key is not None): if (getattr(before_u...
'Responds to a single request for performance counter data. Each request has two required parameters in the query string, \'start\' and \'end\', which specify the beginning and end of the time range to be queried. The times should be expressed as the number of seconds since the unix epoch.'
@handler.authenticated() @handler.asynchronous(datastore=True) @admin.require_permission(level='root') def get(self):
def _OnAggregation(aggregator): self.set_header('Content-Type', 'application/json; charset=UTF-8') self.write(json.dumps(aggregator, default=_SerializeAggregateMetrics)) self.finish() start_time = float(self.get_argument('start')) end_time = float(self.get_argument('end')) int...
'Does a table scan. Invokes \'callback with (items, total_count, last_key).'
@gen.engine def _ScanData(self, table, limit, excl_start_key, callback):
description = (yield gen.Task(self._client.DescribeTable, table=table.name)) scan_results = (yield gen.Task(self._client.Scan, table=table.name, attributes=[c.key for c in table.GetColumns()], limit=limit, excl_start_key=excl_start_key)) callback(scan_results.items, description.count, scan_results.last_key)...
'Does a range query using hash key.'
@gen.engine def _QueryData(self, table, hash_key, range_operator, limit, excl_start_key, callback, reverse):
query = (yield gen.Task(self._client.Query, table=table.name, hash_key=hash_key, range_operator=range_operator, attributes=[c.key for c in table.GetColumns()], limit=limit, excl_start_key=excl_start_key, scan_forward=(not reverse))) count = (yield gen.Task(self._client.Query, table=table.name, hash_key=hash_key...
'Fetch a single entry.'
@gen.engine def _GetData(self, table, hash_key, range_key, callback):
item = (yield gen.Task(self._client.GetItem, table=table.name, key=db_client.DBKey(hash_key, range_key), attributes=[c.key for c in table.GetColumns()], must_exist=False)) if (item is None): callback([], 0, None) else: callback([item.attributes], 1, None)
'Returns the table handler for \'table_name\', if specified in the _TABLE_FORMATTERS map. If none is specified in the map, return the default.'
def _GetTableFormatter(self, table_name):
return DBDataHandler._TABLE_FORMATTERS.get(table_name, formatters.FmtDefault)
'Returns a json-encoded list of auth user and expiration time.'
@classmethod def _CreateCookie(cls, user, timestamp):
return json.dumps((user, (long(timestamp) + basic_auth.COOKIE_EXPIRATION)))
'Validates username / password in conjunction with OTP entry. Returns otp_admin cookie value on success.'
@classmethod def _ValidateCredentials(cls, user, pwd, otp_entry):
otp.VerifyPassword(user, pwd) otp.VerifyOTP(user, otp_entry) return OTPEntryHandler._CreateCookie(user, time.time())
'Writes the template for OTP entry form with this URI as the action.'
def get(self):
self.render('otp.html', uri=self.request.uri, msg=self.get_argument('msg', ''), auth_credentials=self._auth_credentials)
'Verifies the OTP parameter of the POST. On success, sends the user a secure expiration cookie and redirects to the original page. On failure, shows login again with error msg.'
def post(self):
FORM_TYPE = 'application/x-www-form-urlencoded' JSON_TYPE = 'application/json' if self.request.headers['Content-Type'].startswith(FORM_TYPE): try: user = self.get_argument('username', '') pwd = self.get_argument('password', '') otp_entry = self.get_argument('otp',...
'Parses the JSON request body, validates it, and invokes the method as specified in the request URI. On completion, the response is returned as a JSON-encoded HTTP response body.'
@handler.authenticated() @handler.asynchronous(datastore=True, obj_store=True) def post(self, method_name):
def _OnSuccess(method, start_time, response_dict): validictory.validate(response_dict, method.response) self.set_status(200) self.set_header('Content-Type', 'application/json; charset=UTF-8') self.write(response_dict) request_time = (time.time() - start_time) loggi...
'Returns a cookie name, which is currently based on the base class type name.'
def _GetCookieName(self):
return (type(self).__name__ + '_last_key')
'Formats the request data received from jQuery data table. The \'table_name\' parameter is required if a single handler can query more than one data table.'
def ReadTablePageRequest(self, table_name, op_type=None):
requested_start = int(self.get_argument('iDisplayStart')) requested_length = int(self.get_argument('iDisplayLength')) s_echo = self.get_argument('sEcho') cookie = self.get_secure_cookie(self._GetCookieName()) try: (last_table, op_type, last_index, last_key) = json.loads(cookie) if ((...
'Writes the appropriate json response and tracking cookie.'
def WriteTablePageResponse(self, rows, last_key, table_count=None):
req = self._table_request last_index = (req.start + len(rows)) if table_count: table_count = max(table_count, last_index) elif (len(rows) == req.length): table_count = (last_index + 1) else: table_count = last_index json_dict = {'sEcho': int(req.echo), 'iDisplayStart': re...
'Check whether the permissions object has a ROOT rights entry.'
def CheckIsRoot(self):
if (not self._permissions.IsRoot()): raise web.HTTPError(httplib.FORBIDDEN, ('User %s does not have root credentials.' % self._auth_credentials))
'Check whether the permissions object has a SUPPORT rights entry. Root users do not automatically get granted support rights.'
def CheckIsSupport(self):
if (not self._permissions.IsSupport()): raise web.HTTPError(httplib.FORBIDDEN, ('User %s does not have support credentials.' % self._auth_credentials))
'Dict of variables used in all admin templates.'
def PermissionsTemplateDict(self):
return {'auth_credentials': self._auth_credentials, 'is_root': self._permissions.IsRoot(), 'is_support': self._permissions.IsSupport()}
'Get set of permissions for user. Raise an error if the user does not have an entry, of if the set of rights is empty.'
@gen.engine def QueryAdminPermissions(self, callback):
permissions = (yield gen.Task(AdminPermissions.Query, self._client, self._auth_credentials, None, must_exist=False)) if ((permissions is None) or (not permissions.rights)): raise web.HTTPError(httplib.FORBIDDEN, ('User %s has no credentials.' % self._auth_credentials)) callback(permissio...
'Handles presentation of an exception condition to the admin.'
def _handle_request_exception(self, value):
logging.exception('error in admin page') self.render('admin_error.html', auth_credentials=self._auth_credentials, is_root=False, is_support=False, title=value, message=traceback.format_exc()) return True
'Responds to a single request for performance counter data. Each request has two required parameters in the query string, \'start\' and \'end\', which specify the beginning and end of the time range to be queried. The times should be expressed as the number of seconds since the unix epoch.'
@handler.authenticated() @handler.asynchronous(datastore=True) @admin.require_permission(level='support') @gen.engine def get(self):
start_time = float(self.get_argument('start')) end_time = float(self.get_argument('end')) selected_interval = metric.LOGS_INTERVALS[(-1)] group_key = metric.Metric.EncodeGroupKey(metric.LOGS_STATS_NAME, selected_interval) logging.info(('Query performance counters %s, range: %s - ...
'Returns an array of item attributes, one per column in the table definition, formatted for display in HTML table.'
def FormatItemAttributes(self, item):
attributes = self._FormatAllAttributes(item) rows = [pretty for (_, _, _, pretty) in attributes] return rows
'Return an array of rows. Each row consists of "column name", "key", "value".'
def FormatItemAttributesForView(self, item):
attributes = self._FormatAllAttributes(item) rows = [(name, key, pretty) for (name, key, _, pretty) in attributes] rows.extend(self._GetExtraViewFields(item)) return rows
'Class used to append new fields in per-object view. Nothing by default. Must be a list of (name, key, pretty).'
def _GetExtraViewFields(self, item):
return []
'Builds a query link for a hash_key and sort_key. Sort key operator is \'EQ\'.'
@staticmethod def _SortQueryLink(table, hash_key, sort_key, name=None):
return ('<a href="/admin/db?table=%s&type=query&hash_key=%s&sort_key=%s&sort_desc=EQ">%s</a>' % (FmtDefault._Escape(table), FmtDefault._Escape(hash_key), FmtDefault._Escape(sort_key), FmtDefault._XEscape((name if (name is not None) else ('%s:%s' % (hash_key, sort_key))))))
'Build list of (column, key, value, pretty_value). We need a list to keep the columns ordered.'
def _FormatAllAttributes(self, item):
attrs = [] for name in self._table.GetColumnNames(): c = self._table.GetColumn(name) value = item.get(c.key, None) pretty = (self._FormatAttribute(name, value) if (value is not None) else '-') attrs.append((name, c.key, value, pretty)) return attrs
'Returns the attribute value; If none, returns \'-\'. Formats by default the following fields: \'viewpoint_id\', \'episode_id\', \'photo_id\', \'timestamp\', \'Location\', \'Placemark\'.'
def _FormatAttribute(self, name, value):
if ((name == 'viewpoint_id') or (name == 'private_vp_id')): (did, (vid, sid)) = Viewpoint.DeconstructViewpointId(value) pretty = ('%s/%d/%d' % (value, did, vid)) return FmtDefault._ViewpointLink(value, pretty) elif ((name == 'user_id') or (name == 'sender_id')): return self._User...
'Formats a timestamp (in UTC) via default format.'
def _FormatTimestamp(self, timestamp):
return self._XEscape(time.asctime(time.gmtime(timestamp)))
'Returns a URL to display a DB query of the table using hash key \'hash_key\'.'
def _GetQueryURL(self, table, hash_key):
return ('/admin/db?table=%s&type=query&hash_key=%s' % (self._Escape(table), self._Escape(repr(hash_key))))
'Build list of (column, key, value, pretty_value). We need a list to keep the columns ordered. The interpretation of the \'key\' column depends on the beginning of the \'term\' column.'
def _FormatAllAttributes(self, item):
attrs = [] term = item.get('t', None) key = item.get('k', None) data = item.get('d', None) split = term.split(':') table = split[0] key_pretty = key if (table == 'co'): db_key = Contact._ParseIndexKey(key) key_pretty = self._SortQueryLink('Contact', db_key.hash_key, db_ke...
'Formats \'expiration\' as human readable date/times.'
def _FormatAttribute(self, name, value):
if (name == 'expiration'): if (value < time.time()): return '<i>Expired</i>' else: return self._FormatTimestamp(value) else: return FmtDefault._FormatAttribute(self, name, value)
'Formats \'timestamp\' as human readable date/time, {\'json\', \'first_exception\', \'last_exception\'} as <pre/> blocks for readability.'
def _FormatAttribute(self, name, value):
if (name in ('json', 'first_exception', 'last_exception')): return ('<pre>%s</pre>' % self._XEscape(value)) elif (name == 'backoff'): if (value < time.time()): return '<i>Expired</i>' else: return self._FormatTimestamp(value) else: return FmtDefault._F...
'Validates the request and prepares to authenticate by creating user, identity, and device dicts. Returns a tuple of (user_dict, ident_dict, device_dict).'
@gen.coroutine def _StartAuthViewfinder(self, action):
if (action == 'register'): schema = json_schema.REGISTER_VIEWFINDER_REQUEST elif (action == 'login'): schema = json_schema.LOGIN_VIEWFINDER_REQUEST else: schema = json_schema.AUTH_VIEWFINDER_REQUEST if (action == 'register'): migrators = _REQUEST_MIGRATORS else: ...
'Finishes the Viewfinder auth response, passing back the number of digits used in the access token.'
def _FinishAuthViewfinder(self, identity_key):
(identity_type, identity_value) = Identity.SplitKey(identity_key) (num_digits, good_for) = Identity.GetAccessTokenSettings(identity_type, self._UseShortToken()) self._FinishJSONRequest(None, {'token_digits': num_digits}, json_schema.AUTH_VIEWFINDER_RESPONSE)
'Sends an identity verification email or SMS message in order to verify that the user controls the identity.'
@gen.coroutine def _SendVerifyIdMessage(self, user_id, user_name, user_dict, ident_dict, device_dict):
(yield VerifyIdBaseHandler.SendVerifyIdMessage(self._client, self._action, use_short_token=self._UseShortToken(), is_mobile_app=(device_dict is not None), identity_key=ident_dict['key'], user_id=user_id, user_name=user_name, user_dict=user_dict, ident_dict=ident_dict, device_dict=device_dict))
'Validates that the identity key is in canonical format, and that it\'s either an Email or a Phone identity. Returns a tuple containing: (identity_type, identity_value).'
@classmethod def _ValidateIdentityKey(cls, identity_key):
Identity.ValidateKey(identity_key) (identity_type, identity_value) = Identity.SplitKey(identity_key) if (identity_type not in ['Email', 'Phone']): raise web.HTTPError(400, (_IDENTITY_NOT_SUPPORTED % identity_key)) return (identity_type, identity_value)
'Returns true if an auth email should directly in-line a short 4-digit access token so that the user can manually type it into the mobile or web client.'
def _UseShortToken(self):
return ((self._request_message is not None) and (self._request_message.original_version >= message.Message.SEND_EMAIL_TOKEN))
'POST is used when authenticating via the mobile application.'
@handler.asynchronous(datastore=True) @gen.engine def post(self):
(user_dict, ident_dict, device_dict) = (yield gen.Task(self._StartAuthViewfinder, 'register')) identity = (yield gen.Task(Identity.Query, self._client, ident_dict['key'], None)) context = base.ViewfinderContext.current() if ((context.user is not None) and (context.user.user_id == identity.user_id) and c...
'Invoked by VerifyViewfinderHandler to complete the register action.'
@classmethod def _Finish(cls, handler, client, user_dict, ident_dict, device_dict):
handler._AuthUser(user_dict, ident_dict, device_dict, confirmed=True)
'POST is used when authenticating via the mobile application.'
@handler.asynchronous(datastore=True) @gen.engine def post(self):
(user_dict, ident_dict, device_dict) = (yield gen.Task(self._StartAuthViewfinder, 'login')) user = (yield gen.Task(User.Query, self._client, user_dict['user_id'], None)) password = self._request_message.dict['auth_info'].get('password', None) if (password is not None): (yield password_util.Valid...
'Invoked by VerifyViewfinderHandler to complete the login action.'
@classmethod def _Finish(cls, handler, client, user_dict, ident_dict, device_dict):
handler._AuthUser(user_dict, ident_dict, device_dict, confirmed=True)
'POST is used when authenticating via the mobile application.'
@handler.asynchronous(datastore=True) @gen.engine def post(self):
(user_dict, ident_dict, device_dict) = (yield gen.Task(self._StartAuthViewfinder, 'login_reset')) user = (yield gen.Task(User.Query, self._client, user_dict['user_id'], None)) (yield self._SendVerifyIdMessage(user.user_id, user.name, user_dict, ident_dict, device_dict)) self._FinishAuthViewfinder(ident_...
'Invoked by VerifyViewfinderHandler to complete the login action.'
@classmethod def _Finish(cls, handler, client, user_dict, ident_dict, device_dict):
handler._AuthUser(user_dict, ident_dict, device_dict, confirmed=True)
'POST is used when authenticating via the mobile application.'
@handler.asynchronous(datastore=True) @gen.engine def post(self):
(yield gen.Task(self._StartJSONRequest, 'merge_token', self.request, json_schema.MERGE_TOKEN_REQUEST, migrators=_REQUEST_MIGRATORS)) identity_key = self._request_message.dict['identity'] AuthViewfinderHandler._ValidateIdentityKey(identity_key) context = ViewfinderContext.current() if (context.user i...
'POST is used when authenticating via the mobile application.'
@handler.asynchronous(datastore=True) @gen.engine def post(self):
(user_dict, ident_dict, device_dict) = (yield gen.Task(self._StartAuthViewfinder, 'link')) current_user = self.get_current_user() (yield self._SendVerifyIdMessage(current_user.user_id, current_user.name, user_dict, ident_dict, device_dict)) self._FinishAuthViewfinder(ident_dict['key'])
'Invoked by VerifyViewfinderHandler to complete the link action.'
@classmethod def _Finish(cls, handler, client, user_dict, ident_dict, device_dict):
handler._AuthUser(user_dict, ident_dict, device_dict)
'Sends a verification email or SMS message to the given identity. This message may directly contain an access code (e.g. if an SMS is sent), or it may contain a ShortURL link to a page which reveals the access code (e.g. if email was triggered by the mobile app). Or it may contain a link to a page which confirms the us...
@classmethod @gen.coroutine def SendVerifyIdMessage(cls, client, action, use_short_token, is_mobile_app, identity_key, user_id, user_name, **kwargs):
identity = (yield gen.Task(Identity.Query, client, identity_key, None, must_exist=False)) if (identity is None): identity = Identity.CreateFromKeywords(key=identity_key) (yield gen.Task(identity.Update, client)) (identity_type, identity_value) = Identity.SplitKey(identity.key) message_ty...
'Returns a dict of parameters that will be passed to EmailManager.SendEmail in order to email an access token to a user who is verifying his/her account.'
@classmethod def _GetAuthEmail(cls, client, action, use_short_token, user_name, identity, short_url):
action_info = VerifyIdBaseHandler.ACTION_MAP[action] (identity_type, identity_value) = Identity.SplitKey(identity.key) args = {'from': EmailManager.Instance().GetInfoAddress(), 'fromname': 'Viewfinder', 'to': identity_value} util.SetIfNotNone(args, 'toname', user_name) fmt_args = {'user_name': (user...
'Returns a dict of parameters that will be passed to SMSManager.SendSMS in order to text an access token to a user who is verifying his/her account.'
@classmethod def _GetAccessTokenSms(cls, identity):
(identity_type, identity_value) = Identity.SplitKey(identity.key) return {'number': identity_value, 'text': ('Viewfinder code: %s' % identity.access_token)}
'This handler is invoked in two cases: 1. The user clicks a ShortURL link in a verification email that was sent to them. In this case, we return a page that tries to redirect to the mobile app in order to provide it the access code. 2. Once the redirect has been attempted, the page calls here with a redirected=True que...
@gen.engine def _HandleGet(self, short_url, action, identity_key, user_name, access_token, **kwargs):
action_info = VerifyIdBaseHandler.ACTION_MAP[action] identity = (yield gen.Task(Identity.Query, self._client, identity_key, None)) redirected = (self.get_argument('redirected', None) == 'True') if (not redirected): try: (yield identity.VerifyAccessToken(self._client, access_token)) ...
'This handler is invoked when the user clicks a ShortURL link in a verification email that was sent to them. Returns a page that guides the user through the completion of the operation.'
@gen.engine def _HandleGet(self, short_url, action, identity_key, user_name, access_token, **kwargs):
identity = (yield gen.Task(Identity.Query, self._client, identity_key, None)) try: (yield identity.VerifyAccessToken(self._client, identity.access_token)) except Exception as ex: logging.info('error during access token verification: %s', ex) raise ExpiredError(EXPIRED_...
'Used by the auth.html page to validate the user\'s password as part of the registration completion process. This is necessary if the user clicks the email verification link on a machine that was different than the one that sent the email in the first place. In the case of register, the password sent in the POST body i...
@gen.engine def _HandlePost(self, short_url, action, identity_key, user_name, access_token, **kwargs):
(yield gen.Task(self._StartJSONRequest, action, self.request, json_schema.CONFIRM_PASSWORD_REQUEST)) identity = (yield gen.Task(Identity.Query, self._client, identity_key, None)) if (action == 'register'): salt = kwargs['user_dict']['salt'] pwd_hash = kwargs['user_dict']['pwd_hash'] else...
'POST is used when authenticating via the mobile application.'
@handler.asynchronous(datastore=True) @gen.engine def post(self):
(yield gen.Task(self._StartJSONRequest, 'verify', self.request, json_schema.VERIFY_VIEWFINDER_REQUEST)) identity = (yield Identity.VerifyConfirmedIdentity(self._client, self._request_message.dict['identity'], self._request_message.dict['access_token'])) group_id = identity.json_attrs['group_id'] random_...
'POST is used when authenticating via the mobile application.'
@handler.asynchronous(datastore=True) @gen.engine def post(self, action):
if (not ServerEnvironment.IsDevBox()): raise web.HTTPError(403, _FAKE_AUTHORIZATION_FORBIDDEN) (user_dict, ident_dict, device_dict) = (yield gen.Task(self._StartAuthViewfinder, action)) self._AuthUser(user_dict, ident_dict, device_dict)
'Initialize the __userAgent and __httpAccept variables Keyword arguments: userAgent -- the User-Agent header httpAccept -- the Accept header'
def __init__(self, userAgent, httpAccept):
self.__userAgent = (userAgent.lower() if userAgent else '') self.__httpAccept = (httpAccept.lower() if httpAccept else '') self.__isIphone = False self.__isAndroidPhone = False self.__isTierTablet = False self.__isTierIphone = False self.__isTierRichCss = False self.__isTierGenericMobile...
'Return the lower case HTTP_USER_AGENT'
def getUserAgent(self):
return self.__userAgent
'Return the lower case HTTP_ACCEPT'
def getHttpAccept(self):
return self.__httpAccept
'Return whether the device is an Iphone or iPod Touch'
def getIsIphone(self):
return self.__isIphone
'Return whether the device is in the Tablet Tier.'
def getIsTierTablet(self):
return self.__isTierTablet
'Return whether the device is in the Iphone Tier.'
def getIsTierIphone(self):
return self.__isTierIphone
'Return whether the device is in the \'Rich CSS\' tier of mobile devices.'
def getIsTierRichCss(self):
return self.__isTierRichCss
'Return whether the device is a generic, less-capable mobile device.'
def getIsTierGenericMobile(self):
return self.__isTierGenericMobile
'Initialize Key Stored Values.'
def initDeviceScan(self):
self.__isIphone = self.detectIphoneOrIpod() self.__isAndroidPhone = self.detectAndroidPhone() self.__isTierTablet = self.detectTierTablet() self.__isTierIphone = self.detectTierIphone() self.__isTierRichCss = self.detectTierRichCss() self.__isTierGenericMobile = self.detectTierOtherPhones()
'Return detection of an iPhone Detects if the current device is an iPhone.'
def detectIphone(self):
return ((UAgentInfo.deviceIphone in self.__userAgent) and (not self.detectIpad()) and (not self.detectIpod()))
'Return detection of an iPod Touch Detects if the current device is an iPod Touch.'
def detectIpod(self):
return (UAgentInfo.deviceIpod in self.__userAgent)
'Return detection of an iPad Detects if the current device is an iPad tablet.'
def detectIpad(self):
return ((UAgentInfo.deviceIpad in self.__userAgent) and self.detectWebkit())
'Return detection of an iPhone or iPod Touch Detects if the current device is an iPhone or iPod Touch.'
def detectIphoneOrIpod(self):
return ((UAgentInfo.deviceIphone in self.__userAgent) or (UAgentInfo.deviceIpod in self.__userAgent))
'Return detection of an Apple iOS device Detects *any* iOS device: iPhone, iPod Touch, iPad.'
def detectIos(self):
return (self.detectIphoneOrIpod() or self.detectIpad())
'Return detection of an Android device Detects *any* Android OS-based device: phone, tablet, and multi-media player. Also detects Google TV.'
def detectAndroid(self):
if ((UAgentInfo.deviceAndroid in self.__userAgent) or self.detectGoogleTV()): return True return (UAgentInfo.deviceHtcFlyer in self.__userAgent)
'Return detection of an Android phone Detects if the current device is a (small-ish) Android OS-based device used for calling and/or multi-media (like a Samsung Galaxy Player). Google says these devices will have \'Android\' AND \'mobile\' in user agent. Ignores tablets (Honeycomb and later).'
def detectAndroidPhone(self):
if (self.detectAndroid() and (UAgentInfo.mobile in self.__userAgent)): return True if self.detectOperaAndroidPhone(): return True return (UAgentInfo.deviceHtcFlyer in self.__userAgent)
'Return detection of an Android tablet Detects if the current device is a (self-reported) Android tablet. Google says these devices will have \'Android\' and NOT \'mobile\' in their user agent.'
def detectAndroidTablet(self):
if (not self.detectAndroid()): return False if self.detectOperaMobile(): return False if (UAgentInfo.deviceHtcFlyer in self.__userAgent): return False return (UAgentInfo.mobile not in self.__userAgent)
'Return detection of an Android WebKit browser Detects if the current device is an Android OS-based device and the browser is based on WebKit.'
def detectAndroidWebKit(self):
return (self.detectAndroid() and self.detectWebkit())
'Return detection of GoogleTV Detects if the current device is a GoogleTV.'
def detectGoogleTV(self):
return (UAgentInfo.deviceGoogleTV in self.__userAgent)
'Return detection of a WebKit browser Detects if the current browser is based on WebKit.'
def detectWebkit(self):
return (UAgentInfo.engineWebKit in self.__userAgent)
'Return detection of Symbian S60 Browser Detects if the current browser is the Symbian S60 Open Source Browser.'
def detectS60OssBrowser(self):
return (self.detectWebkit() and ((UAgentInfo.deviceSymbian in self.__userAgent) or (UAgentInfo.deviceS60 in self.__userAgent)))
'Return detection of SymbianOS Detects if the current device is any Symbian OS-based device, including older S60, Series 70, Series 80, Series 90, and UIQ, or other browsers running on these devices.'
def detectSymbianOS(self):
return ((UAgentInfo.deviceSymbian in self.__userAgent) or (UAgentInfo.deviceS60 in self.__userAgent) or (UAgentInfo.deviceS70 in self.__userAgent) or (UAgentInfo.deviceS80 in self.__userAgent) or (UAgentInfo.deviceS90 in self.__userAgent))
'Return detection of Windows Phone 7 Detects if the current browser is a Windows Phone 7 device.'
def detectWindowsPhone7(self):
return (UAgentInfo.deviceWinPhone7 in self.__userAgent)
'Return detection of Windows Mobile Detects if the current browser is a Windows Mobile device. Excludes Windows Phone 7 devices. Focuses on Windows Mobile 6.xx and earlier.'
def detectWindowsMobile(self):
if self.detectWindowsPhone7(): return False if ((UAgentInfo.deviceWinMob in self.__userAgent) or (UAgentInfo.deviceIeMob in self.__userAgent) or (UAgentInfo.enginePie in self.__userAgent)): return True if ((UAgentInfo.manuHtc in self.__userAgent) and (UAgentInfo.deviceWindows in self.__userA...
'Return detection of Blackberry Detects if the current browser is any BlackBerry. Includes the PlayBook.'
def detectBlackBerry(self):
return ((UAgentInfo.deviceBB in self.__userAgent) or (UAgentInfo.vndRIM in self.__httpAccept))
'Return detection of a Blackberry Tablet Detects if the current browser is on a BlackBerry tablet device. Example: PlayBook'
def detectBlackBerryTablet(self):
return (UAgentInfo.deviceBBPlaybook in self.__userAgent)
'Return detection of a Blackberry device with WebKit browser Detects if the current browser is a BlackBerry device AND uses a WebKit-based browser. These are signatures for the new BlackBerry OS 6. Examples: Torch. Includes the Playbook.'
def detectBlackBerryWebKit(self):
return (self.detectBlackBerry() and self.detectWebkit())
'Return detection of a Blackberry touchscreen device Detects if the current browser is a BlackBerry Touch device, such as the Storm, Torch, and Bold Touch. Excludes the Playbook.'
def detectBlackBerryTouch(self):
return ((UAgentInfo.deviceBBStorm in self.__userAgent) or (UAgentInfo.deviceBBTorch in self.__userAgent) or (UAgentInfo.deviceBBBoldTouch in self.__userAgent) or (UAgentInfo.deviceBBCurveTouch in self.__userAgent))
'Return detection of a Blackberry device with a better browser Detects if the current browser is a BlackBerry device AND has a more capable recent browser. Excludes the Playbook. Examples, Storm, Bold, Tour, Curve2 Excludes the new BlackBerry OS 6 and 7 browser!!'
def detectBlackBerryHigh(self):
if self.detectBlackBerryWebKit(): return False if (not self.detectBlackBerry()): return False return (self.detectBlackBerryTouch() or (UAgentInfo.deviceBBBold in self.__userAgent) or (UAgentInfo.deviceBBTour in self.__userAgent) or (UAgentInfo.deviceBBCurve in self.__userAgent))
'Return detection of a Blackberry device with a poorer browser Detects if the current browser is a BlackBerry device AND has an older, less capable browser. Examples: Pearl, 8800, Curve1'
def detectBlackBerryLow(self):
if (not self.detectBlackBerry()): return False return (self.detectBlackBerryHigh() or self.detectBlackBerryWebKit())
'Return detection of a PalmOS device Detects if the current browser is on a PalmOS device.'
def detectPalmOS(self):
if ((UAgentInfo.devicePalm in self.__userAgent) or (UAgentInfo.engineBlazer in self.__userAgent) or (UAgentInfo.engineXiino in self.__userAgent)): return (not self.detectPalmWebOS()) return False
'Return detection of a Palm WebOS device Detects if the current browser is on a Palm device running the new WebOS.'
def detectPalmWebOS(self):
return (UAgentInfo.deviceWebOS in self.__userAgent)
'Return detection of an HP WebOS tablet Detects if the current browser is on an HP tablet running WebOS.'
def detectWebOSTablet(self):
return ((UAgentInfo.deviceWebOShp in self.__userAgent) and (UAgentInfo.deviceTablet in self.__userAgent))
'Return detection of a Garmin Nuvifone Detects if the current browser is a Garmin Nuvifone.'
def detectGarminNuvifone(self):
return (UAgentInfo.deviceNuvifone in self.__userAgent)
'Return detection of a general smartphone device Check to see whether the device is any device in the \'smartphone\' category.'
def detectSmartphone(self):
return (self.__isIphone or self.__isAndroidPhone or self.__isTierIphone or self.detectS60OssBrowser() or self.detectSymbianOS() or self.detectWindowsMobile() or self.detectWindowsPhone7() or self.detectBlackBerry() or self.detectPalmWebOS() or self.detectPalmOS() or self.detectGarminNuvifone())