示例#1
0
def add_standard_template_values(template_values):

    # Specify base template based on whether this is a pjax request
    template_values['base_template'] = 'base_pjax.html' if utils.is_pjax_request() else 'base.html'

    # Authentication information
    # NOTE: This may fall foul of template output caching if used by routes that allow caching.
    if users.is_signed_in():
        template_values['nickname'] = users.get_current_user().nickname()
        template_values['auth_url'] = users.create_google_signout_url()
    else:
        template_values['nickname'] = None
        template_values['auth_url'] = users.create_google_signin_url()

    # Make configuration settings available to templates
    template_values['settings'] = settings
    template_values['route_configs'] = routes.configs

    # Identify local versus deployed
    template_values['is_local'] = utils.is_local()

    # Set defaults for page title and active nav
    nav_title = routes.configs.get().nav_title
    template_values['title'] =  nav_title + ' - ' + settings.app_title if nav_title else settings.app_title
    template_values['active_nav'] = routes.configs.get().name

    return template_values
示例#2
0
    def Respond(self, oidresponse):
        logging.warning('Respond: oidresponse.request.mode ' +
                        oidresponse.request.mode)

        if oidresponse.request.mode in ['checkid_immediate', 'checkid_setup']:
            user = users.get_current_user()
            if user:
                from openid.extensions.sreg import SRegRequest, SRegResponse
                sreg_req = SRegRequest.fromOpenIDRequest(oidresponse.request)
                if sreg_req.wereFieldsRequested():
                    logging.info("sreg_req:%s", sreg_req.allRequestedFields())
                    user_data = {
                        'nickname': user.nickname(),
                        'email': user.email()
                    }
                    sreg_resp = SRegResponse.extractResponse(
                        sreg_req, user_data)
                    sreg_resp.toMessage(oidresponse.fields)
        logging.info('Using response: %s' % oidresponse)
        encoded_response = oidserver.encodeResponse(oidresponse)

        for header, value in encoded_response.headers.items():
            self.response.headers[header] = str(value)

        if encoded_response.code in (301, 302):
            self.redirect(self.response.headers['location'])
        else:
            self.response.set_status(encoded_response.code)

        if encoded_response.body:
            logging.debug('Sending response body: %s' % encoded_response.body)
            self.response.out.write(encoded_response.body)
        else:
            self.response.out.write('')
  def CheckUser(self):
    """Checks that the OpenID identity being asserted is owned by this user.

    Specifically, checks that the request URI's path is the user's nickname.

    Returns:
      True if the request's path is the user's nickname. Otherwise, False, and
      prints an error page.
    """
    args = self.ArgsToDict()

    user = users.get_current_user()
    if not user:
      # not logged in!
      return False
#    return True
    # check that the user is logging into their page, not someone else's.
    identity = args['openid.identity']
    parsed = urlparse.urlparse(identity)
    path = parsed[2]

    if identity == 'http://specs.openid.net/auth/2.0/identifier_select':
      return True

    if path[1:] != user.nickname():
      expected = parsed[0] + '://' + parsed[1] + '/' + user.nickname()
      logging.warning('Bad identity URL %s for user %s; expected %s, path:%s' % 
                      (identity, user.nickname(), expected, path))
      return False

    logging.debug('User %s matched identity %s' % (user.nickname(), identity))
    return True
