コード例 #1
0
ファイル: EnvVars.py プロジェクト: AE-BaseApp/Python
def update_vars(self, adp, dtz):
    app_vars = db.GqlQuery('SELECT * FROM EnvVars')
    if not app_vars.get():  # record does not exist yet create it
        record = EnvVars(ad_provider=adp, default_tz=dtz)
        # check if user is admin and update the data else raise 401
        if users.is_current_user_admin():
            try:  
                record.put()
                return(True)
            except:
                self.error(500)
        else:
            self.error(401)
    else:  # record exists so update it
        record = app_vars.get()
        setattr(record, 'ad_provider', adp)
        setattr(record, 'default_tz', dtz)
        # check if user is admin and update the data else raise 401
        if users.is_current_user_admin():
            try:  
                record.put()
                return(True)
            except:
                self.error(500)
        else:
            self.error(401)
コード例 #2
0
ファイル: controller.py プロジェクト: cng1985/express-me
def do_google_signin(**kw):
    ctx = kw['context']
    # get google user:
    gu = users.get_current_user()
    if gu is None:
        logging.error('Google account info is not found. Exit g_signin...')
        raise ApplicationError('Cannot find user information')
    ctx.delete_cookie(cookie.AUTO_SIGNIN_COOKIE)
    email = gu.email().lower()
    nicename = gu.nickname()
    # check if user exist:
    user = store.get_user_by_email(email)
    if user is None:
        # auto-create new user:
        role = store.ROLE_SUBSCRIBER
        if users.is_current_user_admin():
            role = store.ROLE_ADMINISTRATOR
        user = store.create_user(role, email, '', nicename)
    elif users.is_current_user_admin() and user.role!=store.ROLE_ADMINISTRATOR:
        user.role = store.ROLE_ADMINISTRATOR
        user.put()
    ctx.set_cookie(cookie.IS_FROM_GOOGLE_COOKIE, 'yes', 31536000)
    redirect = ctx.get_argument('redirect', '/')
    logging.info('Sign in successfully with Google account and redirect to %s...' % redirect)
    return 'redirect:%s' % redirect
コード例 #3
0
ファイル: views.py プロジェクト: nsmgr8/messnager
def create_member(request):
    if request.method == 'POST':
        if users.is_current_user_admin():
            form = MemberFormAdmin(data=request.POST)
        else:
            form = MemberForm(data=request.POST)
        
        try:
            if form.is_valid():
                entity = form.save(commit=False)
                member = Member.all().filter('email =', entity.email).get()
                if member:
                    form._errors['email'] = {_("user exists"): _("user exists")}
                    raise
                member = Member.all().filter('nick =', entity.nick).get()
                if member:
                    form._errors['nick'] = {_("user exists"): _("user exists")}
                    raise
                entity.put()
                return HttpResponseRedirect('/member/')
        except:
            pass
    else:
        if users.is_current_user_admin():
            form = MemberFormAdmin()
        else:
            user = Member.current_user()
            form = MemberForm(initial={'mess': user.mess.key()})

    return render(request, "member_add.html", {'form':form})
コード例 #4
0
ファイル: ys.py プロジェクト: tessie/yitzscape
	def get(self):
		pageq = db.GqlQuery("SELECT * FROM HomePage")

		pages = pageq.fetch(100)
		
		display_pages = list()

		for page in pages:
			if not page.public:
				if users.is_current_user_admin():
					display_pages.append(page)
			else:
				display_pages.append(page)	

		if users.get_current_user():
			url = users.create_logout_url(self.request.uri)
			url_linktext = 'Logout'
		else:
			url = users.create_login_url(self.request.uri)
			url_linktext = 'Login'

		template_values = {
			'pages': display_pages,
			'url': url,
			'url_linktext': url_linktext,
		}
		
		if users.is_current_user_admin():
			path = os.path.join(os.path.dirname(__file__), 'admin_list.html')
		else:
			path = os.path.join(os.path.dirname(__file__), 'list.html')
		self.response.out.write(template.render(path, template_values))
コード例 #5
0
ファイル: edit.py プロジェクト: mdragon/mileagetracker
    def get(self):
        user = users.get_current_user()
        key = self.request.get("key")
        if user is None:
            self.redirect(self.request.relative_url(users.create_login_url("/Edit?key=" + key)))
            return

        if not users.is_current_user_admin():
            self.redirect("/?not-admin")
            return

        if key != "":
            entry = db.get(key)
        else:
            entry = models.Entry()

        if entry.is_saved():
            key = entry.key()
            entry.prettyDate = entry.date.strftime("%m/%d/%y")
        else:
            key = ""

        template_values = {
            "entry": entry,
            "key": key,
            "admin": users.is_current_user_admin(),
            "login_link": users.create_login_url(self.request.url),
            "logout_link": users.create_logout_url("/"),
            "user": users.get_current_user(),
        }

        path = os.path.join(os.path.dirname(__file__), "../views/edit.html")
        # self.response.out.write(path)
        self.response.out.write(template.render(path, template_values))
コード例 #6
0
ファイル: app.py プロジェクト: tangles/tangles
  def get(self):
    gql = "ORDER BY date DESC"
    if not users.is_current_user_admin():
      gql = "WHERE secret = False " + gql          

    # Establish the XSRF token.  This is verified by @verify_xsrf_token.
    c = Cookie.Cookie()
    c.load(self.request.headers["Cookie"])
    if not c.has_key("xt"):
      # Establish the XSRF cookie.  We use a random string of 7 characters.
      token = sha.sha(str(random.random())).hexdigest()[:7]
      self.response.headers["Set-Cookie"] = "xt=%s" % token
    else:
      token = c["xt"].value

    template_values = {      
      "you_are": users.get_current_user(),
      "user_is_god": users.is_current_user_admin(),
      "data": SharedObject.gql(gql),
      "logout_url": users.create_logout_url(self.request.uri),
      "xsrf_token": "xt" + token,
    }
    
    path = os.path.join(os.path.dirname(__file__), 'upload.html')
    self.response.out.write(template.render(path, template_values))
コード例 #7
0
ファイル: base.py プロジェクト: andreyvit/yoursway-builder
 def read_user(self):
   self.user = users.get_current_user()
   if self.user == None:
     self.profile = Profile(user = None, email = None, level = ANONYMOUS_LEVEL)
     self.data.update(username = None, login_url = users.create_login_url(self.request.uri))
   else:
     self.profile = (Profile.all().filter('user ='******'email =', self.user.email()).get() or
       Profile(user = self.user, email = self.user.email(), level = ANONYMOUS_LEVEL))
     if users.is_current_user_admin() and self.profile.level < GOD_LEVEL:
       # propagate new admins to gods
       self.profile.level = GOD_LEVEL
       self.profile.put()
     elif not users.is_current_user_admin() and self.profile.level == GOD_LEVEL:
       # revoke god priveledges from ex-admins
       self.profile.level = ADMIN_LEVEL
       self.profile.put()
     if self.profile.email == None:
       self.profile.email = self.user.email()
       self.profile.put()
     if self.profile.user == None:
       self.profile.user = self.user
       self.profile.put()
     self.data.update(username = self.user.nickname(), logout_url = users.create_logout_url(self.request.uri))
   self.data.update(profile = self.profile)
コード例 #8
0
ファイル: views.py プロジェクト: beachboysqq/gansha
def add_event(request):
    if not users.is_current_user_admin():
        return HttpResponseRedirect('/')
        
    if request.method == 'POST':
        is_public = request.POST['is_public'] =='1'
        event = Event(
                      title=request.POST['title'],
                      desc=request.POST['desc'],
                      publish_date=today(),
                      is_public=is_public)
        event.put()
        return HttpResponseRedirect( '../event/?event=%s' % str(event.key()) )
        #except:
        #    return...error
    else:
        c = Context({
                'logouturl':LOGOUT,
                'loginurl':LOGIN,
                'cur_user':CURUSER,
                'is_admin':users.is_current_user_admin(),
                'is_admin':True,
                'event':Event(),
                })
    return render_to_response( 'newevent.htm',c )
コード例 #9
0
ファイル: invite.py プロジェクト: bws9000/EatDudeWeb
 def POST(self):
     user = users.get_current_user()
     isadmin = users.is_current_user_admin()
     
     if user :
             validateForm = invite_form()
             if not validateForm.validates():
                 return main_view.user.invite(validateForm)
             
             else :
                 data = web.input()
                 i = Invite()
                 
                 restaurant_keyname = i.checkIfCodeExists(data.invite_code)
                 if restaurant_keyname :
                     rm = RestaurantModel.get(restaurant_keyname)
                     
                     # add profile to restaurant
                     if not users.is_current_user_admin():
                         p = UserProfileModel()
                         current_profile = p.get_by_key_name(users.get_current_user().user_id())
                         if current_profile.key() not in rm.profiles:
                             rm.profiles.append(current_profile.key())
                             rm.put()
                            
                     upm = UserProfileModel.get_by_key_name(user.user_id())
                     upm.invited = True
                     upm.put()
                     
                     return web.seeother('/user/')
                 else:
                     return 'invitation code failed'
     
     else:
            return web.seeother('/')
コード例 #10
0
ファイル: SecurityUtils.py プロジェクト: alfonsodev/edutrynew
def AccessOK(xCurrentUser, PermissionID):
#    PermissionID = int(PermID)
    currentuser = users.get_current_user()
    logging.info('GGG: PermissionID: %s' % PermissionID)
    logging.info('GGG: current_user_admin: %s' % users.is_current_user_admin())
    IsOK = False
    if users.is_current_user_admin():
        logging.info('GGG: AccessOKNew-Where: %s' % 'In user is Admin user')
        IsOK = True
    else:
        logging.info('GGG: AccessOKNew-Where: %s' % 'In user is Admin user ELSE')
        q = UserSuppl.query(UserSuppl.UserID == currentuser)
        user = q.get()
        if user:
            logging.info('GGG: AccessOKNew-Where: %s' % 'retrieveD UserSuppl')
            logging.info('GGG: UserID: %s' % user.UserID)
            logging.info('GGG: Role: %s' % user.Role)
            if user.Status == 'Assigned':
                if user.Role == 'admin':
                    IsOK = True
                else:
                    if PermissionID in user.Permissions:
                        IsOK = True
