Esempio n. 1
0
def set_tenant(tenant, scope="request"):
    global context

    if scope == "request":
        context.tenant = tenant
        webapp2.get_request().environ['IN_SESSION'] = False
    else:
        logging.info("**** Storing tenant in session...")
        webapp2.get_request().environ['IN_SESSION'] = True
        sessions.get_store().get_session()['TENANT'] = tenant
Esempio n. 2
0
def _logout_user():
    """ Delete the cookie and terminate the UserSession. """
    request = webapp2.get_request()
    cookie_value = request.cookies.get(NDB_USERS_COOKIE_KEY)
    if cookie_value:
        ndb.Key(users.UserSession, cookie_value).delete()
        request.response.delete_cookie(NDB_USERS_COOKIE_KEY)
Esempio n. 3
0
def _create_recovery_email_for_user_id(user_id):
    """ Create a password recovery token for `user` and send an email to the
  User's email address including a link to reset their password. """
    request = webapp2.get_request()
    new_user_recovery_key = users.UserRecovery.create_user_recovery(user_id)
    if new_user_recovery_key:
        query_options = {'token': new_user_recovery_key.string_id()}
        continue_uri = request.GET.get('continue')
        if continue_uri:
            query_options['continue'] = continue_uri
        reset_url = ''.join([
            request.host_url,
            webapp2.uri_for('loginPasswordReset'), '?',
            urlencode(query_options)
        ])
        user = ndb.Key(users.User, user_id).get()
        sender_email_address = users._email_sender()
        subject = 'Password Reset'
        body = """Reset your password by clicking the link below:

{recovery_link}

You may ignore this email and continue using your current password if you did \
not request this recovery or remember your current password.
""".format(recovery_link=reset_url)
        mail.send_mail(sender_email_address, user.email, subject, body)
Esempio n. 4
0
def _create_activation_email_for_user_id(user_id):
    """ Create an activation token for `user` and send an email to the User's
  email address including a link to activate. """
    request = webapp2.get_request()
    new_user_activation_key = users.UserActivation.create_user_activation(
        user_id)
    if new_user_activation_key:
        query_options = {'token': new_user_activation_key.string_id()}
        continue_uri = request.GET.get('continue')
        if continue_uri:
            query_options['continue'] = continue_uri
        activation_url = ''.join([
            request.host_url,
            webapp2.uri_for('loginActivate'), '?',
            urlencode(query_options)
        ])
        user = ndb.Key(users.User, user_id).get()
        sender_email_address = users._email_sender()
        subject = 'Account Activation'
        body = """Your account has been created! Please confirm your email address \
by clicking the link below:

{activation_link}
""".format(activation_link=activation_url)
        mail.send_mail(sender_email_address, user.email, subject, body)
Esempio n. 5
0
def get_trace_id_from_webapp2():
    """Get trace_id from webapp2 request headers.

    :rtype: str
    :returns: TraceID in HTTP request headers.
    """
    if webapp2 is None:
        return None

    try:
        # get_request() succeeds if we're in the middle of a webapp2
        # request, or raises an assertion error otherwise:
        # "Request global variable is not set".
        req = webapp2.get_request()
    except AssertionError:
        return None

    header = req.headers.get(_WEBAPP2_TRACE_HEADER)

    if header is None:
        return None

    trace_id = header.split("/", 1)[0]

    return trace_id
Esempio n. 6
0
    def get(self, match=None):
        req = webapp2.get_request()
        top_path = req.path.split('/')
        lang_code = top_path[1]

        langInfo = self.app.config.get('langInfo')
        try:
            collation_string = langInfo.collation_string
        except:
            collation_string = None

        # user_info = getUserInfo(self.request.url)

        # t = Template("My name is {{ person.first_name }}.")

        template_values = {
            'language': langInfo.Language,
            'langInfo': langInfo,
            'collation_data': langInfo.collation_data,
            'collation_string': langInfo.collation_string,
            'converters': langInfo.converters,
            'unicodeFontList': langInfo.unicode_font_list,
            'showTools': self.request.get('tools', None),
            'links': langInfo.links,
        }
        path = os.path.join(os.path.dirname(__file__),
                            'HTML/collationView.html')
        self.response.out.write(template.render(path, template_values))