示例#4
0
def add_standard_template_values(template_values):

    # Specify base template based on whether this is a pjax request
    template_values[
        'base_template'] = 'base_pjax.html' if utils.is_pjax_request(
        ) else 'base.html'

    # Authentication information
    # NOTE: This may fall foul of template output caching if used by routes that allow caching.
    if users.is_signed_in():
        template_values['nickname'] = users.get_current_user().nickname()
        template_values['auth_url'] = users.create_google_signout_url()
    else:
        template_values['nickname'] = None
        template_values['auth_url'] = users.create_google_signin_url()

    # Make configuration settings available to templates
    template_values['settings'] = settings
    template_values['route_configs'] = routes.configs

    # Identify local versus deployed
    template_values['is_local'] = utils.is_local()

    # Set defaults for page title and active nav
    nav_title = routes.configs.get().nav_title
    template_values[
        'title'] = nav_title + ' - ' + settings.app_title if nav_title else settings.app_title
    template_values['active_nav'] = routes.configs.get().name

    return template_values
  def Respond(self, oidresponse):
    logging.warning('Respond: oidresponse.request.mode ' + oidresponse.request.mode)

    if oidresponse.request.mode in ['checkid_immediate', 'checkid_setup']:
      user = users.get_current_user()
      if user:
        from openid.extensions.sreg import SRegRequest, SRegResponse
        sreg_req = SRegRequest.fromOpenIDRequest(oidresponse.request)
        if sreg_req.wereFieldsRequested():
          logging.info("sreg_req:%s", sreg_req.allRequestedFields())
          user_data = {'nickname':user.nickname(),
                       'email':user.email()}
          sreg_resp = SRegResponse.extractResponse(sreg_req, user_data)
          sreg_resp.toMessage(oidresponse.fields)        
    logging.info('Using response: %s' % oidresponse)
    encoded_response = oidserver.encodeResponse(oidresponse)

    for header, value in encoded_response.headers.items():
      self.response.headers[header] = str(value)

    if encoded_response.code in (301, 302):
      self.redirect(self.response.headers['location'])
    else:
      self.response.set_status(encoded_response.code)

    if encoded_response.body:
      logging.debug('Sending response body: %s' % encoded_response.body)
      self.response.out.write(encoded_response.body)
    else:
      self.response.out.write('')
示例#6
0
文件: admin.py 项目: dudarev/osmtweet
    def get(self,action=None):
        self.response.out.write('Admin page<br/><br/>')
        message = self.request.get("message")
        if message:
            self.response.out.write('<font color="red">'+message+'</font><br/><br/>')
        self.response.out.write('<a href="/admin/load">Load and parse changesets</a> (takes time)<br/>')
        self.response.out.write('<a href="/admin/prepare">Prepare to tweet</a><br/>')
        self.response.out.write('<a href="/admin/tweet">Tweet</a><br/><br/>')
        self.response.out.write('<a href="/admin/update_counts">Update counts</a><br/><br/>')
        self.response.out.write('<a href="/admin/update_description">Update description</a><br/><br/>')
        self.response.out.write('<a href="http://localhost:8080/_ah/admin/datastore">Localhost datastore</a><br/><br/>')
        self.response.out.write('<a href="/">Home</a><br/><br/>')

        user = users.get_current_user(self)
        if user:
            login_logout_link = "%s<br/><a href=\"%s\">Logout</a>" % (user, users.create_logout_url(self, "/"))
        else:
            login_logout_link = "<a href=\"%s\">Login with Twitter</a>" % users.create_login_url(self, "/")
        self.response.out.write(login_logout_link)

        if action:
            if action == 'load':
                self.LoadHandler()
            if action == 'prepare':
                self.PrepareHandler()
            if action == 'tweet':
                self.TweetHandler()
            if action == 'update_counts':
                self.UpdateCountsHandler()
            if action == 'update_description':
                self.UpdateDescription()
示例#7
0
    def get(self):
        user = get_current_user()

        # user may have timed out or not be logged in.
        if user:
            user.logout()

        self.redirect("/")
def get_identity_url(request):
    user = users.get_current_user()
    if not user:
      return None
      
    parsed = urlparse.urlparse(request.uri)
    request_url_without_path = parsed[0] + '://' + parsed[1]
    
    return request_url_without_path + '/' + user.nickname()
示例#9
0
def get_identity_url(request):
    user = users.get_current_user()
    if not user:
        return None

    parsed = urlparse.urlparse(request.uri)
    request_url_without_path = parsed[0] + '://' + parsed[1]

    return request_url_without_path + '/' + user.nickname()
示例#10
0
 def get(self):
   config = get_config()
   vtweet = self.request.get('tweetid')
   logging.debug(users.get_current_user(self))
   vuser = users.get_current_user(self)
   if vuser:
     vuser = str(vuser)
     # Check if user voted for this tweet
     try:
       query = db.GqlQuery("SELECT * FROM Tweet WHERE id=:1", int(vtweet))
       if query:
         tweet = query[0]
       else:
         self.response.out.write('error_tweet_not_found')
         return
     except:
       self.response.out.write('error_query_exception %s' % vtweet)
       return
     if vuser in tweet.users_voted:
       self.response.out.write('already')
     else:
       # Add data about the vote
       tweet.users_voted.append(vuser)
       if tweet.votes_count:
         tweet.votes_count += 1
       else:
         tweet.votes_count = 1
       # retweet it if not retweeted before
       if not tweet.is_retweeted:
         config = get_config()
         api = twitter.Api(username=config["twitter_username"], password=config["twitter_password"])
         retweet_text = "RT @%s %s" % (tweet.from_user, tweet.text)
         if len(retweet_text) > 140:
           retweet_text = retweet_text[:135] + "..."
         res = api.PostUpdate(retweet_text)
       try:
         tweet.put()
         self.response.out.write('success')
       except:
         self.response.out.write(str(tweet.users_voted))
   else:
     self.response.out.write('no login')