#    IsOK = True
#    logging.info('GGG: Final IsOK: %s' % IsOK)
    logging.info('GGG: AccessOKNew-Just before Rtn: %s' % IsOK)
    return IsOK
コード例 #11
0
ファイル: auth.py プロジェクト: gbozee/Green-Football-Zone
def retrieve_user_from_google(google_user):
    auth_id = 'federated_%s' % google_user.user_id()

    user_db = model.User.retrieve_one_by('email', google_user.email())
    if user_db:
        if auth_id not in user_db.auth_ids:
            user_db.auth_ids.append(auth_id)
            user_db.username = google_user.nickname()
        user_db.put()
        return user_db

    user_db = model.User.retrieve_one_by('auth_ids', auth_id)
    if user_db:
        if user_db.email == google_user.email():
            return user_db
        if not user_db.admin and users.is_current_user_admin():
            user_db.admin = True
            user_db.put()
        return user_db


    return create_user_db(
        auth_id,
        google_user.nickname().split('@')[0].replace('.', ' ').title(),
        google_user.nickname(),
        google_user.email(),
        admin=users.is_current_user_admin(),
    )
コード例 #12
0
ファイル: main.py プロジェクト: zapstar/gae-location
 def get(self):
     
     #See if the user has logged in
     user = users.get_current_user()
     if user:
         #Double check if the user is an administrator
         if users.is_current_user_admin():
             
             #Create appropriate login/logout url
             logout_url = users.create_logout_url(self.request.url)
             self.loginout_str = '<a href="' + logout_url + '">Logout</a>'
         
             #Admin Area Login Link (Not necessary)
             if users.is_current_user_admin():
                 self.admin_str = '<a href="/admin/">Admin Area</a> |'
             
             #Query the datastore for the last 100 entries from the dataModel
             #named 'GeoLocation', there are no ancestors for this datastore (no namespaces)
             self.query_dict = db.GqlQuery("SELECT * FROM GeoLocation ORDER BY date DESC LIMIT 100")
             
             #the regular templating follows this code
             template_values = {
                         'table' : self.query_dict,
                        'loginout_str' : self.loginout_str,
                        'admin_str' : self.admin_str
             }
             
             file_path = os.path.join(os.path.dirname(__file__), 'templates/admin.html')
             html = template.render(file_path, template_values)
             self.response.out.write(html)
             
         else:
             self.response.out.write('Your\'e not an administrator!')
     else:
         self.response.out.write('Please <a href="' + users.create_login_url() + '">Login</a> here')
コード例 #13
0
ファイル: view.py プロジェクト: MirkoRossini/sketchPatch
    def full_render(self, handler,template_file, params={}):
            scheme, netloc, path, query, fragment = urlparse.urlsplit(handler.request.uri)
            administrator = False

            if users.get_current_user():
                url = users.create_logout_url(handler.request.uri)
                url_linktext = 'Sign out'
                if users.is_current_user_admin():
                    administrator = True
            else:
                url = users.create_login_url(handler.request.uri)
                url_linktext = 'Sign in'
            template_params = {
                "current_url": url,
                'user': users.GetCurrentUser(),
                'url': url,
                'url_linktext': url_linktext,
                'administrator': administrator,
                'request': handler.request,
                "user_is_admin": users.is_current_user_admin(),
                "login_url": users.create_login_url(handler.request.uri),
                "logout_url": users.create_logout_url(handler.request.uri),
                "user_gravatar_url":util.getGravatarUrlByUser(users.get_current_user()),
                "user_nickname":util.getUserNickname(users.get_current_user())
            }
            template_params.update(params)
            return template.render(template_file, template_params, True)
コード例 #14
0
  def get(self):
    if users.is_current_user_admin():
      path = os.path.join(os.path.dirname(__file__), 'stats.phtml')

      forsale = BookSet().all().filter('buyer =', None)
      sold = BookSet().all().filter('buyer !=', None)
      soldAndDeleted = DeletedBookSet().all().filter('buyer !=', None)
      deleted = DeletedBookSet().all().filter('buyer =', None)

      template_values = {
          'bookstats': {
                  'forsale_count': forsale.count(),
                  'sold_count': sold.count() + soldAndDeleted.count(),
                  'sold': sold.fetch(sold.count()),
                  'sold_deleted': soldAndDeleted.fetch(soldAndDeleted.count()),
                  'deleted_count': deleted.count(),
              },
          'page_header': template.render('header.html', {
                  'user': users.get_current_user(),
                  'admin': users.is_current_user_admin(),
                  'url': users.create_logout_url(self.request.uri),
                  'url_linktext': 'Déconnexion',
              }),
          'page_footer': template.render('footer.html', {}),
          }

      self.response.out.write(template.render(path, template_values))
    else:
      self.redirect('/')
コード例 #15
0
ファイル: base.py プロジェクト: ppalucki/shcms
 def pre_dispatch_admin(self):
     """ sprawdzenie dostepu do panelu admina """
     if self._is_admin_request():
         if self.app.local:
             class User():
                 def nickname(self):
                     return 'test'
                 def email(self):
                     return '*****@*****.**'
             self.user = user = User()
             is_admin = True
         else:
             self.user = user = users.get_current_user()
             is_admin = users.is_current_user_admin()                
         can_edit = is_admin or (user is not None and (user.email()==Var.get_value('admin')))            
         logging.debug('current_user: admin=%s can_edit=%s', users.is_current_user_admin(), can_edit)            
         if not can_edit:
             if self.request.method=='POST':                                        
                 self.abort(403) # just 403 - for POSTs
             else:                    
                 if user:
                     # not admin 
                     return self.render('admin/login.html')                        
                 else:
                     # not authorized user so go to login
                     return self.redirect(users.create_login_url(self.request.path)) # login and redirect
         assert can_edit and user is not None
コード例 #16
0
ファイル: base_handler.py プロジェクト: peterlie/pystart-gae
    def handle_exception(self, exception, debug_mode):
        # TODO: this can probably be seriously cleaned up.
        exception_name = sys.exc_info()[0].__name__
        exception_details = str(sys.exc_info()[1])
        exception_traceback = ''.join(traceback.format_exception(*sys.exc_info()))
        self.log_exception(msg=exception_name)
        ctx = {
            'usermsg': exception_name,
            'errormsg': exception_details,
            'flashes': self.session.get_flashes()}

        if users.is_current_user_admin() or is_testenv():
            ctx.update({'traceback': exception_traceback})
        if users.is_current_user_admin():
            admin_user = True
            logout_url = users.create_logout_url('/')
            ctx.update({
                'logout_url': logout_url,
                'is_admin': admin_user,
                'request': self.request,
                'current_uri': self.request.uri})

            self.response.out.write(template.render('templates/errors.html', ctx))
        else:
            self.session.add_flash('%s' % exception_name, level='alert-error')
            self.redirect(self.request.uri)
コード例 #17
0
ファイル: main.py プロジェクト: kcvrgopal/Flashlight
 def post(self):
   secret = self.request.get('secret')
   is_update = False
   if len(secret):
     plugins = Plugin.query(Plugin.secret == secret).fetch()
     if len(plugins) == 0:
       send_upload_form(self, "No plugin could be found that matches that secret.")
       return
     else:
       plugin = plugins[0]
     is_update = True
   else:
     plugin = Plugin()
   plugin.zip_url = 'http://' + os.environ['HTTP_HOST'] + '/serve/' + str(self.get_uploads('zip')[0].key())
   if not read_plugin_info(plugin):
     send_upload_form(self, "We couldn't find a valid info.json file in your zip.")
     return
   plugin.secret = base64.b64encode(os.urandom(128))
   plugin.notes = self.request.get('notes')
   if users.is_current_user_admin():
     existing = Plugin.query(Plugin.name == plugin.name).fetch()
     if len(existing):
       existing[0].approved = False
       existing[0].put()
   if users.is_current_user_admin():
     plugin.approved = True
   plugin.put()
   approval_msg = " It'll be public after it's been approved." if not is_update else ""
   message = "Your plugin was uploaded!" + approval_msg
   self.response.write(template("uploaded.html", {"message": message, "plugin": plugin}))
コード例 #18
0
ファイル: support.py プロジェクト: SecondFriend/second-friend
    def get(self):

        # keep non-admin users away
        if not users.is_current_user_admin():
            self.redirect("/")

        # if user is an admin
        # render support page
        if users.is_current_user_admin():

            # get counselor, if new, then insert
            counselor = Counselor.get_or_insert(str(users.get_current_user().user_id()))

            # set default counselor name to user's nickname
            if not counselor.name:
                counselor.name = users.get_current_user().nickname()

            # update user status to 1 - ready for work!
            counselor.status = 1
            counselor.put()

            template_vars = {
                "app_name": settings.APP_NAME,
                "counselor": counselor,
                "logout_url": "/logout",
                "where": "Support",
            }

            self._output_template("support.html", **template_vars)
コード例 #19
0
ファイル: main.py プロジェクト: aungkozaw/zawgyi
 def get(self):
     if users.is_current_user_admin():
         return self.redirect("/manageforums")
     MAX_FORUMS = 256  # if you need more, tough
     forums = db.GqlQuery("SELECT * FROM Forum").fetch(MAX_FORUMS)
     tvals = {"forums": forums, "isadmin": users.is_current_user_admin(), "log_in_out": get_log_in_out("/")}
     template_out(self.response, "forum_list.html", tvals)