Esempio n. 7
0
  def validate(self):
    request = webapp2.get_request()
    data = json.decode(request.body)

    if not isinstance(data, dict):
      webapp2.abort(403, detail='not a dict')

    for f in self.fields:
      if not f.id in self.validations:
        continue

      try:
        value = data[f.id].strip()
      except KeyError:
        value = ''

      self.field_values[f.id] = value
      for val in self.validations[f.id]:
        val.input = f.id

        if not val.validate(self):
          webapp2.abort(403, 
            detail='validation error, id: %s name: %s value: %s' 
            % (f.id, f.name, value))

    return self.field_values
    def _new_deferred_run(data):
        try:
            func, args, kwds = pickle.loads(data)
        except Exception as e:
            raise deferred.PermanentTaskFailure(e)
        else:
            try:
                logging.debug('Queue: %s\ndeferred.run(%s.%s%s%s)',
                              get_current_queue(),
                              func.__module__, func.__name__,
                              "".join((",\n             %s" % repr(a) for a in args)),
                              "".join((",\n             %s=%s" % (k, repr(v)) for k, v in kwds.iteritems())))
            except:
                logging.exception('Failed to log the info of this defer (%s)', func)

            try:
                return func(*args, **kwds)
            except deferred.PermanentTaskFailure:
                stop_suppressing()
                raise
            except:
                request = webapp2.get_request()
                if request:
                    execution_count_triggering_error_log = 9
                    execution_count = request.headers.get('X-Appengine-Taskexecutioncount', None)
                    if execution_count and int(execution_count) == execution_count_triggering_error_log:
                        logging.error('This deferred.run already failed %s times!', execution_count, _suppress=False)
                raise
Esempio n. 9
0
 def _get(self, model, id, *extra_filters):
   # TODO(doug) does the model name need to be ascii encoded since types don't support utf-8?
   cls = users if model == "users" else type(model.lower(), (ScopedExpando,), {})
   if id:
     me = False
     if model == "users":
       if id == "me":
         me = True
         id = current_user(required=True)
     key = parse_id(id, model)
     m = key.get()
     if not m:
       if model == "users" and me:
         m = users()
         m.key = key
         setattr(m, "$unsaved", True)
         environ = webapp2.get_request().environ
         for k, v in environ.iteritems():
           if k[:14] == "TAILBONE_USER_" and k != "TAILBONE_USER_ID" and v:
             setattr(m, k[14:].lower(), v)
       else:
         raise AppError("No {} with id {}.".format(model, id))
     return m.to_dict()
   else:
     return query(self, cls, *extra_filters)
Esempio n. 10
0
def current_user(required=False):
  u = webapp2.get_request().environ.get("TAILBONE_USER_ID")
  if u:
    return ndb.Key("users", u).urlsafe()
  if required:
    raise LoginError("User must be logged in.")
  return None
Esempio n. 11
0
def _static_dir(file_path, version=None):
    if version:
        version = '?v=%s' % _get_version()
    else:
        version = ''
    return '%s/client/%s%s' % (settings.get_host_url(
        webapp2.get_request().host), file_path, version)
Esempio n. 12
0
def generate_csrf_token():
    session = wa2.get_request().registry['session']
    t = session.get('_csrf_token')
    if not t:
        t = utils.newToken()
        session['_csrf_token'] = t
    return t
Esempio n. 13
0
def template_values(template_values=dict(), query_options=dict(), user=None):
  """ Return `template_values` plus the default key-value pairs. """
  request = webapp2.get_request()
  continue_uri = request.GET.get('continue')
  if continue_uri:
    query_options['continue'] = continue_uri
    template_values.update(continue_uri=continue_uri)
  logout_query_options = query_options.copy()
  logout_query_options['action'] = 'logout'
  if not user:
    # Only fetch via get_current_user() if `user` kwarg is None
    user = get_current_user()
  if user:
    # Default key-value pairs with logged in user
    template_values.update(user={ 'email': user.email },
      logout_uri=_append_query(
        NDB_USERS_LOGIN_URI, urlencode(logout_query_options)),
      password_change_uri=_append_query(
        NDB_USERS_LOGIN_PASSWORD_CHANGE_URI, urlencode(query_options)),
      password_forgot_uri=_append_query(
        NDB_USERS_LOGIN_PASSWORD_FORGOT_URI, urlencode(query_options))
    )
  else:
    # Default key-value pairs with no user
    template_values.update(
        login_uri=_append_query(
          NDB_USERS_LOGIN_URI, urlencode(query_options)),
        create_uri=_append_query(
          NDB_USERS_LOGIN_CREATE_URI, urlencode(query_options)),
        password_forgot_uri=_append_query(
          NDB_USERS_LOGIN_PASSWORD_FORGOT_URI, urlencode(query_options)),
        password_reset_uri=_append_query(
          NDB_USERS_LOGIN_PASSWORD_RESET_URI, urlencode(query_options))
      )
  return template_values