示例#11
0
    def get(self):
        logins = []

        user = users.get_current_user()
        if user:
            query = datastore.Query('Login')
            query['user ='******'time', datastore.Query.DESCENDING))
            logins = query.Get(10)

        self.Render('index', {"logins": logins, "user": user})
  def get(self):
    logins = []

    user = users.get_current_user()
    if user:
      query = datastore.Query('Login')
      query['user ='******'time', datastore.Query.DESCENDING))
      logins = query.Get(10)

    self.Render('index', {"logins": logins, "user": user})
示例#13
0
 def get(self):
     template = env.get_template('index.html')
     user = users.get_current_user()
     if user:
         template_vars = {'logstatus':"Log Out",
                          'logoutlink': users.create_logout_url('/')
                          }
         if UserStorage.query(UserStorage.email == user.email()).get().setup==True:
             template_vars['address'] = UserStorage.query(UserStorage.email == user.email()).get().address
         self.response.write(template.render(template_vars))
     else:
         template_vars = {'logstatus': "Log In",
                          'logoutlink': users.create_login_url('/login')}
         self.response.write(template.render(template_vars))
示例#14
0
 def post(self):
     user = users.get_current_user()
     person = UserStorage.query(UserStorage.email == users.get_current_user().email()).get()
     person.id = self.request.get('name')
     address = self.request.get('user_LatLocation')
     person.address = address
     address = address.replace(" ", "+")
     content = urllib2.urlopen("https://maps.googleapis.com/maps/api/geocode/json?address=%s&key=AIzaSyADJhWkgPHBu3SXXrtqnJNmdmz7Xu_mhRc" % address).read()
     content_dict = json.loads(content)
     person.LatLocation = float(content_dict['results'][0]['geometry']['location']['lat'])
     person.LongLocation = float(content_dict['results'][0]['geometry']['location']['lng'])
     person.setup = True
     person.put()
     template = env.get_template('index.html')
     if user:
         template_vars = {'logstatus':"Log Out",
                          'logoutlink': users.create_logout_url('/'),
                          'address':person.address}
         self.response.write(template.render(template_vars))
     else:
         template_vars = {'logstatus': "Log In",
                          'logoutlink': users.create_login_url('/login')}
         self.response.write(template.render(template_vars))
示例#15
0
    def get(self):
        user = users.get_current_user()
        template = env.get_template('profile.html')
        template_vars = {'name':user.nickname(),
                         'autofill1': "",
                         'autofill2': ""}
        found_user = UserStorage.query(UserStorage.email == user.email()).get()
        if found_user:
            template_vars['autofill1'] = found_user.id
            template_vars['autofill2'] = found_user.address
        else:
            useremail=user.email()
            useremail=useremail.lower()
            print useremail
            UserStorage(email=useremail).put()

        self.response.write(template.render(template_vars))
