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

The following are 30 code examples of google.appengine.api.users.get_current_user(). 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 also want to check out all available functions/classes of the module google.appengine.api.users , or try the search function .
Example #1
Source File: firetactoe_test.py    From python-docs-samples with 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 #2
Source File: test_user_tests.py    From browserscope with 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
Source File: user.py    From loaner with 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 #4
Source File: test_db_datastore.py    From locality-sensitive-hashing with 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 #5
Source File: peer_belt_driver.py    From locality-sensitive-hashing with 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 #6
Source File: blobs.py    From locality-sensitive-hashing with 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 #7
Source File: mr_main.py    From locality-sensitive-hashing with 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 #8
Source File: dschat.py    From dschat with 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 #9
Source File: frontend_views.py    From googleapps-message-recall with 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 #10
Source File: main.py    From datastore-ndb-python with 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 #11
Source File: main.py    From datastore-ndb-python with 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 #12
Source File: update_credentials_view.py    From googleads-python-lib with 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 #13
Source File: ndb_handler.py    From googleads-python-lib with 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 #14
Source File: ndb_handler.py    From googleads-python-lib with 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 #15
Source File: firetactoe_test.py    From python-docs-samples with 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 #16
Source File: show_credentials_view.py    From googleads-python-lib with Apache License 2.0 5 votes vote down vote up
def get(self):
    """Handle get request."""
    template_values = {
        'back_url': '/',
        'back_msg': 'View Accounts',
        'logout_url': users.create_logout_url('/'),
        'user_nickname': users.get_current_user().nickname()
    }
    try:
      try:
        app_user = InitUser()

        template_values['email'] = app_user.email if app_user.email else ''
        template_values['client_id'] = (app_user.client_id if app_user.client_id
                                        else '')
        template_values['client_secret'] = (app_user.client_secret if
                                            app_user.client_secret else '')
        template_values['refresh_token'] = (app_user.refresh_token if
                                            app_user.refresh_token else '')
        template_values['adwords_manager_cid'] = (
            app_user.adwords_manager_cid if app_user.adwords_manager_cid else ''
        )
        template_values['dev_token'] = (app_user.developer_token if
                                        app_user.developer_token else '')
      except Exception as e:
        template_values['error'] = str(e)
    finally:
      # Use template to write output to the page.
      path = os.path.join(os.path.dirname(__file__),
                          '../templates/show_credentials.html')
      self.response.out.write(template.render(path, template_values)) 
Example #17
Source File: main.py    From datastore-ndb-python with Apache License 2.0 5 votes vote down vote up
def get(self):
    nickname = 'Anonymous'
    user = users.get_current_user()
    if user is not None:
      nickname = yield get_nickname(user.user_id())
    values = {'nickname': nickname,
              'login': users.create_login_url('/home'),
              'logout': users.create_logout_url('/home'),
              }
    self.response.out.write(HOME_PAGE % values)
    qry, options = self._make_query()
    pairs = yield qry.map_async(self._hp_callback, options=options)
    for key, text in pairs:
      self.response.out.write(text) 
Example #18
Source File: users.py    From googleapps-message-recall with Apache License 2.0 5 votes vote down vote up
def login_required(handler_method):
    """A decorator to require that a user be logged in to access a handler.

    To use it, decorate your get() method like this::

        @login_required
        def get(self):
            user = users.get_current_user(self)
            self.response.out.write('Hello, ' + user.nickname())

    We will redirect to a login page if the user is not logged in. We always
    redirect to the request URI, and Google Accounts only redirects back as
    a GET request, so this should not be used for POSTs.
    """
    def check_login(self, *args, **kwargs):
        if self.request.method != 'GET':
            self.abort(400, detail='The login_required decorator '
                'can only be used for GET requests.')

        user = users.get_current_user()
        if not user:
            return self.redirect(users.create_login_url(self.request.url))
        else:
            handler_method(self, *args, **kwargs)

    return check_login 
Example #19
Source File: appengine.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def oauth_aware(self, method):
        """Decorator that sets up for OAuth 2.0 dance, but doesn't do it.

        Does all the setup for the OAuth dance, but doesn't initiate it.
        This decorator is useful if you want to create a page that knows
        whether or not the user has granted access to this application.
        From within a method decorated with @oauth_aware the has_credentials()
        and authorize_url() methods can be called.

        Args:
            method: callable, to be decorated method of a webapp.RequestHandler
                    instance.
        """

        def setup_oauth(request_handler, *args, **kwargs):
            if self._in_error:
                self._display_error_message(request_handler)
                return

            user = users.get_current_user()
            # Don't use @login_decorator as this could be used in a
            # POST request.
            if not user:
                request_handler.redirect(users.create_login_url(
                    request_handler.request.uri))
                return

            self._create_flow(request_handler)

            self.flow.params['state'] = _build_state_value(request_handler,
                                                           user)
            self.credentials = self._storage_class(
                self._credentials_class, None,
                self._credentials_property_name, user=user).get()
            try:
                resp = method(request_handler, *args, **kwargs)
            finally:
                self.credentials = None
            return resp
        return setup_oauth 
