Python google.appengine.api.users 模块,get_current_user() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用google.appengine.api.users.get_current_user()

项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def save_auth_tokens(token_dict, user=None):
  """Associates the tokens with the current user and writes to the datastore.

  If there us no current user, the tokens are not written and this function
  returns None.

  Returns:
    The key of the datastore entity containing the user's tokens, or None if
    there was no current user.
  """
  if user is None:
    user = users.get_current_user()
  if user is None:
    return None
  memcache.set('gdata_pickled_tokens:%s' % user, pickle.dumps(token_dict))
  user_tokens = TokenCollection.all().filter('user =', user).get()
  if user_tokens:
    user_tokens.pickled_tokens = pickle.dumps(token_dict)
    return user_tokens.put()
  else:
    user_tokens = TokenCollection(
        user=user, 
        pickled_tokens=pickle.dumps(token_dict))
    return user_tokens.put()
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def load_auth_tokens(user=None):
  """Reads a dictionary of the current user's tokens from the datastore.

  If there is no current user (a user is not signed in to the app) or the user
  does not have any tokens, an empty dictionary is returned.
  """
  if user is None:
    user = users.get_current_user()
  if user is None:
    return {}
  pickled_tokens = memcache.get('gdata_pickled_tokens:%s' % user)
  if pickled_tokens:
    return pickle.loads(pickled_tokens)
  user_tokens = TokenCollection.all().filter('user =', user).get()
  if user_tokens:
    memcache.set('gdata_pickled_tokens:%s' % user, user_tokens.pickled_tokens)
    return pickle.loads(user_tokens.pickled_tokens)
  return {}
项目:arithmancer    作者:google    | 项目源码 | 文件源码
def GetUserByAuth():
  """Returns current users profile."""
  user_key = users.get_current_user().user_id()
  user_key = ndb.Key('Profile', user_key)
  profile = user_key.get()
  for ledger in profile.user_ledger:
    try:
      price = GetPriceByPredictionId(ledger.prediction_id)
      ledger.value = math.fabs((price * ledger.contract_one) - (
          price * ledger.contract_two))
      ledger.prediction_statement = ndb.Key(
          urlsafe=ledger.prediction_id).get().statement
    except:
      ledger.value = 404
      ledger.prediction_statement = 'ERROR'
  return render_template('profile.html', profile=profile)
项目:arithmancer    作者:google    | 项目源码 | 文件源码
def SellStake():
  user_id = users.get_current_user().user_id()
  user_key = ndb.Key('Profile', user_id)
  current_user = user_key.get()
  prediction_key = ndb.Key(urlsafe=request.form['prediction_id'])
  prediction = prediction_key.get()
  portfolio = GetUserPortfolioByAuth(request.form['prediction_id'])
  for ledger in portfolio:
      if ledger.contract_one > 0:
          contract = 'CONTRACT_ONE'
          quantity = ledger.contract_one
      else:
          contract = 'CONTRACT_TWO'
          quantity = ledger.contract_two
  trade = Trade(
      prediction_id=prediction_key,
      user_id=user_key,
      direction='SELL',
      contract=contract,
      quantity=float(quantity))
  err = CreateTradeAction(prediction, current_user, trade)
  if err != 'error':
      flash('You sold your stake!')
  return redirect('/users/me')
项目:Intranet-Penetration    作者:yuxiaokui    | 项目源码 | 文件源码
def main():
  """CGI-style request handler to dump the configuration.

  Put this in your app.yaml to enable (you can pick any URL):

  - url: /lib_config
    script: $PYTHON_LIB/google/appengine/api/lib_config.py

  Note: unless you are using the SDK, you must be admin.
  """
  if not os.getenv('SERVER_SOFTWARE', '').startswith('Dev'):
    from google.appengine.api import users
    if not users.is_current_user_admin():
      if users.get_current_user() is None:
        print 'Status: 302'
        print 'Location:', users.create_login_url(os.getenv('PATH_INFO', ''))
      else:
        print 'Status: 403'
        print
        print 'Forbidden'
      return

  print 'Content-type: text/plain'
  print
  _default_registry._dump()