コード例 #20
0
ファイル: tickuser.py プロジェクト: cheesun/chees-test
 def get_or_create(cls,user=None):
     if not user:
         user = users.get_current_user()
     if not user:
         raise Exception('not logged in - cannot get or create TickUser')
     existing = cls.all().filter('all_users = ',user).get()
     if not existing:
         invitations = None
         if not users.is_current_user_admin():
             invitations = Invitation.all().filter('email_address =',user.email().lower()).fetch(1000)
         if users.is_current_user_admin() or invitations:
             existing = cls(
                 tick_name       = user.nickname(),
                 email_address   = user.email(),
                 all_users       = [user],
                 all_user_ids    = [user.user_id()],
                 )
             existing.put()
             # add inviters as followers
             if invitations:
                 from follow import Follow
                 for invite in invitations:
                     Follow.add_follower(existing,invite.inviter)
             # add default lists
             from ticklist import TickList
             from setlist import SetList
             TickList.create_list('Suggestions for Tick','public')
             getting_started = SetList.all(keys_only=True).filter('name =','getting started with tick').get()
             if getting_started:
                 TickList.create_from_setlist('Getting Started',getting_started.id())
             TickUserStat.generate_stats(existing) # TODO: create a new stats infrastructure
         else:
             raise NotInvitedError('not invited')
     return existing
コード例 #21
0
ファイル: me.py プロジェクト: studyindenmark/newscontrol
 def get(self):
     """ Return info about current logged in user
     
     Automatically create internal user models for admin google users.
     """
     user = utils.get_current_user()
     
     if not user:
         google_user = users.get_current_user()
         
         if not google_user:
             self.error(403)
             return
         
         if users.is_current_user_admin():
             user = utils.create_user(google_user)
         else:
             self.error(401)
             return
     
     data = user.to_struct()
     data['is_admin'] = users.is_current_user_admin()
     
     self.response.headers['Content-Type'] = 'application/json; charset=utf-8'
     self.response.headers['Access-Control-Allow-Origin'] = '*'
     self.response.out.write(json.dumps(data))
コード例 #22
0
ファイル: main.py プロジェクト: alg0002/ssm4gae
 def get(self):
     c=get_content(self.request.path)
     if c and (c.public or users.is_current_user_admin()):
         if c.entitytype=='text':
             if self.returntext(c):
                 return
         elif c.entitytype=='file':
             if self.returnfile(c):
                 return
         elif c.entitytype=='alias':
             if c.aliastarget and c.aliastarget.startswith('http://'):
                 from google.appengine.api import urlfetch
                 result=urlfetch.fetch(url=c.aliastarget)
                 self.response.headers["Content-Type"]=result.headers["Content-Type"]
                 self.response.out.write(result.content)
                 return
             else:
                 c=get_content(c.aliastarget)
                 if c and (c.public or users.is_current_user_admin()):
                     if c.entitytype=='text':
                         if self.returntext(c):
                             return
                     elif c.entitytype=='file':
                         if self.returnfile(c):
                             return
     self.error(404)
コード例 #23
0
    def post(self):
        user = users.get_current_user()
        if not user:
            self.redirect(users.create_login_url(self.request.uri))
            return
        account = self.get_account()
        if (account):
            self.redirect(self.url("dashboard"))
            return

        if config.admin_only and not users.is_current_user_admin():
            self.redirect(self.url("home"))
            return

        if not self.request.get('accept_terms'):
            path = os.path.join(config.TEMPLATES_DIR, 'signup.html')
            template_values = self.get_common_template_values()
            template_values.update({'form_action' : self.url("signup"),
                                    'form_error' : 'You must read and agree the terms of service to create an account'});
            self.response.out.write(template.render(path, template_values))
            return
        else:
            account = models.Account()
            account.user = user
            if config.moderate_signups and not users.is_current_user_admin():
                account.enabled = False
            else:
                account.enabled = True
            account.put()
            self.redirect(self.url("dashboard"))
            return
コード例 #24
0
def getTag(tag=None,id=None):
    if request.args.get('q'):return redirect(url_for('searchresults',q=request.args.get('q')))
    if users.is_current_user_admin() and request.method=="DELETE":
     
        apost=APost(id=id)
        apost.delete()
        return jsonify(msg="OK")
    
    elif users.is_current_user_admin() and request.method=="PUT":
        title=request.json['title']
        body=request.json['body']
        date=request.json['date']
        category=request.json['category']
        posttags=request.json['tags']
        apost=APost(title,body,date,category,posttags,id)
        (data,returnedTags)=apost.update()
        return jsonify(msg="OK",tags=returnedTags,posts=data)
        
    if tag!=None:
        if request.method=="GET":
            action=Action()
            data=action.getall(tagname=tag)
            return  jsonify(msg="OK",posts=data,type="tag")
     
            
    else:  
        tagss=[]
        a=Action()
        [tagss.append([Tag.tag,Tag.key().id()]) for Tag in a.tags]
        tags=map(lambda tag:{"tag":tag[0],"id":tag[1]} ,tagss)
     
      
  
        return jsonify(msg="OK",tags=tags,header="My Tags used",type="tags")
コード例 #25
0
ファイル: illserver.py プロジェクト: JoshuaBWright/illrequest
	def post(self):
		if users.get_current_user() and users.is_current_user_admin():
			key_string = self.request.get('requestKey')
			dismiss_edit_to = urllib.unquote(self.request.get('dismissEditTo'))
			ill_request = ILLRequest.get(key_string)
			is_admin_user = users.is_current_user_admin()
			
			articleEditorGroup_name = self.request.get('articleEditorGroup_name')
			article_editors = ArticleEditor.all().ancestor(articleEditor_key(articleEditorGroup_name))
			
			libraryGroup_name = self.request.get('libraryGroup_name')
			libraries = Library.all().ancestor(library_key(libraryGroup_name))
			
			form_handler_path = '/submit_request_edit'
			submit_message = 'Edit Request'

			if ill_request:
				template_values = {
					'ill_request_prefill': ill_request,
					'article_editors': article_editors,
					'libraries': libraries,
					'form_handler_path': form_handler_path,
					'is_admin_user': is_admin_user,
					'submit_message': submit_message,
					'dismiss_edit_to': dismiss_edit_to,
				}
				template = jinja_environment.get_template('request_form.html')
				self.response.out.write(template.render(template_values))
		else:
			self.redirect('/')
コード例 #26
0
ファイル: handlers.py プロジェクト: writinglin/commonfunction
 def render(self, templateValues, template, contentType='text/html'):
     self.response.headers['Content-Type'] = contentType
     templateValues['request'] = self.request
     user = users.get_current_user()
     analytics_code = self.site.get('analytics_code')
     if user:
         templateValues['user'] = user
         templateValues['user_admin'] = users.is_current_user_admin()
         if users.is_current_user_admin():
             templateValues['ga_disabled'] = True
         templateValues['logout_url'] = users.create_logout_url('/')
     if self.session.get('ga'):
         templateValues['ga_disabled'] = True
     elif 'ga' in self.request.GET:
         self.session['ga'] = True
         templateValues['ga_disabled'] = True
     if templateValues.get('ga_disabled'):
         analytics_code = None
     templateValues['site'] = self.site
     templateValues['i18n'] = self.i18n
     templateValues['analytics_code'] = analytics_code
     if self.extraValues:
         for key, value in self.extraValues.iteritems():
             if key not in templateValues:
                 templateValues[key] = value
     templateValues['request'] = self.request
     content = self.jinja2.render_template(template, **templateValues)
     self.response.out.write(content)
コード例 #27
0
ファイル: __init__.py プロジェクト: DebRez/mtt
    def check(self, *args):
        logging.debug('check_login %s: <%s> admin = %s user = %s' % 
                      (self.__class__.__name__, self.request.method, str(users.is_current_user_admin()), str(self.user)))

        user = users.get_current_user()
        
        if not user:
            greeting = ("<a href=\"%s\">Sign in or register</a>." %
                  users.create_login_url("/"))
            self.response.set_status(401) # Unauthorized
            self.response.out.write("<html><body>%s</body></html>" % greeting)
            return
        
        if not users.is_current_user_admin() and self.user is None:
            if self.request.method == 'GET':
                credential = [user.email(), None]
                self.user = authenticate(credential)
                if self.user is None:
                    self.redirect('%s?%s=%s' % ('/login/', 'next', urllib.quote(self.request.uri)))
                    return
            elif self.request.method == 'POST':
                self.user = authenticate(get_credential())
                if self.user is None:
                    self.response.set_status(401) # Unauthorized
                    return

        handler_method(self, *args)
コード例 #28
0
    def get(self):

        path = os.path.join(os.path.dirname(__file__), 'index.phtml')

        if users.get_current_user():
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Déconnexion'
        else:
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Connexion'
            path = os.path.join(os.path.dirname(__file__), 'login.phtml')

        template_values = {
            'user': users.get_current_user(),
            'admin': users.is_current_user_admin(),
            'url': url,
            'url_linktext': url_linktext,
            'page_header': template.render('header.html', {
                    'user': users.get_current_user(),
                    'admin': users.is_current_user_admin(),
                    'url': url,
                    'url_linktext': url_linktext,
                }),
            'page_footer': template.render('footer.html', {}),
            }

        self.response.out.write(template.render(path, template_values))
コード例 #29
0
ファイル: main.py プロジェクト: eReader/epubhub
    def post(self):
        enforce_login(self)
        if self.request.get('license') is not None and not users.is_current_user_admin():
            self.redirect("/")
        epub = db.get(self.request.get('epub_key'))
        if not users.is_current_user_admin() and epub.entry_count()>1:
            self.redirect("/")
        epub.language = self.request.get('language')
        epub.title = self.request.get('title')
        epub.creator = self.request.get('creator')
        epub.publisher = self.request.get('publisher')
        epub.rights = self.request.get('rights')
        epub.contributor = self.request.get('contributor')
        epub.identifier = self.request.get('identifier')
        epub.description = self.request.get('description')
        epub.date = self.request.get('date')

        license = self.request.get('license')
        if epub.license != license:
            if license=="Public Domain" or license=="Creative Commons":
                unpacker = unpack.Unpacker()
                unpacker.index_epub(epub, "public")
            else:
                index = search.Index("public")
                opts = search.QueryOptions(limit = 1000, ids_only = True)
                query = search.Query(query_string = "book:%s" % epub.key(), options=opts)
                docs = index.search(query)
                for doc in docs:
                    index.remove(doc.doc_id)

        epub.license = self.request.get('license')
        epub.put()
        self.redirect("/book/"+str(epub.key().id()))