Esempio n. 14
0
def _logout_user():
  """ Delete the cookie and terminate the UserSession. """
  request = webapp2.get_request()
  cookie_value = request.cookies.get(NDB_USERS_COOKIE_KEY)
  if cookie_value:
    ndb.Key(users.UserSession, cookie_value).delete()
    request.response.delete_cookie(NDB_USERS_COOKIE_KEY)
Esempio n. 15
0
def _create_recovery_email_for_user_id(user_id):
  """ Create a password recovery token for `user` and send an email to the
  User's email address including a link to reset their password. """
  request = webapp2.get_request()
  new_user_recovery_key = users.UserRecovery.create_user_recovery(user_id)
  if new_user_recovery_key:
    query_options = {
      'token': new_user_recovery_key.string_id()
    }
    continue_uri = request.GET.get('continue')
    if continue_uri:
      query_options['continue'] = continue_uri
    reset_url = ''.join([
      request.host_url,
      webapp2.uri_for('loginPasswordReset'),
      '?', urlencode(query_options)
    ])
    user = ndb.Key(users.User, user_id).get()
    sender_email_address = users._email_sender()
    subject = 'Password Reset'
    body = """Reset your password by clicking the link below:

{recovery_link}

You may ignore this email and continue using your current password if you did \
not request this recovery or remember your current password.
""".format(recovery_link=reset_url)
    mail.send_mail(sender_email_address, user.email, subject, body)
Esempio n. 16
0
def current_user(required=False):
    u = webapp2.get_request().environ.get("TAILBONE_USER_ID")
    if u:
        return ndb.Key("users", u).urlsafe()
    if required:
        raise LoginError("User must be logged in.")
    return None
Esempio n. 17
0
 def _get(self, model, id, *extra_filters):
     # TODO(doug) does the model name need to be ascii encoded since types don't support utf-8?
     cls = users if model == "users" else type(model.lower(),
                                               (ScopedExpando, ), {})
     if id:
         me = False
         if model == "users":
             if id == "me":
                 me = True
                 id = current_user(required=True)
         key = parse_id(id, model)
         m = key.get()
         if not m:
             if model == "users" and me:
                 m = users()
                 m.key = key
                 setattr(m, "$unsaved", True)
                 environ = webapp2.get_request().environ
                 for k, v in environ.iteritems():
                     if k[:
                          14] == "TAILBONE_USER_" and k != "TAILBONE_USER_ID" and v:
                         setattr(m, k[14:].lower(), v)
             else:
                 raise AppError("No {} with id {}.".format(model, id))
         return m.to_dict()
     else:
         return query(self, cls, *extra_filters)
def is_in_deferred():
    try:
        return webapp2.get_request().headers.get('X-Appengine-Taskname', None) is not None
    except AssertionError:
        # when webapp2.get_requests() returns an assertion error, there is no current request so we must be
        # in a deferred task
        return True
Esempio n. 19
0
def get_trace_id_from_webapp2():
    """Get trace_id from webapp2 request headers.

    :rtype: str
    :returns: TraceID in HTTP request headers.
    """
    if webapp2 is None:
        return None

    try:
        # get_request() succeeds if we're in the middle of a webapp2
        # request, or raises an assertion error otherwise:
        # "Request global variable is not set".
        req = webapp2.get_request()
    except AssertionError:
        return None

    header = req.headers.get(_WEBAPP2_TRACE_HEADER)

    if header is None:
        return None

    trace_id = header.split('/', 1)[0]

    return trace_id
Esempio n. 20
0
def settings():
    """
    Returns the entire settings registry
    """

    # Check local request storage for the completed settings registry
    try:
        request = get_request()
    except AssertionError:
        request = None

    if request and 'ferris-settings' in request.registry:
        return request.registry['ferris-settings']

    # If it's not there, do the normal thing

    settings = {}
    settings.update(_defaults)
    events.fire('build_settings', settings=settings)

    # Try to store it back in the request
    if request:
        request.registry['ferris-settings'] = settings

    return settings