项目:MKFQ    作者:maojingios    | 项目源码 | 文件源码
def main():
  """CGI-style request handler to dump the configuration.

  Put this in your app.yaml to enable (you can pick any URL):

  - url: /lib_config
    script: $PYTHON_LIB/google/appengine/api/lib_config.py

  Note: unless you are using the SDK, you must be admin.
  """
  if not os.getenv('SERVER_SOFTWARE', '').startswith('Dev'):
    from google.appengine.api import users
    if not users.is_current_user_admin():
      if users.get_current_user() is None:
        print 'Status: 302'
        print 'Location:', users.create_login_url(os.getenv('PATH_INFO', ''))
      else:
        print 'Status: 403'
        print
        print 'Forbidden'
      return

  print 'Content-type: text/plain'
  print
  _default_registry._dump()
项目:tichu-tournament    作者:aragos    | 项目源码 | 文件源码
def _CheckUserAllowedToSeeMovementMaybeSetStatus(self, tourney, player_pair):
    error  = "Forbidden User"
    user = users.get_current_user()
    if user and tourney.owner_id == user.user_id():
      return True
    pair_id = GetPairIdFromRequest(self.request)
    if not pair_id:
      SetErrorStatus(self.response, 403, error,
                     "User does not own tournament and is not authenticated " +
                     "with a pair code to see this movement")
      return False
    if pair_id != player_pair.id:
      SetErrorStatus(self.response, 403, error,
                     "User does not own tournament and is authenticated with " +
                     "the wrong code for pair {}".format(player_pair.pair_no))
      return False
    return True
项目:tichu-tournament    作者:aragos    | 项目源码 | 文件源码
def get(self, id):
    tourney = GetTourneyWithIdAndMaybeReturnStatus(self.response, id)
    if not tourney:
      return

    if not CheckUserOwnsTournamentAndMaybeReturnStatus(self.response,
        users.get_current_user(), tourney):
      return
    boards = ReadJSONInput(tourney.GetScoredHandList())
    max_rounds = GetMaxRounds(boards)
    summaries = Calculate(boards, max_rounds)
    mp_summaries = summaries
    ap_summaries = summaries
    boards.sort(key=lambda bs : bs._board_no, reverse = False)
    wb = WriteResultsToXlsx(max_rounds, mp_summaries, ap_summaries, boards,
                            name_list=self._GetPlayerListForTourney(tourney))
    self.response.out.write(OutputWorkbookAsBytesIO(wb).getvalue())
    self.response.headers['Content-Type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    self.response.headers['Content-disposition'] = str('attachment; filename=' + 
        tourney.name + 'TournamentResults.xlsx')
    self.response.headers['Content-Transfer-Encoding'] = 'Binary'
    self.response.set_status(200)
项目:tichu-tournament    作者:aragos    | 项目源码 | 文件源码
def get(self, id):
    tourney = GetTourneyWithIdAndMaybeReturnStatus(self.response, id)
    if not tourney:
      return

    if not CheckUserOwnsTournamentAndMaybeReturnStatus(
        self.response,
        users.get_current_user(),
        tourney):
      return

    boards = tourney.GetBoards()

    boardgenerator.RenderToIo(boards, self.response.out)

    self.response.headers['Content-Type'] = 'application/pdf'
    self.response.headers['Content-Disposition'] = (
      'attachment; filename=%sBoards.pdf' % str(urllib.quote(tourney.name)))
    self.response.set_status(200)
项目:xxNet    作者:drzorm    | 项目源码 | 文件源码
def main():
  """CGI-style request handler to dump the configuration.

  Put this in your app.yaml to enable (you can pick any URL):

  - url: /lib_config
    script: $PYTHON_LIB/google/appengine/api/lib_config.py

  Note: unless you are using the SDK, you must be admin.
  """
  if not os.getenv('SERVER_SOFTWARE', '').startswith('Dev'):
    from google.appengine.api import users
    if not users.is_current_user_admin():
      if users.get_current_user() is None:
        print 'Status: 302'
        print 'Location:', users.create_login_url(os.getenv('PATH_INFO', ''))
      else:
        print 'Status: 403'
        print
        print 'Forbidden'
      return

  print 'Content-type: text/plain'
  print
  _default_registry._dump()