Example #20
Source File: appengine.py    From googleapps-message-recall with Apache License 2.0 5 votes vote down vote up
def oauth_aware(self, method):
    """Decorator that sets up for OAuth 2.0 dance, but doesn't do it.

    Does all the setup for the OAuth dance, but doesn't initiate it.
    This decorator is useful if you want to create a page that knows
    whether or not the user has granted access to this application.
    From within a method decorated with @oauth_aware the has_credentials()
    and authorize_url() methods can be called.

    Args:
      method: callable, to be decorated method of a webapp.RequestHandler
        instance.
    """

    def setup_oauth(request_handler, *args, **kwargs):
      if self._in_error:
        self._display_error_message(request_handler)
        return

      user = users.get_current_user()
      # Don't use @login_decorator as this could be used in a POST request.
      if not user:
        request_handler.redirect(users.create_login_url(
            request_handler.request.uri))
        return

      self._create_flow(request_handler)

      self.flow.params['state'] = _build_state_value(request_handler, user)
      self.credentials = self._storage_class(
          self._credentials_class, None,
          self._credentials_property_name, user=user).get()
      try:
        resp = method(request_handler, *args, **kwargs)
      finally:
        self.credentials = None
      return resp
    return setup_oauth 
Example #21
Source File: user_tests.py    From browserscope with 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 #22
Source File: dschat.py    From dschat with MIT License 5 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

        # Create a Message and store it in the DataStore.
        #
        # We set the same parent key on the 'Message' to ensure each Message is
        # in the same entity group. Queries across the single entity group will
        # be consistent. However, the write rate to a single entity group should
        # be limited to ~1/second.
        message = Message(parent=messages_key())

        topic = self.request.get('topic', DEFAULT_TOPIC)
        message.topic = topic
        message.author = Author(
                identity=user.user_id(),
                nickname=user.nickname(),
                email=user.email())
        message.content = self.request.get('content')
        message.date = datetime.datetime.now()
        message_key = message.put()

        # Index the message so it is available for future searches:
        messageindex.add(message_key.urlsafe(), message)

        # Now that we've recorded the message in the DataStore, broadcast it to
        # all open clients.
        broadcast = MessagesBroadcast([message])
        broadcast.send() 
Example #23
Source File: auth.py    From jacs with Apache License 2.0 5 votes vote down vote up
def authorize(action, table):

    oauth_user = None
    oauth_admin = None
    try:
        oauth_user = oauth.get_current_user('https://www.googleapis.com/auth/plus.me')
        oauth_admin = oauth.is_current_user_admin('https://www.googleapis.com/auth/plus.me')
    except oauth.OAuthRequestError, e:
        logging.debug("No valid oauth credentials were received: %s" % e) 
Example #24
Source File: user_tests.py    From browserscope with 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 #25
Source File: decorators.py    From browserscope with 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 #26
Source File: blog.py    From honeything with GNU General Public License v3.0 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 #27
Source File: recipe-577235.py    From code with MIT License 5 votes vote down vote up
def user(method):
    " Prefix the user to method call args. Must have ACSID cookie to log in.  "
    @functools.wraps(method)
    def user_deco(self, *args):
        user = users.get_current_user()
        assert isinstance(user, users.User), "%r" % user
        return method(self, user, *args)              
    return user_deco 
Example #28
Source File: recipe-577235.py    From code with MIT License 5 votes vote down vote up
def http_basic_auth(method):
    " Prefix user to method call. Authenticates using HTTP Basic Authorization.  "
    @functools.wraps(method)
    def http_basic_auth_deco(self, *args):
        user = users.get_current_user()
        if not user:
            basic_auth = self.request.headers.get('Authorization')
            if not basic_auth:
                logger.debug("Request does not carry auth.")
                self.fail_basic_auth()
                return
            username, password = '', ''
            try:
                user_info = base64.decodestring(basic_auth[6:])
                username, password = user_info.split(':')
            except:
                raise Exception, "Could not parse HTTP Authorization. "
            cookie = None
            try:
                cookie = gauth.do_auth(MY_APPSPOT, username, password, 
                        dev=self.is_devhost())
            except gauth.AuthError, e:
                logger.info("Got a failed login attempt for Google Accounts %r", 
                        username)
                self.fail_auth()
                return
            self.response.set_status(302, 'Use Cookie')
            # Give ACSID cookie to client
            self.response.headers['Set-Cookie'] = cookie
            # Then redirect so clients logs into user-framework
            # XXX: dont use internal redir b/c it resets self.response
            self.response.headers['Location'] = self.request.path
            return
        elif 'Authorization' in self.request.headers:
            # FIXME: ignore or act on (new?) credentials
            assert 'USER_ID' in os.environ
            # XXX: just delete and ignore
            del self.request.headers['Authorization']
            del os.environ['HTTP_AUTHORIZATION']
            # XXX: this may happen once if a client retries auth on 302
            logger.warning("Ignored HTTP Authorization.") 
Example #29
Source File: recipe-577780.py    From code with MIT License 5 votes vote down vote up
def get(self):
        user = users.get_current_user()
        
        if user:
            welcome = ("Welcome, %s! (<a href='%s'>Sing out</a>)"
                        % (user.nickname(), users.create_logout_url('/')))
        else:
            welcome = ("<a href='%s'>Sign in or Register</a>"
                        % users.create_login_url('/'))
        
        self.response.out.write("<html><head><title>Web App Title</title></head><body>%s</body></html>"
                                % welcome) 
Example #30
Source File: main.py    From datastore-ndb-python with Apache License 2.0 5 votes vote down vote up
def post(self):
    # TODO: XSRF protection.
    body = self.request.get('body', '').strip()
    if body:
      userid = None
      user = users.get_current_user()
      if user:
        userid = user.user_id()
      message = Message(body=body, when=time.time(), userid=userid)
      yield message.put_async()
    self.redirect('/home')