Esempio n. 21
0
def get_fms_client():
    """
    Returns a soap client object.

    If an object has already been created, we recyle it,
    otherwise, a new one is created and returned.

    """
    app = webapp2.get_app()
    request = webapp2.get_request()

    username = request.registry["session"].get("username")
    password = request.registry["session"].get("password")
    fms_key = "fms_client:{}".format(username)

    # check if we already have the client
    fms_client = app.registry.get(fms_key)
    if not fms_client:
        fms_client = Client(FMS_URL, cache=None)
        fms_client.add_prefix("rsp", "http://response.atms.core.mtrak.digi.com/xsd")
        fms_client.add_prefix("srv", "http://service.atms.core.mtrak.digi.com")
        fms_client.add_prefix("vo", "http://vo.atms.core.mtrak.digi.com/xsd")

        app.registry[fms_key] = fms_client

    fms_client.set_options(soapheaders=(Element("username").setText(username), Element("password").setText(password)))

    return fms_client
Esempio n. 22
0
def settings():
    """
    Returns the entire settings registry
    """

    # Check local request storage for the completed settings registry
    try:
        request = get_request()
    except AssertionError:
        request = None

    if request and "ferris-settings" in request.registry:
        return request.registry["ferris-settings"]

    # If it's not there, do the normal thing

    settings = {}
    settings.update(_defaults)
    events.fire("build_settings", settings=settings)

    # Try to store it back in the request
    if request:
        request.registry["ferris-settings"] = settings

    return settings
Esempio n. 23
0
def create_security_question(answer1, answer2, answer3,
                             question1, question2, question3, userName):
    """
    Create a new security question.

    """

    lgn_client = get_lgn_client()

    session = webapp2.get_request().registry.get('session')

    userId = session.get('user_id')

    securityQuestionVO = _make_VO('vo', 'SecurityQuestionVO')

    securityQuestionVO.reminderAnswer1 = answer1
    securityQuestionVO.reminderQuestion1 = question1

    securityQuestionVO.reminderAnswer2 = answer2
    securityQuestionVO.reminderQuestion2 = question2

    securityQuestionVO.reminderAnswer3 = answer3
    securityQuestionVO.reminderQuestion3 = question3

    securityQuestionVO.userId = userId
    securityQuestionVO.userName = userName

    response = lgn_client.service.createSecurityQuestion(securityQuestionVO)

    return response
Esempio n. 24
0
def get_lgn_client():
    '''
    Returns a soap client object.

    If an object has already been created, we recyle it,
    otherwise, a new one is created and returned.

    '''
    app = webapp2.get_app()
    request = webapp2.get_request()

    username = request.registry['session'].get('username')
    password = request.registry['session'].get('password')
    lgn_key = 'lgn_client:{}'.format(username)

    # Check if we already have the client
    lgn_client = app.registry.get(lgn_key)

    if not lgn_client:
        lgn_client = Client(LGN_URL, cache=None)
        lgn_client.add_prefix(
            'srv', "http://service.login.core.mtrak.digi.com")
        lgn_client.add_prefix(
            'vo', "http://vo.login.core.mtrak.digi.com/xsd")

        app.registry[lgn_key] = lgn_client

    lgn_client.set_options(soapheaders=(
        Element('username').setText(username),
        Element('password').setText(password)))

    return lgn_client
Esempio n. 25
0
def reset_password(new_password, answer1, answer2, answer3,
                   question1, question2, question3, userName):
    """
    Reset the password given all of the security questions and answers.

    """

    lgn_client = get_lgn_client()

    session = webapp2.get_request().registry.get('session')

    userId = session.get('user_id')

    securityQuestionVO = _make_VO('vo', 'SecurityQuestionVO')

    securityQuestionVO.newPassword = new_password

    securityQuestionVO.reminderAnswer1 = answer1
    securityQuestionVO.reminderQuestion1 = question1

    securityQuestionVO.reminderAnswer2 = answer2
    securityQuestionVO.reminderQuestion2 = question2

    securityQuestionVO.reminderAnswer3 = answer3
    securityQuestionVO.reminderQuestion3 = question3

    securityQuestionVO.userId = userId
    securityQuestionVO.userName = userName

    response = lgn_client.service.resetPassword(securityQuestionVO)

    return response