项目:gae-sports-data    作者:jnguyen-ca    | 项目源码 | 文件源码
def sys_processor():
    def _get_app_var(key):
        if key in constants.APPVAR_DISPLAY_LIST:
            return models.ApplicationVariable.get_app_var(key)
        return None

    def _is_logged_in():
        if users.get_current_user():
            return True
        return False

    def _is_admin():
        return users.is_current_user_admin()

    def _login_link(endpoint):
        return users.create_login_url(endpoint)

    return dict(get_app_var=_get_app_var,
                is_logged_in=_is_logged_in,
                is_admin=_is_admin,
                login_link=_login_link)
项目:gdata-python3    作者:dvska    | 项目源码 | 文件源码
def save_auth_tokens(token_dict, user=None):
    """Associates the tokens with the current user and writes to the datastore.

    If there us no current user, the tokens are not written and this function
    returns None.

    Returns:
      The key of the datastore entity containing the user's tokens, or None if
      there was no current user.
    """
    if user is None:
        user = users.get_current_user()
    if user is None:
        return None
    memcache.set('gdata_pickled_tokens:%s' % user, pickle.dumps(token_dict))
    user_tokens = TokenCollection.all().filter('user =', user).get()
    if user_tokens:
        user_tokens.pickled_tokens = pickle.dumps(token_dict)
        return user_tokens.put()
    else:
        user_tokens = TokenCollection(
            user=user,
            pickled_tokens=pickle.dumps(token_dict))
        return user_tokens.put()
项目:gdata-python3    作者:dvska    | 项目源码 | 文件源码
def load_auth_tokens(user=None):
    """Reads a dictionary of the current user's tokens from the datastore.

    If there is no current user (a user is not signed in to the app) or the user
    does not have any tokens, an empty dictionary is returned.
    """
    if user is None:
        user = users.get_current_user()
    if user is None:
        return {}
    pickled_tokens = memcache.get('gdata_pickled_tokens:%s' % user)
    if pickled_tokens:
        return pickle.loads(pickled_tokens)
    user_tokens = TokenCollection.all().filter('user =', user).get()
    if user_tokens:
        memcache.set('gdata_pickled_tokens:%s' % user, user_tokens.pickled_tokens)
        return pickle.loads(user_tokens.pickled_tokens)
    return {}
项目:montage    作者:storyful    | 项目源码 | 文件源码
def dispatch(self, request, **kwargs):
        """
            Override disptach to validate export format and set user.

            While generally not good practice, we set CSRF as exempt
            because no POST requests handled by this view modify any
            server side data.
        """
        self.user = users.get_current_user()
        self.format = request.POST.get('format', 'csv').lower()
        eventbus.publish_appevent(
            kind=EventKind.USEREXPORTEDVIDEOS,
            object_id=request.user.pk,
            project_id=kwargs['project_id'],
            user=request.user,
            meta=self.format
        )

        if self.format not in ('csv', 'kml'):
            return HttpResponseBadRequest("Format not valid")

        return super(BaseExportView, self).dispatch(request, **kwargs)
项目:appbackendapi    作者:codesdk    | 项目源码 | 文件源码
def post(self):
        # We set the same parent key on the 'Greeting' to ensure each greeting
        # is in the same entity group. Queries across the single entity group
        # are strongly consistent. However, the write rate to a single entity
        # group is limited to ~1/second.
        guestbook_name = self.request.get('guestbook_name')
        greeting = Greeting(parent=guestbook_key(guestbook_name))

        if users.get_current_user():
            greeting.author = users.get_current_user().nickname()

        greeting.content = self.request.get('content')
        greeting.put()
        memcache.delete('{}:greetings'.format(guestbook_name))
        self.redirect('/?' +
                      urllib.urlencode({'guestbook_name': guestbook_name}))