コード例 #30
0
ファイル: shell.py プロジェクト: ata/emotiongraph
  def get(self):
    # set up the session. TODO: garbage collect old shell sessions
    session_key = self.request.get('session')
    if session_key:
      session = Session.get(session_key)
    else:
      # create a new session
      session = Session()
      session.unpicklables = [db.Text(line) for line in INITIAL_UNPICKLABLES]
      session_key = session.put()

    template_file = os.path.join(os.path.dirname(__file__), 'templates',
                                 'shell.html')
    session_url = '/?session=%s' % session_key
    vars = { 'server_software': os.environ['SERVER_SOFTWARE'],
             'python_version': sys.version,
             'session': str(session_key),
             'user': users.get_current_user()
             }
             
    user = users.get_current_user()
    if user == None:
        vars.update({'login_url': users.create_login_url(self.request.uri),
                                'admin': users.is_current_user_admin(),
                                'login_label':'login'})
    else:
        vars.update({'login_url': users.create_logout_url(self.request.uri),
                                'login_label':'logout',
                                'admin': users.is_current_user_admin(),
                                'nickname':user.nickname()})
    
    
    rendered = webapp.template.render(template_file, vars, debug=_DEBUG)
    self.response.out.write(rendered)
コード例 #31
0
def get_testcase_detail(testcase):
  """Get testcase detail for rendering the testcase detail page."""
  config = db_config.get()
  crash_address = testcase.crash_address
  crash_state = testcase.crash_state
  crash_state_lines = crash_state.strip().splitlines()
  crash_type = data_handler.get_crash_type_string(testcase)
  reproduction_help_url = data_handler.get_reproduction_help_url(
      testcase, config)
  external_user = not access.has_access(job_type=testcase.job_type)
  issue_url = issue_tracker_utils.get_issue_url(testcase)
  metadata = testcase.get_metadata()
  original_testcase_size = _get_blob_size_string(testcase.fuzzed_keys)
  minimized_testcase_size = _get_blob_size_string(testcase.minimized_keys)
  stack_clean_regex_lines = config.stack_clean_regex
  has_issue_tracker = bool(data_handler.get_issue_tracker_name())

  if not testcase.regression:
    regression = 'Pending'
  elif testcase.regression == 'NA':
    regression = 'NA'
  else:
    regression = _get_revision_range_html_from_string(testcase.job_type,
                                                      testcase.regression)

  fixed_full = None
  if 'progression_pending' in metadata:
    fixed = 'Pending'
  elif not testcase.fixed:
    fixed = 'NO'
  elif testcase.fixed == 'NA':
    fixed = 'NA'
  elif testcase.fixed == 'Yes':
    fixed = 'YES'
  else:
    fixed = 'YES'
    fixed_full = _get_revision_range_html_from_string(testcase.job_type,
                                                      testcase.fixed)

  last_tested = None
  last_tested_revision = (
      metadata.get('last_tested_revision') or testcase.crash_revision)
  if last_tested_revision:
    last_tested = _get_revision_range_html(testcase.job_type,
                                           last_tested_revision)

  crash_revision = testcase.crash_revision
  crash_revisions_dict = revisions.get_component_revisions_dict(
      crash_revision, testcase.job_type)
  crash_stacktrace = data_handler.get_stacktrace(testcase)
  crash_stacktrace = filter_stacktrace(crash_stacktrace, testcase.crash_type,
                                       stack_clean_regex_lines,
                                       crash_revisions_dict)
  crash_stacktrace = convert_to_lines(crash_stacktrace, crash_state_lines,
                                      crash_type)
  crash_stacktrace_preview_lines = _preview_stacktrace(crash_stacktrace)

  second_crash_stacktrace_revision = metadata.get(
      'second_crash_stacktrace_revision')
  second_crash_stacktrace_revisions_dict = (
      revisions.get_component_revisions_dict(second_crash_stacktrace_revision,
                                             testcase.job_type))
  second_crash_stacktrace = data_handler.get_stacktrace(
      testcase, stack_attribute='second_crash_stacktrace')
  second_crash_stacktrace = filter_stacktrace(
      second_crash_stacktrace, testcase.crash_type, stack_clean_regex_lines,
      second_crash_stacktrace_revisions_dict)
  second_crash_stacktrace = convert_to_lines(second_crash_stacktrace,
                                             crash_state_lines, crash_type)
  second_crash_stacktrace_preview_lines = _preview_stacktrace(
      second_crash_stacktrace)

  last_tested_crash_revision = metadata.get('last_tested_crash_revision')
  last_tested_crash_revisions_dict = revisions.get_component_revisions_dict(
      last_tested_crash_revision, testcase.job_type)
  last_tested_crash_stacktrace = data_handler.get_stacktrace(
      testcase, stack_attribute='last_tested_crash_stacktrace')
  last_tested_crash_stacktrace = filter_stacktrace(
      last_tested_crash_stacktrace, testcase.crash_type,
      stack_clean_regex_lines, last_tested_crash_revisions_dict)
  last_tested_crash_stacktrace = convert_to_lines(last_tested_crash_stacktrace,
                                                  crash_state_lines, crash_type)
  last_tested_crash_stacktrace_preview_lines = _preview_stacktrace(
      last_tested_crash_stacktrace)

  privileged_user = access.has_access(need_privileged_access=True)

  # Fix build url link. |storage.cloud.google.com| takes care of using the
  # right set of authentication credentials needed to access the link.
  if 'build_url' in metadata:
    metadata['build_url'] = metadata['build_url'].replace(
        'gs://', 'https://storage.cloud.google.com/')

  pending_blame_task = (
      testcase.has_blame() and 'blame_pending' in metadata and
      metadata['blame_pending'])
  pending_impact_task = (
      testcase.has_impacts() and not testcase.is_impact_set_flag)
  pending_minimize_task = not testcase.minimized_keys
  pending_progression_task = ('progression_pending' in metadata and
                              metadata['progression_pending'])
  pending_regression_task = not testcase.regression
  pending_stack_task = testcase.last_tested_crash_stacktrace == 'Pending'
  needs_refresh = (
      testcase.status == 'Pending' or
      ((testcase.status == 'Processed' or testcase.status == 'Duplicate') and
       (pending_blame_task or pending_impact_task or pending_minimize_task or
        pending_progression_task or pending_regression_task or
        pending_stack_task)))

  if data_types.SecuritySeverity.is_valid(testcase.security_severity):
    security_severity = label_utils.severity_to_string(
        testcase.security_severity)
  else:
    security_severity = None

  auto_delete_timestamp = None
  auto_close_timestamp = None

  if testcase.one_time_crasher_flag:
    last_crash_time = (
        crash_stats.get_last_crash_time(testcase) or testcase.timestamp)

    # Set auto-delete timestamp for unreproducible testcases with
    # no associated bug.
    if not testcase.bug_information:
      auto_delete_timestamp = utils.utc_datetime_to_timestamp(
          last_crash_time + datetime.timedelta(
              days=data_types.UNREPRODUCIBLE_TESTCASE_NO_BUG_DEADLINE))

    # Set auto-close timestamp for unreproducible testcases with
    # an associated bug.
    if testcase.open and testcase.bug_information:
      auto_close_timestamp = utils.utc_datetime_to_timestamp(
          last_crash_time + datetime.timedelta(
              days=data_types.UNREPRODUCIBLE_TESTCASE_WITH_BUG_DEADLINE))

  memory_tool_display_string = environment.get_memory_tool_display_string(
      testcase.job_type)
  memory_tool_display_label = memory_tool_display_string.split(':')[0]
  memory_tool_display_value = memory_tool_display_string.split(':')[1].strip()

  helpers.log('Testcase %s' % testcase.key.id(), helpers.VIEW_OPERATION)
  return {
      'id': testcase.key.id(),
      'crash_type': crash_type,
      'crash_address': crash_address,
      'crash_state': crash_state,  # Used by reproduce tool.
      'crash_state_lines': crash_state_lines,
      'crash_revision': testcase.crash_revision,
      'csrf_token': form.generate_csrf_token(),
      'external_user': external_user,
      'footer': testcase.comments,
      'fixed': fixed,
      'fixed_full': fixed_full,
      'issue_url': issue_url,
      'is_admin': users.is_current_user_admin(),
      'metadata': metadata,
      'minimized_testcase_size': minimized_testcase_size,
      'needs_refresh': needs_refresh,
      'original_testcase_size': original_testcase_size,
      'privileged_user': privileged_user,
      'regression': regression,
      'crash_stacktrace': {
          'lines':
              crash_stacktrace,
          'preview_lines':
              crash_stacktrace_preview_lines,
          'revision':
              revisions.get_real_revision(
                  crash_revision, testcase.job_type, display=True)
      },
      'second_crash_stacktrace': {
          'lines':
              second_crash_stacktrace,
          'preview_lines':
              second_crash_stacktrace_preview_lines,
          'revision':
              revisions.get_real_revision(
                  second_crash_stacktrace_revision,
                  testcase.job_type,
                  display=True)
      },
      'last_tested_crash_stacktrace': {
          'lines':
              last_tested_crash_stacktrace,
          'preview_lines':
              last_tested_crash_stacktrace_preview_lines,
          'revision':
              revisions.get_real_revision(
                  last_tested_crash_revision, testcase.job_type, display=True)
      },
      'security_severity': security_severity,
      'security_severities': data_types.SecuritySeverity.list(),
      'stats': {
          'min_hour': crash_stats.get_min_hour(),
          'max_hour': crash_stats.get_max_hour(),
      },
      'suspected_cls': _parse_suspected_cls(metadata.get('predator_result')),
      'testcase': testcase,
      'timestamp': utils.utc_datetime_to_timestamp(testcase.timestamp),
      'show_blame': testcase.has_blame(),
      'show_impact': testcase.has_impacts(),
      'impacts_production': testcase.impacts_production(),
      'find_similar_issues_options': FIND_SIMILAR_ISSUES_OPTIONS,
      'auto_delete_timestamp': auto_delete_timestamp,
      'auto_close_timestamp': auto_close_timestamp,
      'memory_tool_display_label': memory_tool_display_label,
      'memory_tool_display_value': memory_tool_display_value,
      'last_tested': last_tested,
      'is_admin_or_not_oss_fuzz': is_admin_or_not_oss_fuzz(),
      'has_issue_tracker': has_issue_tracker,
      'reproduction_help_url': reproduction_help_url,
  }