Esempio n. 26
0
def _add_appengine_trace(extras):
    """Add App Engine tracing information."""
    if sys.version_info.major != 3 or not _is_running_on_app_engine():
        # TODO(ochang): Remove Python 3 check once all migrated to Python 3.
        return

    import webapp2

    try:
        request = webapp2.get_request()
        if not request:
            return
    except Exception:
        # FIXME: Find a way to add traces in threads. Skip adding for now, as
        # otherwise, we hit an exception "Request global variable is not set".
        return

    trace_header = request.headers.get('X-Cloud-Trace-Context')
    if not trace_header:
        return

    project_id = os.getenv('APPLICATION_ID')
    trace_id = trace_header.split('/')[0]
    extras['logging.googleapis.com/trace'] = (
        'projects/{project_id}/traces/{trace_id}').format(
            project_id=project_id, trace_id=trace_id)
Esempio n. 27
0
def get_device_client():
    '''
    Returns a soap client object.

    If an object has already been created, we recyle it,
    otherwise, a new one is created and returned.

    '''
    app = webapp2.get_app()
    request = webapp2.get_request()

    # check if we already have the client
    username = request.registry['session'].get('username')
    password = request.registry['session'].get('password')
    device_key = 'device_client:{}'.format(username)

    # check if we aleady have the client
    device_client = app.registry.get(device_key)
    if not device_client:
        device_client = Client(DEV_URL, cache=None)
        device_client.add_prefix(
            'rsp', "http://response.devicemanagement.core.mtrak.digi.com/xsd")
        device_client.add_prefix(
            'srv', "http://service.devicemanagement.core.mtrak.digi.com")
        device_client.add_prefix(
            'vo', "http://vo.devicemanagement.core.mtrak.digi.com/xsd")

        app.registry[device_key] = device_client

    device_client.set_options(soapheaders=(
        Element('username').setText(username),
        Element('password').setText(password)))

    return device_client
Esempio n. 28
0
def get(setting):
    # 1. Try request-local cache
    request = webapp2.get_request()
    if request:
        if 'thonkify_setting_cache' not in request.registry:
            request.registry['thonkify_setting_cache'] = {}
        if setting in request.registry['thonkify_setting_cache']:
            # NOTE: we don't update caches here because that's the only place it
            # could have come from, and it would result in a bunch of memcache set()
            # traffic.
            return request.registry['thonkify_setting_cache'][setting]

    # 2. Try memcache
    mc = memcache.get_multi([setting], key_prefix=SETTING_MC_PREFIX)
    if setting in mc:
        # ... but don't try to update memcache, because we've just got it from there
        return _update_caches(setting, mc[setting], skip_memcache=True)

    # 3. Try datastore
    value = GlobalSetting.get(setting)
    if value is not None:
        return _update_caches(setting, value)

    # 4. Fall back to defaults
    if setting in TWEAKABLE_DEFAULTS:
        s = TWEAKABLE_DEFAULTS[setting]
        return _update_caches(setting, s[0] if isinstance(s, tuple) else s)

    # 5. Module-level constant?
    if setting[0] in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' and setting in globals():
        return _update_caches(setting, globals()[setting])

    # 6. Give up
    raise KeyError('Setting "%s" does not exist' % setting)
def get_current_queue():
    try:
        import webapp2
        request = webapp2.get_request()
        if request:
            return request.headers.get('X-Appengine-Queuename', None)
    except:
        logging.warn('Failed to get the name of the current queue', exc_info=1)
Esempio n. 30
0
def get_storage():
    request = webapp2.get_request()
    if not hasattr(request, 'localstorage'):
        storage = LocalStorage()
        setattr(request, 'localstorage', storage)
    else:
        storage = getattr(request, 'localstorage')
    return storage
Esempio n. 31
0
def insert_result(sid, stop):
    aggregated_results = webapp2.get_request().registry['aggregated_results']

    if len(aggregated_results) == 0:
        aggregated_results = [stop]
    else:
        done = False
        for i, s in enumerate(aggregated_results):
            if stop.time <= s.time:
                aggregated_results.insert(i, stop)
                done = True
                break
        if not done:
            aggregated_results.append(stop)

    # always reset the request registry value
    webapp2.get_request().registry['aggregated_results'] = aggregated_results
def get_callback_domain():
    request = webapp2.get_request()
    host = request.host
    if "localhost" in host:
        callback_domain = host
    else:
        callback_domain = CALLBACK_DOMAIN
    return callback_domain
Esempio n. 33
0
def get_current_queue():
    try:
        import webapp2
        request = webapp2.get_request()
        if request:
            return request.headers.get('X-Appengine-Queuename', None)
    except:
        logging.warn('Failed to get the name of the current queue', exc_info=1)