项目:appbackendapi    作者:codesdk    | 项目源码 | 文件源码
def post(self):
        try:
            upload = self.get_uploads()[0]
            user_photo = UserPhoto(
                user=users.get_current_user().user_id(),
                blob_key=upload.key())
            user_photo.put()

            self.redirect('/view_photo/%s' % upload.key())

        except:
            self.error(500)
# [END upload_handler]


# [START download_handler]
项目:appbackendapi    作者:codesdk    | 项目源码 | 文件源码
def post(self):
        guestbook_name = self.request.get('guestbook_name')
        greeting = Greeting(parent=guestbook_key(guestbook_name))

        if users.get_current_user():
            greeting.author = users.get_current_user().nickname()

        greeting.content = self.request.get('content')

        # [START sign_handler_1]
        avatar = self.request.get('img')
        # [END sign_handler_1]
        # [START transform]
        avatar = images.resize(avatar, 32, 32)
        # [END transform]
        # [START sign_handler_2]
        greeting.avatar = avatar
        greeting.put()
        # [END sign_handler_1]

        self.redirect('/?' + urllib.urlencode(
            {'guestbook_name': guestbook_name}))
# [END sign_handler]
项目:Deploy_XXNET_Server    作者:jzp820927    | 项目源码 | 文件源码
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):
    if self.request.method != 'GET':
      raise webapp.Error('The check_login decorator can only be used for GET '
                         'requests')
    user = users.get_current_user()
    if not user:
      self.redirect(users.create_login_url(self.request.uri))
      return
    else:
      handler_method(self, *args)
  return check_login
项目:Deploy_XXNET_Server    作者:jzp820927    | 项目源码 | 文件源码
def main():
  """CGI-style request handler to dump the configuration.

  Put this in your app.yaml to enable (you can pick any URL):

  - url: /lib_config
    script: $PYTHON_LIB/google/appengine/api/lib_config.py

  Note: unless you are using the SDK, you must be admin.
  """
  if not os.getenv('SERVER_SOFTWARE', '').startswith('Dev'):
    from google.appengine.api import users
    if not users.is_current_user_admin():
      if users.get_current_user() is None:
        print 'Status: 302'
        print 'Location:', users.create_login_url(os.getenv('PATH_INFO', ''))
      else:
        print 'Status: 403'
        print
        print 'Forbidden'
      return

  print 'Content-type: text/plain'
  print
  _default_registry._dump()
项目:GAMADV-X    作者:taers232c    | 项目源码 | 文件源码
def save_auth_tokens(token_dict, user=None):
  """Associates the tokens with the current user and writes to the datastore.

  If there us no current user, the tokens are not written and this function
  returns None.

  Returns:
    The key of the datastore entity containing the user's tokens, or None if
    there was no current user.
  """
  if user is None:
    user = users.get_current_user()
  if user is None:
    return None
  memcache.set('gdata_pickled_tokens:%s' % user, pickle.dumps(token_dict))
  user_tokens = TokenCollection.all().filter('user =', user).get()
  if user_tokens:
    user_tokens.pickled_tokens = pickle.dumps(token_dict)
    return user_tokens.put()
  else:
    user_tokens = TokenCollection(
        user=user, 
        pickled_tokens=pickle.dumps(token_dict))
    return user_tokens.put()
项目:GAMADV-X    作者:taers232c    | 项目源码 | 文件源码
def load_auth_tokens(user=None):
  """Reads a dictionary of the current user's tokens from the datastore.

  If there is no current user (a user is not signed in to the app) or the user
  does not have any tokens, an empty dictionary is returned.
  """
  if user is None:
    user = users.get_current_user()
  if user is None:
    return {}
  pickled_tokens = memcache.get('gdata_pickled_tokens:%s' % user)
  if pickled_tokens:
    return pickle.loads(pickled_tokens)
  user_tokens = TokenCollection.all().filter('user =', user).get()
  if user_tokens:
    memcache.set('gdata_pickled_tokens:%s' % user, user_tokens.pickled_tokens)
    return pickle.loads(user_tokens.pickled_tokens)
  return {}