コード例 #32
0
ファイル: handlers.py プロジェクト: nebulae/rainwater
 def dispatch(self):
     admin = users.is_current_user_admin()
     if admin:
         super(AdminAuthenticatedTemplateHandler, self).dispatch()
     else:
         self.redirect(users.create_login_url('/'))
コード例 #33
0
    def authenticate(self, google_user=None):
        """
        Handles authentication of a user from the given credentials.
        Credentials must be a 'google_user' as returned by the App Engine
        Users API.
        """
        if google_user is None:
            return None

        User = get_user_model()

        if not issubclass(User, GaeAbstractBaseUser):
            raise ImproperlyConfigured(
                "AppEngineUserAPIBackend requires AUTH_USER_MODEL to be a "
                " subclass of djangae.contrib.auth.base.GaeAbstractBaseUser.")

        user_id = google_user.user_id()
        email = BaseUserManager.normalize_email(google_user.email())

        try:
            # User exists and we can bail immediately.
            return User.objects.get(username=user_id)
        except User.DoesNotExist:
            pass

        auto_create = should_create_unknown_user()
        user_is_admin = users.is_current_user_admin()

        try:
            existing_user = User.objects.get(email=email)
        except User.DoesNotExist:
            if not (auto_create or user_is_admin):
                # User doesn't exist and we aren't going to create one.
                return None

            existing_user = None

        # OK. We will grant access. We may need to update an existing user, or
        # create a new one, or both.

        # Those 3 scenarios are:
        # 1. A User object has been created for this user, but that they have not logged in yet.
        # In this case wefetch the User object by email, and then update it with the Google User ID
        # 2. A User object exists for this email address but belonging to a different Google account.
        # This generally only happens when the email address of a Google Apps account has been
        # signed up as a Google account and then the apps account itself has actually become a
        # Google account. This is possible but very unlikely.
        # 3. There is no User object realting to this user whatsoever.

        if existing_user:
            if existing_user.username is None:
                # We can use the existing user for this new login.
                existing_user.username = user_id
                existing_user.email = email
                existing_user.last_login = timezone.now()
                existing_user.save()

                return existing_user
            else:
                # We need to update the existing user and create a new one.
                with self.atomic(**self.atomic_kwargs):
                    existing_user = User.objects.get(pk=existing_user.pk)
                    existing_user.email = None
                    existing_user.save()

                    return User.objects.create_user(user_id, email=email)
        else:
            # Create a new user, but account for another thread having created it already in a race
            # condition scenario. Our logic cannot be in a transaction, so we have to just catch this.
            try:
                return User.objects.create_user(user_id, email=email)
            except IntegrityError:
                return User.objects.get(username=user_id)
コード例 #34
0
 def is_current_user_gae_admin(request):  # pylint: disable=unused-argument
   return users.is_current_user_admin()
コード例 #35
0
ファイル: qbrary.py プロジェクト: di445/khanacademy
    def get(self):
        if not users.is_current_user_admin():
            self.redirect(util.create_login_url(self.request.uri))
            return

        user = util.get_current_user()

        # This if/then clause just makes sure that the user is logged in

        if user:
            subject_key = self.request.get('subject_key')
            subject_name = self.request.get('subject_name')  # Get this if editing name of subject
            child_name = self.request.get('child_name')  # Get this if adding child to subject

            # Get the subject key if we are editing its name or adding a child
            # I think this will always be the case so we may want to get rid of the if/then clause and
            # just do the if part

            if subject_key:
                subject = db.get(subject_key)
            else:
                subject = Subject(author=user)

            st = subtopics(subject)
            next_index = st.count() + 1

            # This is the case that someone has created or changed a subject's name (forwards back to profile page)
            # This subject has no parent and no index

            if subject_name:
                subject.name = subject_name
                subject.put()
                self.redirect('/qbrary')
            else:

                # This is the case the someone is adding a subtopic to this subject

                if child_name:
                    child_subject = Subject()
                    child_subject.author = user
                    child_subject.name = child_name
                    child_subject.parent_subject = subject
                    child_subject.index = next_index
                    child_subject.put()
                    st = subtopics(subject)

                    # subtopics = Subject.gql("WHERE parent_subject = :1 ORDER BY index", subject)

                bc = breadcrumb(subject)
                html_tree = htmlChildren(subject)

                root = Subject.gql('WHERE parent_subject=:1', None).get()
                subjects = Subject.gql('WHERE parent_subject = :1', root)
                greeting = 'user: %s [<a href="%s">sign out</a>]' % (user.nickname(), users.create_logout_url('/'))

                template_values = {
                    'subject': subject,
                    'subjects': subjects,
                    'greeting': greeting,
                    'subtopics': st,
                    'tree': html_tree,
                    'breadcrumb': bc,
                    'redirect_url': self.request.uri,
                    }
                path = os.path.join(os.path.dirname(__file__), 'editsubject.html')
                self.response.out.write(template.render(path, template_values))
        else:

            self.redirect(util.create_login_url(self.request.uri))
コード例 #36
0
def is_current_user_super_admin():
    """Checks whether the current user owns this app."""
    return users.is_current_user_admin()
コード例 #37
0
ファイル: roles.py プロジェクト: dgerod/cb4oeu
 def is_direct_super_admin(cls):
     """Checks if current user is a super admin, without delegation."""
     return users.is_current_user_admin()
コード例 #38
0
    def get(self):
        cont = self.request_string('continue', default = "/")

        # Immediately after login we make sure this user has a UserData entity
        user_data = UserData.current()
        if user_data:

            # Update email address if it has changed
            current_google_user = users.get_current_user()
            if current_google_user and current_google_user.email() != user_data.email:
                user_data.user_email = current_google_user.email()
                user_data.put()

            # Update nickname if it has changed
            current_nickname = get_nickname_for(user_data)
            if user_data.user_nickname != current_nickname:
                user_data.user_nickname = current_nickname
                user_data.put()

            # Set developer and moderator to True if user is admin
            if (not user_data.developer or not user_data.moderator) and users.is_current_user_admin():
                user_data.developer = True
                user_data.moderator = True
                user_data.put()

            # If user is brand new and has 0 points, migrate data
            phantom_id = get_phantom_user_id_from_cookies()
            if phantom_id:
                phantom_data = UserData.get_from_db_key_email(phantom_id)

                # First make sure user has 0 points and phantom user has some activity
                if user_data.points == 0 and phantom_data and phantom_data.points > 0:

                    # Make sure user has no students
                    if not user_data.has_students():

                        # Clear all "login" notifications
                        UserNotifier.clear_all(phantom_data)

                        # Update phantom user_data to real user_data
                        phantom_data.user_id = user_data.user_id
                        phantom_data.current_user = user_data.current_user
                        phantom_data.user_email = user_data.user_email
                        phantom_data.user_nickname = user_data.user_nickname

                        if phantom_data.put():
                            # Phantom user was just transitioned to real user
                            user_counter.add(1)
                            user_data.delete()

                        cont = "/newaccount?continue=%s" % cont
        else:

            # If nobody is logged in, clear any expired Facebook cookie that may be hanging around.
            self.delete_cookie("fbsr_" + App.facebook_app_id)
            self.delete_cookie("fbs_" + App.facebook_app_id)

            logging.critical("Missing UserData during PostLogin, with id: %s, cookies: (%s), google user: %s" % (
                    util.get_current_user_id(), os.environ.get('HTTP_COOKIE', ''), users.get_current_user()
                )
            )

        # Always delete phantom user cookies on login
        self.delete_cookie('ureg_id')

        self.redirect(cont)
コード例 #39
0
 def have_access(self):
     return users.is_current_user_admin()
コード例 #40
0
 def testLogin(self):
     self.assertFalse(users.get_current_user())
     self.loginUser()
     self.assertEquals(users.get_current_user().email(), '*****@*****.**')
     self.loginUser(is_admin=True)
     self.assertTrue(users.is_current_user_admin())
コード例 #41
0
 def post(self, message_id):
     if not users.is_current_user_admin():
         return self.render_template("not_admin.html")
     result = Message.get_by_id(int(message_id))
     result.key.delete()
     return self.redirect_to("deleted_list")