示例#16
0
  def get(self):
    config = get_config()

    # Tweets
    if self.sort_by_votes:
        count = Tweet.all().filter("votes_count >",0).count(1000)
    else:
        count = Tweet.all().count(1000)
    page = int(self.request.get('page', 1))
    prev_page = page-1
    next_page = page+1
    show_prev_page = (page>1)
    show_next_page = (page*20<count)
    tweets = []
    if self.sort_by_votes:
        query = Tweet.all().filter("votes_count >",0).order("-votes_count").order("-id").fetch(20, (page-1)*20)
    else:
        query = Tweet.all().order("-id").fetch(20, (page-1)*20)
    for tweet in query:
      tweet.status = twitter.Status(id=tweet.id, created_at=tweet.created_at)
      tweet.text = unescape(tweet.text)
      tweet.source = unescape(tweet.source)
      tweets.append(tweet)

    # User cloud
    cloud_tweets = Tweet.all().order('-id').fetch(300)
    cloud_items = {}
    cloud = []
    max = 0
    for tw in cloud_tweets:
      cloud_items[tw.from_user] = 0
    for tw in cloud_tweets:
      cloud_items[tw.from_user] = cloud_items[tw.from_user]+1
      if cloud_items[tw.from_user]>max: max = cloud_items[tw.from_user]
    for k in cloud_items:
      cloud.append({'name':k, 'lower_name':k.lower(), 'count':cloud_items[k], 'html':'<a href="http://twitter.com/%s" style="font-size:%spx">%s</a>' % (k, (9 + 16*(1.0*cloud_items[k]/max)), k)})

    user = users.get_current_user(self)
    if user:
      login_logout_link = "<strong>%s</strong> | <a href=\"%s\">Logout</a>" % (user,users.create_logout_url(self,"/"))
    else:
      login_logout_link = "<a href=\"%s\">Login</a>" % users.create_login_url(self,"/")
    nav_link = login_logout_link
      
    path = os.path.join(os.path.dirname(__file__), 'index.html')
    self.response.out.write(template.render(path, locals()))
示例#17
0
    def store_login(self, oidrequest, kind):
        """Stores the details of an OpenID login in the datastore.

    Args:
      oidrequest: OpenIDRequest

      kind: string
      'remembered', 'confirmed', or 'declined'
    """
        assert kind in ['remembered', 'confirmed', 'declined']
        user = users.get_current_user()
        assert user

        login = datastore.Entity('Login')
        login['relying_party'] = oidrequest.trust_root
        login['time'] = datetime.datetime.now()
        login['kind'] = kind
        login['user'] = user.id()
        datastore.Put(login)
  def store_login(self, oidrequest, kind):
    """Stores the details of an OpenID login in the datastore.

    Args:
      oidrequest: OpenIDRequest

      kind: string
      'remembered', 'confirmed', or 'declined'
    """
    assert kind in ['remembered', 'confirmed', 'declined']
    user = users.get_current_user()
    assert user

    login = datastore.Entity('Login')
    login['relying_party'] = oidrequest.trust_root
    login['time'] = datetime.datetime.now()
    login['kind'] = kind
    login['user'] = user.id()
    datastore.Put(login)
示例#19
0
    def get(self):
        """Handles GET requests."""
        login_url = users.create_login_url(self.request.uri)
        user = users.get_current_user()
        if user:
            logging.debug('User: %s' % user)
        else:
            logging.info('no user, redirect to login url')
            self.redirect(login_url)

        oidrequest = self.GetOpenIdRequest()
        postargs = oidrequest.message.toPostArgs() if oidrequest else {}

        if oidrequest is False:
            # there was an error, and GetOpenIdRequest displayed it. bail out.
            return
        elif oidrequest is None:
            # this is a request from a browser
            self.ShowFrontPage()
        elif oidrequest.mode in ['checkid_immediate', 'checkid_setup']:
            if self.HasCookie(oidrequest.trust_root) and user:
                logging.debug('Has cookie, confirming identity to ' +
                              oidrequest.trust_root)
                self.store_login(oidrequest, 'remembered')
                self.Respond(
                    oidrequest.answer(True,
                                      identity=get_identity_url(self.request)))
            elif oidrequest.immediate:
                self.store_login(oidrequest, 'declined')
                oidresponse = oidrequest.answer(False)
                self.Respond(oidresponse)
            else:
                if self.CheckUser():
                    self.Render('prompt', vars())
                else:
                    self.ShowFrontPage()

        elif oidrequest.mode in ['associate', 'check_authentication']:
            self.Respond(oidserver.handleRequest(oidrequest))

        else:
            self.ReportError('Unknown mode: %s' % oidrequest.mode)
  def get(self):
    """Handles GET requests."""
    login_url = users.create_login_url(self.request.uri)
    user = users.get_current_user()
    if user:
      logging.debug('User: %s' % user)
    else:
      logging.info('no user, redirect to login url')
      self.redirect(login_url)

    oidrequest = self.GetOpenIdRequest()
    postargs = oidrequest.message.toPostArgs() if oidrequest else {}
    
    if oidrequest is False:
      # there was an error, and GetOpenIdRequest displayed it. bail out.
      return
    elif oidrequest is None:
      # this is a request from a browser
      self.ShowFrontPage()
    elif oidrequest.mode in ['checkid_immediate', 'checkid_setup']:
      if self.HasCookie(oidrequest.trust_root) and user:
        logging.debug('Has cookie, confirming identity to ' + 
                      oidrequest.trust_root)
        self.store_login(oidrequest, 'remembered')
        self.Respond(oidrequest.answer(True, identity=get_identity_url(self.request)))
      elif oidrequest.immediate:
        self.store_login(oidrequest, 'declined')
        oidresponse = oidrequest.answer(False)
        self.Respond(oidresponse)
      else:
        if self.CheckUser():
          self.Render('prompt', vars())
        else:
          self.ShowFrontPage()

    elif oidrequest.mode in ['associate', 'check_authentication']:
      self.Respond(oidserver.handleRequest(oidrequest))

    else:
      self.ReportError('Unknown mode: %s' % oidrequest.mode)