Esempio n. 34
0
def get_callback_domain():
    request = webapp2.get_request()
    host = request.host
    if 'localhost' in host:
        callback_domain = host
    else:
        callback_domain = CALLBACK_DOMAIN
    return callback_domain
Esempio n. 35
0
    def get(self, match=None):
        # Match is the actual url route matched.
        req = webapp2.get_request()
        # Can use this for additional information
        langInfo = self.app.config.get('langInfo')

        try:
            text_direction = langInfo.direction
        except AttributeError:
            text_direction = 'ltr'

        try:
            test_data = langInfo.test_data
        except AttributeError:
            test_data = ''
        try:
            variation_sequence = langInfo.variation_sequence
        except:
            variation_sequence = None

        try:
            encoded_ranges = langInfo.encoded_ranges
        except:
            encoded_ranges = None

        try:
            allFonts = langInfo.allFonts
        except:
            allFonts = False

        # Use the standard demo / keyboard template
        home_html = 'HTML/demo_general.html'

        kb_radical = [
            {
                'shortName': 'ig_nsi_radicals',
                'longName': 'Igbo Radical',
                'fontFamily': 'Akagu2020',
                'instructions': 'Type radical keys to get combinations.'
            },
        ]
        template_values = {
            'allFonts': allFonts,
            'direction': text_direction,
            'encoded_ranges': encoded_ranges,
            'language': langInfo.Language,
            'langTag': langInfo.LanguageCode,
            'font_list': langInfo.unicode_font_list,
            'lang_list': langInfo.lang_list,
            'kb_list': kb_radical,
            'langInfo': langInfo,
            'links': langInfo.links,
            'showTools': self.request.get('tools', None),
            'test_data': test_data,
            'variation_sequence': variation_sequence,
        }
        path = os.path.join(os.path.dirname(__file__), home_html)
        self.response.out.write(template.render(path, template_values))
Esempio n. 36
0
def get_current_user():
    """  GAE compatibility method. """
    request = webapp2.get_request()
    app = webapp2.get_app()
    audience = app.config.get('idtoken_audience')
    if not audience:
        raise Exception('idtoken_audience not configured')
    token = request.headers.get('x-w69b-idtoken')
    return _user_from_token(token, audience)
Esempio n. 37
0
def isFromTaskQueue(request=None):
    """ Check if we are currently running from a task queue """
    request = request or webapp2.get_request()
    # As stated in the doc (https://developers.google.com/appengine/docs/python/taskqueue/overview-push#Task_Request_Headers)
    # These headers are set internally by Google App Engine.
    # If your request handler finds any of these headers, it can trust that the request is a Task Queue request.
    # If any of the above headers are present in an external user request to your App, they are stripped.
    # The exception being requests from logged in administrators of the application, who are allowed to set the headers for testing purposes.
    return bool(request.headers.get('X-Appengine-TaskName'))
Esempio n. 38
0
 def getConfig(self, asset_id):
     request = webapp2.get_request()
     org_id = request.registry['session'].get('organization_id')
     self.response.out.write(
         template.render(
             os.path.join('template', 'config_tmpl.html'),
             {'username': self.session.get('username'),
              'pageData': create_current_config(org_id, asset_id),
              'version': version_string}))
Esempio n. 39
0
def isFromTaskQueue(request=None):
    """ Check if we are currently running from a task queue """
    request = request or webapp2.get_request()
    # As stated in the doc (https://developers.google.com/appengine/docs/python/taskqueue/overview-push#Task_Request_Headers)
    # These headers are set internally by Google App Engine.
    # If your request handler finds any of these headers, it can trust that the request is a Task Queue request.
    # If any of the above headers are present in an external user request to your App, they are stripped.
    # The exception being requests from logged in administrators of the application, who are allowed to set the headers for testing purposes.
    return bool(request.headers.get('X-Appengine-TaskName'))
Esempio n. 40
0
def SetSinglePrivilegedRequest():
  """Allows the current request to act as a privileged user only ONCE.

  This should be called ONLY by handlers that have checked privilege immediately
  before making a query. It will be automatically unset when the next query is
  made.
  """
  request = webapp2.get_request()
  request.registry['single_privileged'] = True
Esempio n. 41
0
  def field(self, id):
    if not id in self.field_values:
      return ''

    if isinstance(self.field_values[id], basestring):
      return self.field_values[id]

    request = webapp2.get_request()
    webapp2.abort(403, detail='not a string, id: %s' % id)