コード例 #42
0
def get_view_file(handler, params={}):
    """
    Looks for presence of template files with priority given to 
     HTTP method (verb) and role.
    Full filenames are <handler>.<role>.<verb>.<ext> where
     <handler> = lower-case handler name
     <role> = role of current user
     <verb> = HTTP verb, e.g. GET or POST
     <ext> = html, xml, etc.
    Only <handler> and <ext> are required.
    Properties 'module_name' and 'handler_name' can be passed in 
     params to override the current module/handler name.
     
    Returns:
      Tuple with first element = template file name and
      second element = template directory path tuple
    """
    if 'ext' in params:
        desired_ext = params['ext']
    else:
        desired_ext = 'html'

    verb = handler.request.method.lower()
    app_name = ''
    module_name = None
    handler_name = None
    cls = handler.__class__
    if (cls.__module__.startswith('handlers.')
            and cls.__name__.endswith('Handler')):
        handler_path = cls.__module__.split('.')
        if len(handler_path) == 3:
            app_name = to_filename(handler_path[1])
        module_name = to_filename(handler_path[-1])
        handler_name = to_filename(cls.__name__.partition('Handler')[0])

    if 'app_name' in params:
        app_name = params['app_name']
    if 'module_name' in params:
        module_name = params['module_name']
    if 'handler_name' in params:
        handler_name = params['handler_name']

    # Get template directory hierarchy -- Needed if we inherit from templates
    # in directories above us (due to sharing with other templates).
    themes = config.BLOG['theme']
    if isinstance(themes, basestring):
        themes = [themes]
    template_dirs = []
    views_dir = os.path.join(config.APP_ROOT_DIR, 'views')
    for theme in themes:
        root_folder = os.path.join(views_dir, theme)
        if module_name:
            template_dirs += (os.path.join(root_folder, app_name,
                                           module_name), )
        if app_name:
            template_dirs += (os.path.join(root_folder, app_name), )
        template_dirs += (root_folder, )

    # Now check possible extensions for the given template file.
    if module_name and handler_name:
        entries = templates.get(app_name, {}).get(module_name, {})
        possible_roles = []
        if users.is_current_user_admin():
            possible_roles.append('.admin.')
        if users.get_current_user():
            possible_roles.append('.user.')
        possible_roles.append('.')
        for role in possible_roles:
            filename = ''.join([handler_name, role, verb, '.', desired_ext])
            if filename in entries:
                return {'file': filename, 'dirs': template_dirs}
        for role in possible_roles:
            filename = ''.join([handler_name, role, desired_ext])
            if filename in entries:
                return {'file': filename, 'dirs': template_dirs}
    return {'file': 'notfound.html', 'dirs': template_dirs}
コード例 #43
0
def IsAdmin(unused_action, unused_user, unused_entity):
    """An authorized_function that checks to see if user is an admin."""
    return users.is_current_user_admin()
コード例 #44
0
    def get(self):
        site = memcache.get("site")
        if site is None:
            site = Site.all().get()
            memcache.add("site", site)
        if not site:
            self.redirect('/config')
        else:
            try:
                outputcaptcha = captcha()
                if outputcaptcha:
                    template_values = {
                        'site': site,
                        'captcha': outputcaptcha,
                        'page': 'guestbook',
                        'recentcomments': getrecentcomments(PAGESIZE)
                    }

                    user = users.get_current_user()
                    if user:
                        template_values['logout'] = users.create_logout_url(
                            self.request.uri)
                        template_values['user'] = users.get_current_user()
                        if users.is_current_user_admin():
                            template_values['admin'] = True
                    else:
                        template_values['login'] = users.create_login_url(
                            self.request.uri)

                    comments = memcache.get("comments-none")
                    if comments is None:
                        comments = getcomments(None, None)
                        memcache.add("comments-none", comments)

                    for comment in comments:
                        comment.email = hashlib.new('md5',
                                                    comment.email).hexdigest()

                    template_values['commentcount'] = len(comments)

                    reply = None
                    replykey = self.request.get('reply')
                    if replykey:
                        comment = memcache.get("comment-" + replykey)
                        if comment is None:
                            comment = Comment.all().order("-__key__").filter(
                                '__key__ =', db.Key(replykey)).get()
                            memcache.add("comment-" + replykey, comment)
                        if comment and comment.post == None:
                            reply = {
                                'key': str(replykey),
                                'captcha': outputcaptcha
                            }
                            template_values['reply'] = True

                    commenthtml = outputcomment(None, comments, [], None,
                                                reply)

                    template_values['commenthtml'] = commenthtml

                    if ismobile(self):
                        template_values['mobile'] = True

                    path = os.path.join(os.path.dirname(__file__),
                                        'template/guestbook.html')
                    self.response.out.write(
                        template.render(path, template_values))
                else:
                    self.redirect('/')
            except:
                self.redirect('/')
コード例 #45
0
 def get(self):
     if users.is_current_user_admin():
         self.redirect('/')
     else:
         login_page = users.create_login_url('/')
         self.redirect(login_page)
コード例 #46
0
def outputcomment(post, comments, temp, parentkey, reply):
    commenthtml = ''
    for child in comments:
        if child not in temp:
            if child.parentkey == parentkey or (not parentkey
                                                and not child.parentkey):
                temp.append(child)
                childkey = child.key().__str__()
                commenthtml += '<li class="comment" id="comment-' + childkey + '">'
                if post:
                    commenthtml += '<div class="comment-avator"><a class="comment-permalink" href="/post/' + post + '#comment-' + childkey + '"><img src="http://www.gravatar.com/avatar/' + cgi.escape(
                        child.email.encode('utf-8')) + '?s=48" /></a></div>'
                else:
                    commenthtml += '<div class="comment-avator"><a class="comment-permalink" href="/guestbook#comment-' + childkey + '"><img src="http://www.gravatar.com/avatar/' + cgi.escape(
                        child.email.encode('utf-8')) + '?s=48" /></a></div>'
                commenthtml += '<div class="comment-author">'
                if child.url:
                    commenthtml += '<a href="' + cgi.escape(
                        child.url.encode('utf-8')) + '">'
                if child.author:
                    commenthtml += cgi.escape(child.author.encode('utf-8'))
                else:
                    commenthtml += '匿名'
                if child.url:
                    commenthtml += '</a>'
                commenthtml += '</div>'
                commenthtml += '<div class="comment-info">'
                commenthtml += ' <a class="time">' + cgi.escape(
                    str((child.time + timedelta(hours=+8)).strftime(
                        '%Y-%m-%d %H:%M:%S')).encode('utf-8')) + '</a>'
                commenthtml += '</div>'
                commenthtml += '<div class="comment-content">'
                commenthtml += '<pre>' + cgi.escape(
                    child.content.encode('utf-8')) + '</pre>'
                commenthtml += '</div>'
                commenthtml += '<div class="operate">'
                if not reply or (reply and reply['key'] != childkey):
                    if post:
                        commenthtml += '<a class="reply-link" href="/post/' + post + '?reply=' + childkey + '#comment-form">回复</a>'
                    else:
                        commenthtml += '<a class="reply-link" href="/guestbook?reply=' + childkey + '#comment-form">回复</a>'
                if users.is_current_user_admin():
                    commenthtml += ' <a class="update-link" href="/update/comment?key=' + childkey + '">修改</a>'
                    commenthtml += ' <a class="delete-link" href="/delete/comment?key=' + childkey + '">删除</a>'
                #commenthtml += ' <a class="time">' + cgi.escape(str((child.time + timedelta(hours=+8)).strftime('%Y-%m-%d %H:%M:%S')).encode('utf-8')) + '</a>'
                commenthtml += '</div>'
                if reply and reply['key'] == childkey:
                    commenthtml += '<div id="comment-form">'
                    commenthtml += '<h5>回复评论</h5>'
                    commenthtml += '<form action="/add/comment" method="post">'
                    commenthtml += '<label>名称:<input type="text" name="author" id="comment-author"></label>'
                    commenthtml += '<br />'
                    commenthtml += '<label>邮箱:<input type="email" name="email" id="comment-email"></label>'
                    commenthtml += '<br />'
                    commenthtml += '<label>网址:<input type="url" name="url" id="comment-url"></label>'
                    commenthtml += '<br />'
                    commenthtml += '<label>内容:<textarea name="content" id="comment-content"></textarea></label>'
                    commenthtml += '<br />'
                    commenthtml += '<label>请输入“' + reply[
                        'captcha'] + '”的阿拉伯数字:<input type="number" name="captcha" id="comment-captcha" min="0" max="9"></label>'
                    commenthtml += '<br />'
                    commenthtml += '<input type="submit" value="提交" id="comment-submit">'
                    if post:
                        commenthtml += '<br />'
                        commenthtml += '<input type="hidden" name="post" value="' + post + '" id="comment-post">'
                    commenthtml += '<br />'
                    commenthtml += '<input type="hidden" name="parentkey" value="' + reply[
                        'key'] + '" id="comment-parentkey">'
                    commenthtml += '</form>'
                    commenthtml += '<div class="operate">'
                    if post:
                        commenthtml += '<a class="cancel-link" href="/post/' + post + '#comment-' + reply[
                            'key'] + '">取消</a>'
                    else:
                        commenthtml += '<a class="cancel-link" href="/guestbook#comment-' + reply[
                            'key'] + '">取消</a>'
                    commenthtml += '</div>'
                    commenthtml += '</div>'
                commenthtml += '<ol class="children">'
                commenthtml += outputcomment(post, comments, temp, childkey,
                                             reply)
                commenthtml += '</ol>'
                commenthtml += '</li>'
    return commenthtml
コード例 #47
0
def can_control_experiments():
    from models import UserData
    user_data = UserData.current(bust_cache=True)
    return users.is_current_user_admin() or (user_data and user_data.developer)
コード例 #48
0
    def get(self, str):
        site = memcache.get("site")
        if site is None:
            site = Site.all().get()
            memcache.add("site", site)
        if not site:
            self.redirect('/config')
        else:
            if str != '':
                if str == 'login':
                    self.redirect(users.create_login_url('/'))
                else:
                    self.redirect('/')
            else:
                q = self.request.get('q').strip()
                if q:
                    posts = memcache.get("qposts-" + q)
                    if posts is None:
                        posts = getposts(PAGESIZE, None, q, 'next')
                        memcache.add("qposts-" + q, posts)
                else:
                    posts = memcache.get("posts")
                    if posts is not None and len(posts) != PAGESIZE + 1:
                        memcache.delete("posts")
                        posts = None
                    if posts is None:
                        query = Post.gql('ORDER BY time DESC, __key__ ASC')
                        posts = query.fetch(PAGESIZE + 1)
                        memcache.add("posts", posts)

                if len(posts) == PAGESIZE + 1:
                    posts = posts[:PAGESIZE]
                    next = posts[-1].key()
                else:
                    next = None

                for post in posts:
                    post.content = re.sub(
                        ur'<code(?P<index>.*)>(?P<content>[\s\S]*)</code(?P=index)>',
                        lambda m: '<code>' + cgi.escape(m.group(
                            'content')) + '</code>', post.content)
                    post.comment = memcache.get("postcommentcount-" +
                                                post.key().__str__())
                    if post.comment is None:
                        post.comment = len(
                            getcomments(post.key().__str__(), None))
                        memcache.add(
                            "postcommentcount-" + post.key().__str__(),
                            post.comment)
                    post.time += timedelta(hours=+8)

                template_values = {
                    'site': site,
                    'posts': posts,
                    'previous': None,
                    'recentcomments': getrecentcomments(PAGESIZE),
                    'next': next,
                    'page': 'home'
                }

                user = users.get_current_user()
                if user:
                    template_values['logout'] = users.create_logout_url(
                        self.request.uri)
                    template_values['user'] = users.get_current_user()
                    if users.is_current_user_admin():
                        template_values['admin'] = True
                else:
                    template_values['login'] = users.create_login_url(
                        self.request.uri)

                if q:
                    template_values['q'] = q

                if ismobile(self):
                    template_values['mobile'] = True

                path = os.path.join(os.path.dirname(__file__),
                                    'template/home.html')
                self.response.out.write(template.render(path, template_values))