示例#21
0
    def Render(self, template_name, extra_values={}):
        parsed = urlparse.urlparse(self.request.uri)
        request_url_without_path = parsed[0] + '://' + parsed[1]
        request_url_without_params = request_url_without_path + parsed[2]

        self.response.headers.add_header('X-XRDS-Location',
                                         request_url_without_path + '/xrds')

        values = {
            'request': self.request,
            'request_url_without_path': request_url_without_path,
            'request_url_without_params': request_url_without_params,
            'user': users.get_current_user(),
            'login_url': users.create_login_url(self.request.uri),
            'register_url': 'signup',
            'logout_url': users.create_logout_url('/'),
            'debug': self.request.get('deb'),
        }
        values.update(extra_values)
        cwd = os.path.dirname(__file__)
        path = os.path.join(cwd, 'templates', template_name + '.html')
        logging.debug(path)
        self.response.out.write(template.render(path, values))
  def Render(self, template_name, extra_values={}):
    parsed = urlparse.urlparse(self.request.uri)
    request_url_without_path = parsed[0] + '://' + parsed[1]
    request_url_without_params = request_url_without_path + parsed[2]

    self.response.headers.add_header(
      'X-XRDS-Location', request_url_without_path + '/xrds')

    values = {
      'request': self.request,
      'request_url_without_path': request_url_without_path,
      'request_url_without_params': request_url_without_params,
      'user': users.get_current_user(),
      'login_url': users.create_login_url(self.request.uri),
      'register_url':  'signup',
      'logout_url': users.create_logout_url('/'),
      'debug': self.request.get('deb'),
    }
    values.update(extra_values)
    cwd = os.path.dirname(__file__)
    path = os.path.join(cwd, 'templates', template_name + '.html')
    logging.debug(path)
    self.response.out.write(template.render(path, values))
示例#23
0
    def CheckUser(self):
        """Checks that the OpenID identity being asserted is owned by this user.

    Specifically, checks that the request URI's path is the user's nickname.

    Returns:
      True if the request's path is the user's nickname. Otherwise, False, and
      prints an error page.
    """
        args = self.ArgsToDict()

        user = users.get_current_user()
        if not user:
            # not logged in!
            return False


#    return True
# check that the user is logging into their page, not someone else's.
        identity = args['openid.identity']
        parsed = urlparse.urlparse(identity)
        path = parsed[2]

        if identity == 'http://specs.openid.net/auth/2.0/identifier_select':
            return True

        if path[1:] != user.nickname():
            expected = parsed[0] + '://' + parsed[1] + '/' + user.nickname()
            logging.warning(
                'Bad identity URL %s for user %s; expected %s, path:%s' %
                (identity, user.nickname(), expected, path))
            return False

        logging.debug('User %s matched identity %s' %
                      (user.nickname(), identity))
        return True
示例#24
0
    def get(self):
        user = get_current_user()
        values = {"server_url": SERVER_URL, "api_key": API_KEY, "user": user}

        path = os.path.join(os.path.dirname(__file__), "templates", "login.html")
        self.response.out.write(template.render(path, values, debug=True))
示例#25
0
 def get(self):
     user = get_current_user()
     values = {'user': user}
         
     path = os.path.join(os.path.dirname(__file__), 'templates', 'home.html')
     self.response.out.write(template.render(path, values, debug=_DEBUG))