Esempio n. 42
0
def fb_get_meta():
  fb=webapp2.get_request().cookies.get("fb_user")
  if not fb:
    fb=webapp2.get_request().get("auth")
  if fb:
    fb=fb.split(":",1)
    meta=memcache.get("fb"+fb[0])
    if meta is None:
      meta=UserMeta.all().filter('fb_id =',fb[0]).get()
      if meta is not None:
        memcache.add("fb"+fb[0],meta)
    if meta is not None:
      if len(fb)> 1 and fb[1] in meta.auth_verify:
        return meta
      else:
        return None
  else:
    return None
Esempio n. 43
0
def SetSinglePrivilegedRequest():
  """Allows the current request to act as a privileged user only ONCE.

  This should be called ONLY by handlers that have checked privilege immediately
  before making a query. It will be automatically unset when the next query is
  made.
  """
  request = webapp2.get_request()
  request.registry['single_privileged'] = True
Esempio n. 44
0
 def userPage(self):
     request = webapp2.get_request()
     org_id = request.registry['session'].get('organization_id')
     self.response.out.write(
         template.render(
             os.path.join('template', 'user_tmpl.html'),
             {'username': self.session.get('username'),
              'org_id': org_id,
              'version': version_string}))
Esempio n. 45
0
 def parse(self,
           argmap,
           req=None,
           locations=None,
           validate=None,
           force_all=False):
     """Wrap :meth:`core.Parser.parse` to inject the active :class:`webapp2.Request` in"""
     req = req or webapp2.get_request()
     return super(Webapp2Parser, self).parse(argmap, req, locations,
                                             validate, force_all)
Esempio n. 46
0
 def wrapper(*argv, **kwargs):
     req = webapp2.get_request()
     if 'timer' in req.registry:
         timer = req.registry['timer']
         class_name = str(argv[0]).partition("<")[0]
         event_idx = timer.startEvent(class_name, fn.__name__, argv[1:])
     ret_value = fn(*argv, **kwargs)
     if 'timer' in req.registry:
         timer.finishEvent(event_idx)
     return ret_value
Esempio n. 47
0
 def getDataStr(cls):
   req = webapp2.get_request();
   timer = req.registry['timer']
   timer.addEvent('done')
   result = ["Timer:\n\nCurr request = " + str(req)]
   result.append("\ntiming: ")
   for e in timer.events:
     result.append("%0.3f, %0.3f, %s" % (e[0], e[1], str(e[2:])))
   result.append("\n");
   return '\n'.join(result)
Esempio n. 48
0
 def wrapper(*argv, **kwargs):
   req = webapp2.get_request()
   if 'timer' in req.registry:
     timer =  req.registry['timer']
     class_name = str(argv[0]).partition("<")[0]
     event_idx = timer.startEvent(class_name, fn.__name__, argv[1:])
   ret_value = fn(*argv, **kwargs)
   if 'timer' in req.registry:
     timer.finishEvent(event_idx)
   return ret_value
Esempio n. 49
0
def SetPrivilegedRequest():
  """Allows the current request to act as a privileged user.

  This should ONLY be called for handlers that are restricted from end users
  by some other mechanism (IP whitelisting, admin-only pages).

  This should be set once per request, before accessing the data store.
  """
  request = webapp2.get_request()
  request.registry['privileged'] = True
Esempio n. 50
0
def SetPrivilegedRequest():
  """Allows the current request to act as a privileged user.

  This should ONLY be called for handlers that are restricted from end users
  by some other mechanism (IP allowlist, admin-only pages).

  This should be set once per request, before accessing the data store.
  """
  request = webapp2.get_request()
  request.registry['privileged'] = True
Esempio n. 51
0
 def getDataStr(cls):
     req = webapp2.get_request()
     timer = req.registry['timer']
     timer.addEvent('done')
     result = ["Timer:\n\nCurr request = " + str(req)]
     result.append("\ntiming: ")
     for e in timer.events:
         result.append("%0.3f, %0.3f, %s" % (e[0], e[1], str(e[2:])))
     result.append("\n")
     return '\n'.join(result)
Esempio n. 52
0
def del_tenant(scope="request"):
    global context

    in_session = webapp2.get_request().environ.get('IN_SESSION')

    if not in_session:
        del context.tenant
    else:
        s = sessions.get_store().get_session()
        if 'TENANT' in  s:
            del s['TENANT']