コード例 #49
0
    def get(self):
        date_time = datetime.datetime.now(
            pytz.timezone('US/Mountain')).strftime("%m/%d '%y &nbsp; %H:%M")
        user = users.get_current_user()
        if user:
            login_key = users.create_logout_url(self.request.uri)
            gate = 'logout'
            admin = ''
            if users.is_current_user_admin():
                admin = 'yes'
        else:
            login_key = users.create_login_url(self.request.uri)
            gate = 'login'
            admin = ''
        site = Site
        logo = Logo
        analytics = Analytics

        CoinBase_Buy_url = 'https://coinbase.com/api/v1/prices/buy'
        CoinBase_Sell_url = 'https://coinbase.com/api/v1/prices/sell'
        BitStamp_url = 'https://www.bitstamp.net/api/ticker/'
        btce_url = 'https://btc-e.com/api/2/btc_usd/ticker'
        coindesk_url = 'https://api.coindesk.com/v1/bpi/currentprice.json'

        CoinBase_Buy_result = urlfetch.fetch(CoinBase_Buy_url)
        if CoinBase_Buy_result.status_code == 200:
            CoinBase_Buy = CoinBase_Buy_result.content
            # print type(CoinBase_Buy)
        else:
            CoinBase_Buy = ''

        CoinBase_Sell_result = urlfetch.fetch(CoinBase_Sell_url)
        if CoinBase_Sell_result.status_code == 200:
            CoinBase_Sell = CoinBase_Sell_result.content
        else:
            CoinBase_Sell = ''

        BitStamp_prices_result = urlfetch.fetch(BitStamp_url)
        if BitStamp_prices_result.status_code == 200:
            BitStamp_prices = BitStamp_prices_result.content
        else:
            BitStamp_prices = ''

        btce_prices_result = urlfetch.fetch(btce_url)
        if btce_prices_result.status_code == 200:
            btce_prices = btce_prices_result.content
        else:
            btce_prices = ''

        coindesk_result = urlfetch.fetch(coindesk_url)
        if btce_prices_result.status_code == 200:
            #coindesk_result = coindesk_result.content
            coindesk_result = json.loads(coindesk_result.content)
            # print "lala:", coindesk_result
            usd_rate = str(coindesk_result['bpi']['USD']['rate'])
            # print "lala:", usd_rate
            # print type(usd_rate)
        else:
            usd_rate = ''

    # - template
        objects = {
            'Site': site,
            'Logo': logo,
            'login_key': login_key,
            'gate': gate,
            'user': user,
            'coinbase_buy': CoinBase_Buy,
            'coinbase_sell': CoinBase_Sell,
            'bitstamp_prices': BitStamp_prices,
            'btce_prices': btce_prices,
            'usd_rate': usd_rate,
            'analytics': analytics,
            'date_time': date_time,
        }
        # - render
        path = os.path.join(os.path.dirname(__file__), 'html/publicSite.html')
        self.response.out.write(template.render(path, objects))
コード例 #50
0
    def get(self, key):
        site = memcache.get("site")
        if site is None:
            site = Site.all().get()
            memcache.add("site", site)
        if not site:
            self.redirect('/config')
        else:
            if key:
                try:
                    q = self.request.get('q').strip()
                    if q:
                        posts = memcache.get("nextqposts-" + key + q)
                        if posts is None:
                            posts = getposts(PAGESIZE, db.Key(key), q, 'next')
                            memcache.add("nextqposts-" + key + q, posts)
                    else:
                        posts = memcache.get("nextposts-" + key)
                        if posts is None:
                            post = Post.all().order("-__key__").filter(
                                '__key__ =', db.Key(key)).get()
                            query = Post.gql(
                                'WHERE time = :time AND __key__ > :key ORDER BY __key__ ASC, time DESC',
                                time=post.time,
                                key=post.key())
                            posts = query.fetch(PAGESIZE + 1)
                            if len(posts) < PAGESIZE + 1:
                                remainder = PAGESIZE + 1 - len(posts)
                                query = Post.gql(
                                    'WHERE time < :time ORDER BY time DESC, __key__ ASC',
                                    time=post.time)
                                moreposts = query.fetch(remainder)
                                posts += moreposts
                            memcache.add("nextposts-" + key, posts)

                    if posts:
                        previous = posts[0].key()
                    else:
                        previous = None
                    if len(posts) == PAGESIZE + 1:
                        posts = posts[:PAGESIZE]
                        next = posts[-1].key()
                    else:
                        next = None

                    for item in posts:
                        item.content = re.sub(
                            ur'<code(?P<index>.*)>(?P<content>[\s\S]*)</code(?P=index)>',
                            lambda m: '<code>' + cgi.escape(m.group(
                                'content')) + '</code>', item.content)
                        item.comment = len(
                            getcomments(item.key().__str__(), None))
                        item.time += timedelta(hours=+8)

                    template_values = {
                        'site': site,
                        'posts': posts,
                        'previous': previous,
                        'next': next,
                        'page': 'next'
                    }

                    user = users.get_current_user()
                    if user:
                        template_values['logout'] = users.create_logout_url(
                            self.request.uri)
                        template_values['user'] = users.get_current_user()
                        if users.is_current_user_admin():
                            template_values['admin'] = True
                    else:
                        template_values['login'] = users.create_login_url(
                            self.request.uri)

                    if q:
                        template_values['q'] = q

                    if ismobile(self):
                        template_values['mobile'] = True

                    path = os.path.join(os.path.dirname(__file__),
                                        'template/home.html')
                    self.response.out.write(
                        template.render(path, template_values))
                except:
                    self.redirect('/')
            else:
                self.redirect('/')
コード例 #51
0
 def wrapper(*args, **kwargs):
     if not users.get_current_user() or not users.is_current_user_admin():
         return redirect(users.create_login_url(request.path))
     return func(*args, **kwargs)
コード例 #52
0
 def dispatch(self):
     admin = users.is_current_user_admin()
     if admin:
         super(AdminAuthenticatedJsonHandler, self).dispatch()
     else:
         self.abort(401, detail="You must be an authenticated administrator to access this resource.")
コード例 #53
0
def include_admin_bit():
    return {'is_admin': users.is_current_user_admin()}
コード例 #54
0
ファイル: main.py プロジェクト: zhaneric/TutoringLog
def is_valid_user():
    return users.get_current_user().email().endswith(restricted_domain(
    )) or restricted_domain() == '' or users.is_current_user_admin()
コード例 #55
0
    def get(self, key):
        site = memcache.get("site")
        if site is None:
            site = Site.all().get()
            memcache.add("site", site)
        if not site:
            self.redirect('/config')
        else:
            if key:
                try:
                    post = memcache.get("post-" + key)
                    if post is None:
                        post = Post.all().order("-__key__").filter(
                            '__key__ = ', db.Key(key)).get()
                        memcache.add("post-" + key, post)
                    outputcaptcha = captcha()
                    if post and outputcaptcha:
                        template_values = {
                            'site': site,
                            'captcha': outputcaptcha,
                            'recentcomments': getrecentcomments(PAGESIZE)
                        }

                        user = users.get_current_user()
                        if user:
                            template_values[
                                'logout'] = users.create_logout_url(
                                    self.request.uri)
                            template_values['user'] = users.get_current_user()
                            if users.is_current_user_admin():
                                template_values['admin'] = True
                        else:
                            template_values['login'] = users.create_login_url(
                                self.request.uri)

                        previouspost = memcache.get("previouspost-" + key)
                        if previouspost is None:
                            previouspost = Post.gql(
                                'WHERE time = :time AND __key__ < :key ORDER BY __key__ DESC, time ASC',
                                time=post.time,
                                key=post.key()).get()
                            if not previouspost:
                                previouspost = Post.gql(
                                    'WHERE time > :time ORDER BY time ASC, __key__ DESC',
                                    time=post.time).get()
                            memcache.add("previouspost-" + key, previouspost)
                        if previouspost:
                            template_values['previouspost'] = previouspost

                        nextpost = memcache.get("nextpost-" + key)
                        if nextpost is None:
                            nextpost = Post.gql(
                                'WHERE time = :time AND __key__ > :key ORDER BY __key__ ASC, time DESC',
                                time=post.time,
                                key=post.key()).get()
                            if not nextpost:
                                nextpost = Post.gql(
                                    'WHERE time < :time ORDER BY time DESC, __key__ ASC',
                                    time=post.time).get()
                            memcache.add("nextpost-" + key, nextpost)
                        if nextpost:
                            template_values['nextpost'] = nextpost

                        comments = memcache.get("comments-" + key)
                        if comments is None:
                            comments = getcomments(key, None)
                            memcache.add("comments-" + key, comments)

                        for comment in comments:
                            comment.email = hashlib.new(
                                'md5', comment.email).hexdigest()

                        template_values['commentcount'] = len(comments)

                        reply = None
                        replykey = self.request.get('reply')
                        if replykey:
                            comment = memcache.get("comment-" + replykey)
                            if comment is None:
                                comment = Comment.all().order(
                                    "-__key__").filter('__key__ =',
                                                       db.Key(replykey)).get()
                                memcache.add("comment-" + replykey, comment)
                            if comment and comment.post == key:
                                reply = {
                                    'key': str(replykey),
                                    'captcha': outputcaptcha
                                }
                                template_values['reply'] = True

                        commenthtml = outputcomment(key, comments, [], None,
                                                    reply)

                        template_values['commenthtml'] = commenthtml

                        if ismobile(self):
                            template_values['mobile'] = True

                        post.content = re.sub(
                            ur'<code(?P<index>.*)>(?P<content>[\s\S]*)</code(?P=index)>',
                            lambda m: '<code>' + cgi.escape(m.group(
                                'content')) + '</code>', post.content)
                        post.time += timedelta(hours=+8)
                        template_values['post'] = post

                        path = os.path.join(os.path.dirname(__file__),
                                            'template/post.html')
                        self.response.out.write(
                            template.render(path, template_values))
                    else:
                        self.redirect('/')
                except:
                    self.redirect('/')
            else:
                self.redirect('/')