项目:Docker-XX-Net    作者:kuanghy    | 项目源码 | 文件源码
def main():
  """CGI-style request handler to dump the configuration.

  Put this in your app.yaml to enable (you can pick any URL):

  - url: /lib_config
    script: $PYTHON_LIB/google/appengine/api/lib_config.py

  Note: unless you are using the SDK, you must be admin.
  """
  if not os.getenv('SERVER_SOFTWARE', '').startswith('Dev'):
    from google.appengine.api import users
    if not users.is_current_user_admin():
      if users.get_current_user() is None:
        print 'Status: 302'
        print 'Location:', users.create_login_url(os.getenv('PATH_INFO', ''))
      else:
        print 'Status: 403'
        print
        print 'Forbidden'
      return

  print 'Content-type: text/plain'
  print
  _default_registry._dump()
项目:share-class    作者:junyiacademy    | 项目源码 | 文件源码
def get(self):

        user = UserData.get_current_user()
        if user:
            # we already have this user in datastore, do nothing at this time
            pass
        else:
            logging.info('into Login handler')
            google_user_property = users.get_current_user()
            user = UserData.get_by_user_email(google_user_property.email())
            if user:
                # ???????????email??????????????
                logging.error('Email %s already used by one of our user' % user.user_email)
                raise Exception('Email %s already used by one of our user' % user.user_email)
            else:  # email ???????????????
                new_user = UserData(google_user_id=google_user_property.user_id(),
                                user_email=google_user_property.email(),
                                user_nickname=google_user_property.nickname()
                                )
            new_user.put()
        self.redirect('/find-resource')
项目:oscars2016    作者:0x0ece    | 项目源码 | 文件源码
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
项目:sndlatr    作者:Schibum    | 项目源码 | 文件源码
def get(self):
        if decorator.has_credentials():
            # result = service.tasks().list(tasklist='@default').execute(
            #     http=decorator.http())
            # tasks = result.get('items', [])
            # for task in tasks:
            #     task['title_short'] = truncate(task['title'], 26)
            logging.debug(decorator.credentials)
            user = users.get_current_user()
            msg = test_imap(user.email())
            # self.response.write(msg)
            self.render_response('index.html', tasks=[], msg=msg)
        else:
            url = decorator.authorize_url()
            self.render_response('index.html', tasks=[], authorize_url=url)
项目:sndlatr    作者:Schibum    | 项目源码 | 文件源码
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
项目:love    作者:Yelp    | 项目源码 | 文件源码
def get_current_employee(cls):
        user = users.get_current_user()
        user_email = user.email()
        employee = cls.query(cls.user == user, cls.terminated == False).get()  # noqa
        if employee is None:
            raise NoSuchEmployee('Couldn\'t find a Google Apps user with email {}'.format(user_email))
        return employee
项目:love    作者:Yelp    | 项目源码 | 文件源码
def user_required(func):
    @wraps(func)
    def decorated_view(*args, **kwargs):
        if not users.get_current_user():
            return redirect(users.create_login_url(request.url))
        return func(*args, **kwargs)
    return decorated_view
项目:love    作者:Yelp    | 项目源码 | 文件源码
def admin_required(func):
    @wraps(func)
    def decorated_view(*args, **kwargs):
        if users.get_current_user():
            if not users.is_current_user_admin():
                abort(401)  # Unauthorized
            return func(*args, **kwargs)
        return redirect(users.create_login_url(request.url))
    return decorated_view
项目:love    作者:Yelp    | 项目源码 | 文件源码
def is_admin():
    return users.get_current_user() and users.is_current_user_admin()
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
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
项目:isthislegit    作者:duo-labs    | 项目源码 | 文件源码
def context_setup():
    """
    Sets up context for the request
    """
    g.user = users.get_current_user()
    g.domain = address.parse(g.user.email()).hostname
    g.stats = Stats(g.domain)
    g.base_report_query = EmailReport.domain_query(g.domain)