Esempio n. 53
0
    def get(self, match=None):
        # Match is the actual url route matched.
        req = webapp2.get_request()
        # Can use this for additional information
        langInfo = self.app.config.get('langInfo')

        filename = 'testdata/GamWin_convert_test.tsv'
        path = os.path.join(os.path.split(__file__)[0], filename)
        with open(path, 'rb') as f:
            page_content = f.read().decode('utf-8').split('\n')
        self.response.write(page_content)
Esempio n. 54
0
def create_password_change_url(redirect_uri=None):
    """ Return a URL for changing the user's password. Redirect optional.
  Note: Will return current protocol (i.e. http:// or https://),
  secure parameter in app.yaml will redirect to secure URL. """
    request = webapp2.get_request()
    if redirect_uri:
        return ''.join([
            request.host_url, NDB_USERS_LOGIN_PASSWORD_CHANGE_URI, '?',
            urlencode({'continue': redirect_uri})
        ])
    return ''.join([request.host_url, NDB_USERS_LOGIN_PASSWORD_CHANGE_URI])
Esempio n. 55
0
def create_login_url(redirect_uri=None):
    """ A login page, upon successful login will redirect to `redirect_uri`.
  Note: Will return current protocol (i.e. http:// or https://),
  secure parameter in app.yaml will redirect to secure URL. """
    request = webapp2.get_request()
    if redirect_uri:
        return ''.join([
            request.host_url, NDB_USERS_LOGIN_URI, '?',
            urlencode({'continue': redirect_uri})
        ])
    return ''.join([request.host_url, NDB_USERS_LOGIN_URI])
Esempio n. 56
0
def move_order(order, venue):
    if order.venue_id == str(venue.key.id()):
        return

    order.venue_id = str(venue.key.id())
    order.put()

    req = webapp2.get_request()
    renderer = jinja2.get_jinja2()
    send_venue_email(venue, order, req.host_url, renderer, move=True)
    send_venue_sms(venue, order, move=True)
Esempio n. 57
0
 def persist_authorization_code(self, client_id, code, scope):
     user = webapp2.get_request().user
     key = AuthorizationCode.get_key(client_id, code)
     if key.get() is not None:
         raise Exception("duplicate_authorization_code")
     scope = scope.split() if scope else ['data']
     auth_code = AuthorizationCode(
         key=key, code=code, client_id=client_id, scope=scope,
         user_key=user.key, expires_in=oauth_config.TOKEN_EXPIRES_IN
     )
     auth_code.put()
Esempio n. 58
0
def is_mobile(_):
    '''
    Custom jinja2 test.  Use like this:
    {% if _ is mobile %}  (it expects some variable...
    '''
    req = webapp2.get_request()
#    logging.debug( "UA ----------- %s", handler.request.user_agent )
    for ua in ('iPhone','Android','iPod','iPad','BlackBerry','webOS','IEMobile'):
        try: 
            if req.user_agent.index(ua) >= 0: return True
        except ValueError: pass # substring not found, continue
    return False
Esempio n. 59
0
    def get(self, match=None):
        # Match is the actual url route matched.
        req = webapp2.get_request()
        # Can use this for additional information
        langInfo = self.app.config.get('langInfo')

        try:
            text_direction = langInfo.direction
        except AttributeError:
            text_direction = 'ltr'

        try:
            test_data = langInfo.test_data
        except AttributeError:
            test_data = ''
        try:
            variation_sequence = langInfo.variation_sequence
        except:
            variation_sequence = None

        try:
            encoded_ranges = langInfo.encoded_ranges
        except:
            encoded_ranges = None

        try:
            allFonts = langInfo.allFonts
        except:
            allFonts = False

        try:
            home_html = langInfo.custom_home_template
        except:
            home_html = 'HTML/demo_general.html'

        template_values = {
            'allFonts': allFonts,
            'direction': text_direction,
            'encoded_ranges': encoded_ranges,
            'language': langInfo.Language,
            'langTag': langInfo.LanguageCode,
            'font_list': langInfo.unicode_font_list,
            'lang_list': langInfo.lang_list,
            'kb_list': langInfo.kb_list,
            'langInfo': langInfo,
            'links': langInfo.links,
            'showTools': self.request.get('tools', None),
            'test_data': test_data,
            'variation_sequence': variation_sequence,
        }
        path = os.path.join(os.path.dirname(__file__), home_html)
        self.response.out.write(template.render(path, template_values))