コード例 #56
0
def is_admin_or_not_oss_fuzz():
  """Return True if the current user is an admin or if this is not OSS-Fuzz."""
  return not utils.is_oss_fuzz() or users.is_current_user_admin()
コード例 #57
0
ファイル: main.py プロジェクト: ccwen/devtusita
 def isAdmin(self, email):
   if not users.is_current_user_admin():
     self.abort(404)
コード例 #58
0
ファイル: debug.py プロジェクト: rindow/skeleton-mini-webapp2
 def dispatch(self):
     if not users.is_current_user_admin():
         self.redirect('/')
         return
     super(BaseHandler, self).dispatch()
コード例 #59
0
 def get(self):
     if not users.is_current_user_admin():
         return self.render_template("not_admin.html")
     list_ = Message.query(Message.deleted == True).fetch()
     params = {"list_": list_}
     return self.render_template("deleted_list.html", params=params)
コード例 #60
0
ファイル: view.py プロジェクト: giteugen/peeep
def createControls(html, page, cache):
    id = page.key().name().encode('utf-8')[1:]
    user = users.get_current_user()
    url = ADDRESS2 + id
    date2 = ' <div class="peeep_date">%s</div>' % cache.date.strftime(
        '%d %b %Y %H:%M')
    mailshare = 'mailto:?subject=%5Bpeeep%5D%20Get%20a%20link&body=Hi!%0A%0AYour%20friend%20shared%20this%20link%20with%20you:%0A' + urllib.quote(
        url
    ) + '%0A%0A%0A--%0Apeeep%2C%20more%20than%20a%20url%20shortener%0Ahttp://www.peeep.us/'
    twittershare = "http://twitter.com/home?status=" + urllib.quote(url)
    gmailshare = "https://mail.google.com/mail/?view=cm&fs=1&tf=1&to=&su=" + "%5Bpeeep%5D%20Get%20a%20link" + "&body=" + 'Hi!%0A%0AYour%20friend%20shared%20this%20link%20with%20you:%0A' + urllib.quote(
        url
    ) + '%0A%0A%0A--%0Apeeep%2C%20more%20than%20a%20url%20shortener%0Ahttp://www.peeep.us/' + "&zx=BITLY&shva=1&disablechatbrowsercheck=1&ui=1"
    fbshare = 'http://www.facebook.com/sharer.php?u=' + urllib.quote(
        url) + "&t=" + '%5Bpeeep%5D'
    analytics = '''<script type="text/javascript">var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));</script>
<script type="text/javascript">
try { var pageTracker = _gat._getTracker("UA-836471-6"); pageTracker._trackPageview(); }
catch(err) {}</script>'''
    delete = '''<div style="width: 16px; float: right;">
			<form method="post" action="%(peeep)supdate.php">
				<input type="hidden" name="id" value="%(id)s"/><input type="hidden" name="token" value="%(token)s"/>
				<input type="hidden" name="action" value="del"/>
				<input type="image" src="%(peeep)sassets/del.png" alt="delete" title="remove page from peeep"
					onclick="return confirm('Are you sure to remove the page from peeep?');"/>
			</form>
		</div>''' if users.is_current_user_admin() or (
        page.owner == user and page.owner is not None) else ''

    controls = '''<!--PEEEP--><style type="text/css"> 
	html { position: absolute; left: 0; top: 23px; width: 100%%; } body { _margin: 0; }
	#peeep_toolbar, #peeep_toolbar div, #peeep_toolbar input, #peeep_toolbar form { display: block; overflow: hidden;
		margin: 0; padding: 0; text-align: left; zoom: 1; visibility: visible; line-height: 16px; width: auto; height: auto; }
	#peeep_toolbar, #peeep_toolbar div, #peeep_toolbar input, #peeep_toolbar a, #peeep_toolbar span {
		outline: 0; border: 0; color: #999; vertical-align: baseline;
		text-transform: none; white-space: normal; background: none; font: normal 12px Arial, sans-serif; }
	#peeep_toolbar .peeep_wrapper { padding: 3px 10px; border-bottom: 1px solid #cb5; overflow: hidden; zoom: 1; }
	#peeep_toolbar img { border: 0; }
	#peeep_toolbar a:link, #peeep_toolbar a:hover, #peeep_toolbar a:visited, #peeep_toolbar a:active, #peeep_toolbar a:focus { color: #00f; }
	#peeep_toolbar { position:fixed; z-index: 32768; left:0; top: 0px; width:100%%; height: 23px;
		 background: #ffc; }
	#peeep_toolbar .peeep_date { font-size: .8em; color: #cb5; margin: 2px 1em 0 0; float: left; }
	#peeep_toolbar.peeep_verified { background-color: #efd; }
	#peeep_toolbar.peeep_verified .peeep_wrapper { border-bottom: 1px solid #ab9; }
	#peeep_toolbar.peeep_verified .shares:hover, #peeep_toolbar.peeep_verified .shares.hover { background-color: #dfc; }
	#peeep_toolbar.peeep_verified .peeep_date { color: #6a4; }

	#peeep_toolbar .peeep_logo { float: left; margin-right: 1em; margin-bottom: -1em; }
	#peeep_toolbar .original_link { font-size: .9em; color: #999; height: 16px; overflow: hidden; }
	#peeep_toolbar .original_link a { color: #999; }
	#peeep_toolbar .original_link a:visited { color: #bbb; }
	#peeep_toolbar .shares { float: right; line-height: 10px;/*?see Chrome*/ margin: -3px 20px -6px 2em; padding: 3px 3px; }
	#peeep_toolbar .shares img { margin: 0; padding: 0; }
	#peeep_toolbar .shares .share { display: none; margin: 0 0 0 3px; }
	#peeep_toolbar .shares:hover, #peeep_toolbar .shares.hover { background: #eec; }
	#peeep_toolbar .shares:hover .grip, #peeep_toolbar .shares.hover .grip { display: none; }
	#peeep_toolbar .shares:hover .share, #peeep_toolbar .shares.hover .share { display: inline; }
	</style>
	<div id="peeep_toolbar" class="%(toolbar_class)s"><div class="peeep_wrapper">
		<a href="%(peeep)s" class="peeep_logo"><img src="%(peeep)sassets/peeep.png" alt="peeep" title="peeep url shortener" 
			width="16" height="16" /></a>
		%(delete)s
		<div class="shares" onmouseover="this.className='shares hover'" onmouseout="this.className='shares'">
			<a class="share" href="%(mailshare)s"><img src="%(peeep)sassets/mail.png" alt="mail" title="Email this link" width="16" height="16" /></a>
			<a class="share" href="%(gmailshare)s" target="_blank"><img src="%(peeep)sassets/gmail.png" alt="gmail" title="Send this link with GMail" width="16" height="16" /></a>
			<a class="share" href="%(fbshare)s" target="_blank"><img src="%(peeep)sassets/facebook.png" alt="facebook" title="Share on Facebook" width="16" height="16" /></a>
			<a class="share" href="%(twittershare)s" target="_blank"><img src="%(peeep)sassets/twitter.png" alt="twitter" title="Share on Twitter" width="16" height="16" /></a>
			<span class="grip"><img src="%(peeep)sassets/share.png" alt="Share..." width="16" height="16" /></span>
		</div>
		%(date2)s
		<div class="original_link"><a href="%(url)s">%(url)s</a></div>
	</div></div>
	
	%(analytics)s
	
	<!--/PEEEP-->'''
    ctx = {
        'peeep': getEffectiveAddress(),
        'id': id,
        'date2': date2,
        'mailshare': mailshare,
        'twittershare': twittershare,
        'gmailshare': gmailshare,
        'fbshare': fbshare,
        'analytics': analytics,
        'url': cgi.escape(page.url.encode('utf-8'), True),
        'token': tools.token(page, user),
        'toolbar_class': 'peeep_verified' if cache.verified else '',
    }
    ctx['delete'] = delete % ctx
    controls = controls % ctx

    offs = 0
    m = re.match(
        r'''(?isLx)((?:
		\s+ | # just white-space
		<!DOCTYPE\b[^>]*> | <html\b[^>]*> | </?head\b[^>]*> | </?base\b[^>]*> | 
		</?command\b[^>]*> | </?link\b[^>]*> | </?meta\b[^>]*> | </?noscript\b[^>]*> |
		<script\b[^>]*>.*?</script> | # using non-greedy .*?
		<style\b[^>]*>.*?</style> | <title\b[^>]*>.*?</title> | <body\b[^>]*> |
		<!--.*?--> | <!.*?> # comments/DTDs/IE conditionals
		)*)''', html)
    if m:  # skip any heading tags before body
        offs = m.end(0)

    html = html[:offs] + controls + html[offs:]

    return html