项目:isthislegit    作者:duo-labs    | 项目源码 | 文件源码
def context_setup():
    """
    Sets up context for the request
    """
    g.user = users.get_current_user()
    g.domain = address.parse(g.user.email()).hostname
    g.base_report_query = EmailReport.domain_query(g.domain)
项目:isthislegit    作者:duo-labs    | 项目源码 | 文件源码
def context_setup():
    """
    Sets up context for the request
    """
    g.user = users.get_current_user()
    g.domain = address.parse(g.user.email()).hostname
项目:office-interoperability-tools    作者:milossramek    | 项目源码 | 文件源码
def oauth_required(self, method):
    """Decorator that starts the OAuth 2.0 dance.

    Starts the OAuth dance for the logged in user if they haven't already
    granted access for this application.

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

    def check_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)

      # Store the request URI in 'state' so we can use it later
      self.flow.params['state'] = _build_state_value(request_handler, user)
      self.credentials = StorageByKeyName(
          CredentialsModel, user.user_id(), 'credentials').get()

      if not self.has_credentials():
        return request_handler.redirect(self.authorize_url())
      try:
        return method(request_handler, *args, **kwargs)
      except AccessTokenRefreshError:
        return request_handler.redirect(self.authorize_url())

    return check_oauth
项目:office-interoperability-tools    作者:milossramek    | 项目源码 | 文件源码
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 = StorageByKeyName(
          CredentialsModel, user.user_id(), 'credentials').get()
      return method(request_handler, *args, **kwargs)
    return setup_oauth
项目:office-interoperability-tools    作者:milossramek    | 项目源码 | 文件源码
def callback_handler(self):
    """RequestHandler for the OAuth 2.0 redirect callback.

    Usage:
       app = webapp.WSGIApplication([
         ('/index', MyIndexHandler),
         ...,
         (decorator.callback_path, decorator.callback_handler())
       ])

    Returns:
      A webapp.RequestHandler that handles the redirect back from the
      server during the OAuth 2.0 dance.
    """
    decorator = self

    class OAuth2Handler(webapp.RequestHandler):
      """Handler for the redirect_uri of the OAuth 2.0 dance."""

      @login_required
      def get(self):
        error = self.request.get('error')
        if error:
          errormsg = self.request.get('error_description', error)
          self.response.out.write(
              'The authorization request failed: %s' % _safe_html(errormsg))
        else:
          user = users.get_current_user()
          decorator._create_flow(self)
          credentials = decorator.flow.step2_exchange(self.request.params)
          StorageByKeyName(
              CredentialsModel, user.user_id(), 'credentials').put(credentials)
          redirect_uri = _parse_state_value(str(self.request.get('state')),
                                            user)
          self.redirect(redirect_uri)

    return OAuth2Handler
项目:touch-pay-client    作者:HackPucBemobi    | 项目源码 | 文件源码
def get_user(self):
        user = users.get_current_user()
        if user:
            return dict(nickname = user.nickname(),
                        email = user.email(),
                        registration_id = user.user_id(),
                        user_id = user.user_id(),
                        source = "google account")
项目:arithmancer    作者:google    | 项目源码 | 文件源码
def CheckSignIn():
  user = users.get_current_user()
  if not user:
    login_url = users.create_login_url('/')
    greeting = '<a href="{}">Sign in</a>'.format(login_url)
    return render_template('splash.html', login=login_url)
  else:
    profile = check_if_user_profile(user.user_id())
    return redirect('/predictions')
项目:arithmancer    作者:google    | 项目源码 | 文件源码
def CreateUser():
  """Route for checking if user exists."""
  profile = check_if_user_profile(users.get_current_user().user_id())
  return str(profile)
项目:arithmancer    作者:google    | 项目源码 | 文件源码
def GetUserBalanceByAuth():
  """Returns current users balance."""
  user_key = ndb.Key('Profile', users.get_current_user().user_id())
  profile = user_key.get()
  return str(profile.balance)

# TODO(goldhaber): change to GetUserPortfolioByAuth By Prediction ID
项目:arithmancer    作者:google    | 项目源码 | 文件源码
def GetUserPortfolioByAuth(prediction_id):
  """Returns current users porfolio by prediction_id."""
  user_key = ndb.Key('Profile', users.get_current_user().user_id())
  profile = user_key.get()
  portfolio = []
  if prediction_id:
    portfolio = [
        i for i in profile.user_ledger if i.prediction_id == prediction_id
    ]
  return portfolio
项目:arithmancer    作者:google    | 项目源码 | 文件源码
def GetTradesForPredictionId(prediction_id):
    user = users.get_current_user()
    trades = Trade.query(ndb.AND(Trade.prediction_id == ndb.Key(urlsafe=prediction_id),
                                 Trade.user_id == ndb.Key('Profile', user.user_id()))).fetch()
    return str(trades)
项目:arithmancer    作者:google    | 项目源码 | 文件源码
def inject_balance():
    user = users.get_current_user()
    if not user:
        return dict(balance=0)
    user_key = ndb.Key('Profile', user.user_id())
    profile = user_key.get()
    return dict(balance=profile.balance)
项目:arithmancer    作者:google    | 项目源码 | 文件源码
def check_if_user_profile(user_id):
  """Check if User has a profile, if not create a Profile."""
  profile_query = Profile.query(Profile.user_id == user_id).fetch()
  if len(profile_query) > 0:
    return True
  else:
    profile = Profile(
        user_id=users.get_current_user().user_id(),
        balance=100.00,
        user_email=users.get_current_user().email())
    profile.key = ndb.Key('Profile', users.get_current_user().user_id())
    profile_key = profile.put()
    return profile
项目:webapp2    作者:GoogleCloudPlatform    | 项目源码 | 文件源码
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
项目:webapp2    作者:GoogleCloudPlatform    | 项目源码 | 文件源码
def admin_required(handler_method):
    """A decorator to require that a user be an admin for this application
    to access a handler.

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

        @admin_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_admin(self, *args, **kwargs):
        if self.request.method != 'GET':
            self.abort(400,
                       detail='The admin_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))
        elif not users.is_current_user_admin():
            self.abort(403)
        else:
            handler_method(self, *args, **kwargs)

    return check_admin
项目:tesismometro    作者:joapaspe    | 项目源码 | 文件源码
def user_view():
    """
        User interface (only shows the token).
        :return: An http response with the submitted information.
    """
    user = users.get_current_user()

    if not user:
        return redirect(users.create_login_url("/user"))
    email = user.email()
    doctors = tesis_bd.Doctor.query(tesis_bd.Doctor.email == email).fetch()

    if len(doctors) == 0:
        return render_template('error.html', message="User not found in the DB.")

    doctor = doctors[0]
    name = doctor.name

    if not doctor.token:
        doctor.token = "%016x" % random.getrandbits(64)
    code = doctor.token

    doctor.put()
    logout_url = users.create_logout_url("/")
    return render_template('user_view.html', login=doctor.name, name=name, email=email, code=code,
                           logout_url=logout_url)
项目:daytravel    作者:warsawpact    | 项目源码 | 文件源码
def get(self):
        current_user = users.get_current_user()
        logout_url= users.create_logout_url('/')
        login_url= users.create_login_url('/')

        template = jinja_environment.get_template("templates/daytravel.html")
        template_vars = {
        'current_user': current_user,
        'logout_url': logout_url,
        'login_url': login_url,
        }
        self.response.write(template.render(template_vars))
项目:daytravel    作者:warsawpact    | 项目源码 | 文件源码
def post(self):
        city= self.request.get('city')
        current_user = users.get_current_user()
        logout_url= users.create_logout_url('/')
        login_url= users.create_login_url('/')

        self.redirect('/plan?city=' + city)