Python google.appengine.api.users.get_current_user() Examples

The following are 30 code examples for showing how to use google.appengine.api.users.get_current_user(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module google.appengine.api.users , or try the search function .

Example 1
Project: loaner   Author: google   File: user.py    License: Apache License 2.0 6 votes vote down vote up
def get_user_email():
  """Retrieves the currently logged in user email.

  Returns:
    A string of the email address of the current user.

  Raises:
    UserNotFound: Raised if a user is not currently logged in.
  """

  try:
    current_user = endpoints.get_current_user() or users.get_current_user()
  except endpoints.InvalidGetUserCall:
    current_user = users.get_current_user()

  if current_user:

    return current_user.email()
  raise UserNotFound('get_user_email failed: No user account detected.') 
Example 2
Project: browserscope   Author: elsigh   File: test_user_tests.py    License: Apache License 2.0 6 votes vote down vote up
def testGetTestSetFromResultString(self):
    current_user = users.get_current_user()
    u = models.user_test.User.get_or_insert(current_user.user_id())
    test = models.user_test.Test(user=u, name='Fake Test',
                                 url='http://fakeurl.com/test.html',
                                 description='stuff')
    test.save()

    results_str = 'test_1=0,test_2=1'
    test_set_category = 'usertest_%s' % test.key()
    test_set = models.user_test.Test.get_test_set_from_results_str(
        test_set_category, results_str)
    self.assertTrue(test_set != None)
    self.assertEqual(test_set.category, test_set_category)
    self.assertEqual(len(test_set.tests), 2)
    self.assertEqual('test_1', test_set.tests[0].key)
    self.assertEqual('test_2', test_set.tests[1].key) 
Example 3
Project: locality-sensitive-hashing   Author: singhj   File: test_db_datastore.py    License: MIT License 6 votes vote down vote up
def get(self):
        user = users.get_current_user()
        username = user.nickname()
        
        items = Matrix.all()
        for item in items:
            logging.info('item key %s blob_key %s, filename %s ', item.key.urlsafe(), item.file_key, item.filename)
        length = len(items)
        upload_url = blobstore.create_upload_url("/test_upload_blob")

        self.response.out.write(self.template_env.get_template("blobs.html").render(
            {"username": username,
             "items": items,
             "length": length,
             "upload_url": upload_url,
             "top_form_url": "test_db_datastore"})) 
Example 4
Project: locality-sensitive-hashing   Author: singhj   File: peer_belt_driver.py    License: MIT License 6 votes vote down vote up
def get(self):
        logging.info(os.path.abspath(os.path.curdir))
        logging.info('Peer Belt Driver get method called!')
        user = users.get_current_user()
        username = user.nickname()

        results = BlobDataset.query()
        items = [result for result in results]

        for item in items:
            item.ds_key = item.key.urlsafe()
        length = len(items)

        upload_url = create_upload_url("upload_blob2")

        self.response.out.write(self.template_env.get_template("blobs2.html").render(
            {"username": username,
             "items": items,
             "length": length,
             "upload_url": upload_url})) 
Example 5
Project: locality-sensitive-hashing   Author: singhj   File: blobs.py    License: MIT License 6 votes vote down vote up
def get(self):
        user = users.get_current_user()
        username = user.nickname()

        items = DatasetPB.all()
#         items = [result for result in results.fetch(10)]
#         for item in items:
#             logging.info('fn %s', item.blob_key)
        length = len(items)
        upload_url = blobstore.create_upload_url("/upload_blob")
        
#         Datazz.create(u'fn1', 'ol1')
#         Datazz.all()
#         Datazz.create('fn1', 'ol2')
#         Datazz.create('fn2', 'ol3')
#         Datazz.all()

        self.response.out.write(self.template_env.get_template("blobs.html").render(
            {"username": username,
             "items": items,
             "length": length,
             "upload_url": upload_url,
             "top_form_url": "blobs"})) 
Example 6
Project: locality-sensitive-hashing   Author: singhj   File: mr_main.py    License: MIT License 6 votes vote down vote up
def post(self):
        source = "uploaded by user"
        upload_files = self.get_uploads("file")
        blob_key = upload_files[0].key()
        name = self.request.get("name")

        user = users.get_current_user()

        username = user.nickname()
        date = datetime.datetime.now()
        str_blob_key = str(blob_key)
        key = FileMetadata.getKeyName(username, date, str_blob_key)

        m = FileMetadata(key_name = key)
        m.owner = user
        m.filename = name
        m.uploadedOn = date
        m.source = source
        m.blobkey = str_blob_key
        m.put()

        self.redirect("/mr") 
Example 7
Project: dschat   Author: colohan   File: dschat.py    License: MIT License 6 votes vote down vote up
def post(self):
        user = users.get_current_user()
        if not user:
            # This should never happen, as AppEngine should only run this
            # handler if the user is signed in.  But defense in depth applies...
            self.redirect(users.create_login_url(self.request.uri))
            return

        older_than_id = self.request.get('older_than')
        older_than = datetime.datetime.strptime(older_than_id,
                                                "%Y-%m-%dT%H:%M:%S.%f")

        query = Message.query(ancestor=messages_key()).filter(Message.date <
                                                              older_than
        ).order(-Message.date)
        # Limit query to 50 messages:
        query_results = query.fetch(50)

        if len(query_results) > 0:
            broadcast = MessagesBroadcast(query_results)
            broadcast.send_messages(user.user_id()) 
Example 8
Project: googleapps-message-recall   Author: google   File: frontend_views.py    License: Apache License 2.0 6 votes vote down vote up
def _SafelyGetCurrentUserEmail():
  """Retrieve the current user's email or raise an exception.

  We set 'login: required' in app.yaml so all users should be logged-in.
  But, is has been observed that users.get_current_user() *can* return None.
  Therefore, this must be checked.

  Returns:
    String email address of the currently logged-in user.

  Raises:
    MessageRecallAuthenticationError: If current user is noticed as None.
  """
  user = None
  get_user_attempts = 0
  while not user and get_user_attempts < _GET_USER_MAX_RETRIES:
    user = users.get_current_user()
    get_user_attempts += 1
  if not user:
    raise recall_errors.MessageRecallAuthenticationError(
        'A logged-in user was not retrieved. Please try again.')
  return user.email() 
Example 9
Project: datastore-ndb-python   Author: GoogleCloudPlatform   File: main.py    License: Apache License 2.0 6 votes vote down vote up
def get(self):
    user = users.get_current_user()
    if not user:
      self.redirect(users.create_login_url('/account'))
      return
    email = user.email()
    action = 'Create'
    account, nickname = yield (get_account(user.user_id()),
                               get_nickname(user.user_id()))
    if account is not None:
      action = 'Update'
    if account:
      proposed_nickname = account.nickname or account.email
    else:
      proposed_nickname = email
    values = {'email': email,
              'nickname': nickname,
              'proposed_nickname': proposed_nickname,
              'login': users.create_login_url('/home'),
              'logout': users.create_logout_url('/home'),
              'action': action,
              }
    self.response.out.write(ACCOUNT_PAGE % values) 
Example 10
Project: datastore-ndb-python   Author: GoogleCloudPlatform   File: main.py    License: Apache License 2.0 6 votes vote down vote up
def post(self):
    # TODO: XSRF protection.
    @ndb.tasklet
    def helper():
      user = users.get_current_user()
      if not user:
        self.redirect(users.create_login_url('/account'))
        return
      account = yield get_account(user.user_id())
      if self.request.get('delete'):
        if account:
          yield account.key.delete_async()
        self.redirect('/account')
        return
      if not account:
        account = Account(key=account_key(user.user_id()),
                          email=user.email(), userid=user.user_id())
      nickname = self.request.get('nickname')
      if nickname:
        account.nickname = nickname
      yield account.put_async()
      self.redirect('/account')
    yield ndb.transaction_async(helper) 
Example 11
Project: googleads-python-lib   Author: googleads   File: update_credentials_view.py    License: Apache License 2.0 6 votes vote down vote up
def post(self):
    """Handle post request."""
    template_values = {
        'back_url': '/showCredentials',
        'back_msg': 'View Credentials',
        'logout_url': users.create_logout_url('/'),
        'user_nickname': users.get_current_user().nickname()
    }
    try:
      UpdateUserCredentials(self.request.get('client_id'),
                            self.request.get('client_secret'),
                            self.request.get('refresh_token'),
                            self.request.get('adwords_manager_cid'),
                            self.request.get('dev_token'))
      self.redirect('/showCredentials')
    except Exception as e:
      template_values['error'] = str(e)
      # Use template to write output to the page.
      path = os.path.join(os.path.dirname(__file__),
                          '../templates/base_template.html')
      self.response.out.write(template.render(path, template_values)) 
Example 12
Project: googleads-python-lib   Author: googleads   File: ndb_handler.py    License: Apache License 2.0 6 votes vote down vote up
def InitUser():
  """Initialize application user.

  Retrieve existing user credentials from datastore or add new user.

  Returns:
    AppUser instance of the application user.
  """
  result = AppUser.query(AppUser.user == users.get_current_user()).fetch()

  if result:
    app_user = result[0]
  else:
    app_user = AppUser(user=users.get_current_user(),
                       email=users.get_current_user().email())
    app_user.put()

  return app_user 
Example 13
Project: googleads-python-lib   Author: googleads   File: ndb_handler.py    License: Apache License 2.0 6 votes vote down vote up
def UpdateUserCredentials(client_id, client_secret, refresh_token,
                          adwords_manager_cid, developer_token):
  """Update the credentials associated with application user.

  Args:
    client_id: str Client Id retrieved from the developer's console.
    client_secret: str Client Secret retrieved from the developer's console.
    refresh_token: str Refresh token generated with the above client id/secret.
    adwords_manager_cid: str Customer Id for the AdWords manager account.
    developer_token: str Developer Token for the AdWords account.
  """
  app_user = AppUser.query(AppUser.user == users.get_current_user()).fetch()[0]

  app_user.client_id = client_id
  app_user.client_secret = client_secret
  app_user.refresh_token = refresh_token
  app_user.adwords_manager_cid = adwords_manager_cid
  app_user.developer_token = developer_token

  app_user.put() 
Example 14
Project: python-docs-samples   Author: GoogleCloudPlatform   File: firetactoe_test.py    License: Apache License 2.0 6 votes vote down vote up
def test_opened(app, monkeypatch):
    with mock.patch(
        "google.auth.transport.requests.AuthorizedSession.request", autospec=True
    ) as auth_session:
        data = {'access_token': '123'}
        auth_session.return_value = MockResponse(data, http_client.OK)
        firetactoe.Game(id='razem', userX=users.get_current_user()).put()

        app.post('/opened?g=razem', status=200)

        auth_session.assert_called_once_with(
            mock.ANY,  # AuthorizedSession object
            method="PATCH",
            url="http://firebase.com/test-db-url/channels/38razem.json",
            body='{"winner": null, "userX": "38", "moveX": null, "winningBoard": null, "board": null, "userO": null}',
            data=None,
        ) 
Example 15
Project: python-docs-samples   Author: GoogleCloudPlatform   File: firetactoe_test.py    License: Apache License 2.0 6 votes vote down vote up
def test_move(app, monkeypatch):
    with mock.patch(
        "google.auth.transport.requests.AuthorizedSession.request", autospec=True
    ) as auth_session:
        data = {'access_token': '123'}
        auth_session.return_value = MockResponse(data, http_client.OK)

        firetactoe.Game(
            id='razem', userX=users.get_current_user(), board=9*' ',
            moveX=True).put()

        app.post('/move?g=razem', {'i': 0}, status=200)

        game = ndb.Key('Game', 'razem').get()
        assert game.board == 'X' + (8 * ' ')

        auth_session.assert_called_once_with(
            mock.ANY,  # AuthorizedSession object
            method="PATCH",
            url="http://firebase.com/test-db-url/channels/38razem.json",
            body='{"winner": null, "userX": "38", "moveX": false, "winningBoard": null, "board": "X        ", "userO": null}',
            data=None,
        ) 
Example 16
Project: loaner   Author: google   File: frontend.py    License: Apache License 2.0 5 votes vote down vote up
def get(self, path):
    user = users.get_current_user()
    if not user:
      self.response.status = httplib.UNAUTHORIZED
      self.response.out.write('You must be logged in to access this app.')
      return
    elif user.email().split('@')[1] not in constants.APP_DOMAINS:
      self.response.status = httplib.FORBIDDEN
      self.response.out.write('Forbidden.')
      return

    if path == '/application.js':
      self._serve_frontend_javascript()
      return

    if self.bootstrap_completed or re.match(
        r'^/(bootstrap|authorization)', path):
      self._serve_frontend()
    else:
      self._sync_roles_if_necessary()
      # Re-checks if the bootstrap status did not change since the handler was
      # first loaded.
      self.bootstrap_completed = bootstrap.is_bootstrap_completed()
      if self.bootstrap_completed:
        self.redirect(path)
      else:
        datastore_user = user_model.User.get_user(user.email())
        if (permissions.Permissions.BOOTSTRAP in
            datastore_user.get_permissions()):
          self.redirect(BOOTSTRAP_URL)
        else:
          self.redirect('/maintenance') 
Example 17
Project: tornado-zh   Author: tao12345666333   File: blog.py    License: MIT License 5 votes vote down vote up
def get_current_user(self):
        user = users.get_current_user()
        if user: user.administrator = users.is_current_user_admin()
        return user 
Example 18
Project: gae-secure-scaffold-python   Author: google   File: handlers.py    License: Apache License 2.0 5 votes vote down vote up
def requires_auth(f):
  """A decorator that requires a currently logged in user."""
  @functools.wraps(f)
  def wrapper(self, *args, **kwargs):
    if not users.get_current_user():
      self.DenyAccess()
    else:
      return f(self, *args, **kwargs)
  return wrapper 
Example 19
Project: gae-secure-scaffold-python   Author: google   File: handlers.py    License: Apache License 2.0 5 votes vote down vote up
def current_user(self):
    return users.get_current_user() 
Example 20
Project: browserscope   Author: elsigh   File: decorators.py    License: Apache License 2.0 5 votes vote down vote up
def login_required(func):
  """Tests to make sure the current user is an admin."""
  def _wrapper(request, *args, **kw):
    if request.session.get('api_key_override'):
      return func(request, *args, **kw)

    user = users.get_current_user()
    if user:
      return func(request, *args, **kw)
    else:
      return HttpResponseRedirect(
          users.create_login_url(request.get_full_path()))
  return _wrapper 
Example 21
Project: browserscope   Author: elsigh   File: decorators.py    License: Apache License 2.0 5 votes vote down vote up
def admin_required(func):
  """Tests to make sure the current user is an admin."""
  def _wrapper(request, *args, **kw):
    user = users.get_current_user()
    if user:
      if users.is_current_user_admin():
        return func(request, *args, **kw)
      else:
        return HttpResponse('You need to be an admin. <a href="%s">login</a>.'
                            % users.create_login_url(request.get_full_path()))
    else:
      return HttpResponseRedirect(
          users.create_login_url(request.get_full_path()))
  return _wrapper 
Example 22
Project: browserscope   Author: elsigh   File: user_tests.py    License: Apache License 2.0 5 votes vote down vote up
def Settings(request):
  if request.POST:
    current_user = users.get_current_user()
    u = models.user_test.User.get_or_insert(current_user.user_id())
    u.email = request.POST.get('email', current_user.email())
    u.save()
    return http.HttpResponseRedirect('/user/settings')

  # Regular GET.
  current_user = users.get_current_user()
  user = models.user_test.User.get_or_insert(
      current_user.user_id(),
      email=current_user.email())
  tests = db.Query(models.user_test.Test)
  tests.filter('user', user)
  # Only admins can see deleted tests.
  if not users.is_current_user_admin():
    tests.filter('deleted', False)
  tests.order('-created')
  if tests.count() == 0:
    tests = None

  params = {
    'api_key': user.key().name(),
    'tests': tests,
    'csrf_token': request.session.get('csrf_token')
  }
  return util.Render(request, 'user_settings.html', params)


# Decorators are inherited by TestEdit 
Example 23
Project: browserscope   Author: elsigh   File: user_tests.py    License: Apache License 2.0 5 votes vote down vote up
def WebPagetest(request, key):
  """Sends an API request to run one's test page on WebPagetest.org."""
  test = models.user_test.Test.get_mem(key)
  if not test:
    msg = 'No test was found with test_key %s.' % key
    return http.HttpResponseServerError(msg)

  current_user = users.get_current_user()
  if (test.user.key().name() != current_user.user_id() and not
        users.is_current_user_admin()):
      return http.HttpResponse('You can\'t play with tests you don\'t own')

  # Help users autorun their tests by adding autorun=1 to the test url.
  test_url_parts = list(urlparse.urlparse(test.url))
  test_url_query = dict(cgi.parse_qsl(test_url_parts[4]))
  test_url_query.update({'autorun': '1'})
  test_url_parts[4] = urllib.urlencode(test_url_query)
  test_url = urlparse.urlunparse(test_url_parts)

  # TODO(elsigh): callback url.
  webpagetest_url = ('%s&url=%s&notify=%s' %
                     (WEBPAGETEST_URL, test_url,
                      urllib.quote('elsigh@gmail.com')))

  webpagetests = {}
  # See http://goo.gl/EfK1r for WebPagetest instructions.
  for location in WEBPAGETEST_LOCATIONS:
    url = '%s&location=%s' % (webpagetest_url, location)
    response = urlfetch.fetch(url)
    json = simplejson.loads(response.content)
    webpagetests[location] = json

  params = {
    'test': test,
    'webpagetests': webpagetests
  }
  return util.Render(request, 'user_test_webpagetest.html', params) 
Example 24
Project: browserscope   Author: elsigh   File: test_user_tests.py    License: Apache License 2.0 5 votes vote down vote up
def testUser(self):
    current_user = users.get_current_user()
    u = models.user_test.User.get_or_insert(current_user.user_id())
    u.email = current_user.email()
    u.save()

    user_q = models.user_test.User.get_by_key_name(current_user.user_id())
    self.assertTrue(user_q.email, current_user.email()) 
Example 25
Project: browserscope   Author: elsigh   File: test_user_tests.py    License: Apache License 2.0 5 votes vote down vote up
def testGetTestSetFromResultStringThrowsOnLongKeys(self):
    current_user = users.get_current_user()
    u = models.user_test.User.get_or_insert(current_user.user_id())
    test = models.user_test.Test(user=u, name='Fake Test',
                                 url='http://fakeurl.com/test.html',
                                 description='stuff')
    test.save()

    too_long_key_name = repeat_to_length('x',
                                         models.user_test.MAX_KEY_LENGTH + 1)
    results_str = 'test_1=0,test_2=1,%s=2' % too_long_key_name
    test_set_category = 'usertest_%s' % test.key()
    self.assertRaises(models.user_test.KeyTooLong,
        models.user_test.Test.get_test_set_from_results_str,
        test_set_category, results_str) 
Example 26
Project: browserscope   Author: elsigh   File: test_user_tests.py    License: Apache License 2.0 5 votes vote down vote up
def setUp(self):
    self.client = Client()
    current_user = users.get_current_user()
    u = models.user_test.User.get_or_insert(current_user.user_id())
    u.email = current_user.email()
    u.save()
    meta = models.user_test.TestMeta().save()
    self.test = models.user_test.Test(user=u, name='Fake Test',
                                      url='http://fakeurl.com/test.html',
                                      description='stuff', sandboxid='sand',
                                      meta=meta)
    self.test.save() 
Example 27
Project: browserscope   Author: elsigh   File: test_user_tests.py    License: Apache License 2.0 5 votes vote down vote up
def setUp(self):
    self.client = Client()

    current_user = users.get_current_user()
    u = models.user_test.User.get_or_insert(current_user.user_id())
    u.email = current_user.email()
    u.save()

    test = models.user_test.Test(user=u, name='Fake Test',
                                 url='http://fakeurl.com/test.html',
                                 description='stuff')
    # Because GAEUnit won't run the deferred taskqueue properly.
    test.test_keys = ['apple', 'coconut', 'banana']
    test.save()
    self.test = test

    self.test_set = mock_data.MockUserTestSet()
    self.test_set.user_test_category = test.get_memcache_keyname()
    #all_test_sets.AddTestSet(self.test_set)

    params = {
      'category': self.test.get_memcache_keyname(),
      'results': 'apple=1,banana=2,coconut=4',
    }
    csrf_token = self.client.get('/get_csrf').content
    params['csrf_token'] = csrf_token
    response = self.client.get('/beacon', params, **mock_data.UNIT_TEST_UA)
    self.assertEqual(204, response.status_code) 
Example 28
Project: browserscope   Author: elsigh   File: decorators.py    License: Apache License 2.0 5 votes vote down vote up
def admin_required(func):
  """Tests to make sure the current user is an admin."""
  def _wrapper(request, *args, **kw):
    user = users.get_current_user()
    if user:
      if users.is_current_user_admin():
        return func(request, *args, **kw)
      else:
        return HttpResponse('You need to be an admin. <a href="%s">login</a>.'
                            % users.create_login_url(request.get_full_path()))
    else:
      return HttpResponseRedirect(
          users.create_login_url(request.get_full_path()))
  return _wrapper


# TRUSTED_TESTERS = ['elsigh', 'stevesoudersorg', 'steve.lamm', 'annie.sullivan',
#                    'jeresig', 'kellegous', 'mnotting', 'storey.david',
#                    'test@example.com']
# def trusted_tester_required(func):
#   """Tests to make sure the current user is an admin."""
#   def _wrapper(request, *args, **kw):
#     user = users.get_current_user()
#     logging.info('User: %s' % user.user_id())
#     if user and user in TRUSTED_TESTERS:
#       return func(request, *args, **kw)
#     else:
#       return HttpResponse('You need to be logged in. <a href="%s">login</a>.'
#                           % users.create_login_url(request.get_full_path()))
#   return _wrapper 
Example 29
Project: browserscope   Author: elsigh   File: views.py    License: Apache License 2.0 5 votes vote down vote up
def Render(request, template, params={}):
  """Wrapper function to render templates with global and category vars."""
  params['app_title'] = settings.APP_TITLE
  params['version_id'] = os.environ['CURRENT_VERSION_ID']
  params['build'] = settings.BUILD
  params['epoch'] = int(time.time())
  params['request_path'] = request.get_full_path()
  params['request_path_lastbit'] = re.sub('^.+\/([^\/]+$)', '\\1', request.path)
  params['current_ua_string'] = request.META['HTTP_USER_AGENT']
  params['current_ua'] = user_agent_parser.PrettyUserAgent(params['current_ua_string'])
  params['chromeframe_enabled'] = request.COOKIES.get(
      'browserscope-chromeframe-enabled', '0')
  params['app_categories'] = []
  params['is_admin'] = users.is_current_user_admin()

  current_user = users.get_current_user()
  if current_user:
    params['user_id'] = current_user.user_id()
  else:
    params['user_id'] = None
  params['user'] = current_user

  params['sign_in'] = users.create_login_url(request.get_full_path())
  params['sign_out'] = users.create_logout_url('/')

  return shortcuts.render_to_response(template, params) 
Example 30
Project: github-stats   Author: lipis   File: gae.py    License: MIT License 5 votes vote down vote up
def gae_authorized():
  gae_user = users.get_current_user()
  if gae_user is None:
    flask.flash('You denied the request to sign in.')
    return flask.redirect(util.get_next_url())

  user_db = retrieve_user_from_gae(gae_user)
  return auth.signin_user_db(user_db)