def resetChangePOST(auth, uid, token): # artificial delay (to slow down brute force attacks) sleep(auth.config.forced_delay) i = web.input() password = i.get('password', '').strip() password2 = i.get('password2', '').strip() try: user = auth._db.select('user', where='user_id = $uid', vars={'uid': uid}).list() if not user: raise AuthError('expired') user = user[0] if not tokens.check_token(user, token, auth.config.reset_expire_after): raise AuthError('expired') if password != password2: raise AuthError('match') if len(password) < auth.config.password_minlen: raise AuthError('bad password') auth.setPassword(user.user_login, password) auth.login(user) except AuthError, e: auth.session.auth_error = str(e) web.found(web.ctx.path) return
def POST(self, uid, token): # artificial delay (to slow down brute force attacks) sleep(auth.config.forced_delay) i = web.input() password = i.get('password', '').strip() password2 = i.get('password2', '').strip() try: user = auth.db.select('user', where='user_id = $uid', vars={'uid': uid}).list() if not user: raise AuthError('expired') user = user[0] if not check_token(user, token, auth.config.reset_expire_after): raise AuthError('expired') if password != password2: raise AuthError('match') if len(password) < auth.config.password_minlen: raise AuthError('bad password') auth.set_password(user.user_login, password) auth.login(user) except AuthError as e: auth.session.auth_error = str(e) web.found(web.ctx.path) return web.found(auth.config.url_after_login) return
def GET(self): if 'facebook_access_token' not in web.ctx.session: raise web.found('/') access_token = web.ctx.session.pop('facebook_access_token') access_token = access_token['access_token'][-1] profile = json.load( urllib.urlopen( "https://graph.facebook.com/me?" + urllib.urlencode(dict(access_token=access_token)))) user = UsersRepository.get(profile['id']) if not user: avatar = 'https://graph.facebook.com/%(id)s/picture?type=large' avatar = avatar % dict(id=profile['id']) user = UsersRepository.add(profile['id'], profile['name'], avatar, access_token) user.token = access_token web.ctx.orm.add(user) web.ctx.orm.commit() # Merge fying and persistent object: this enables us to read the # automatically generated user id user = web.ctx.orm.merge(user) web.setcookie('token', user.token) raise web.found('/settings/parties')
def GET(self): if 'facebook_access_token' in web.ctx.session: raise web.found(web.ctx.path_url + '/authorized') data = web.input(error=None, code=None) if data.error: # The client denied permissions to the app # XXX flash some message here raise web.found('/') if data.code is None: raise web.found(AUTHORIZE_URL + '?' + urllib.urlencode( dict(client_id=web.config.FACEBOOK_APP_ID, redirect_uri=web.ctx.path_url, response_type='code', scope=''))) consumer = oauth2.Consumer(web.config.FACEBOOK_APP_ID, web.config.FACEBOOK_APP_SECRET) client = oauth2.Client(consumer) (resp, content) = client.request( ACCESS_TOKEN_URL + '?' + urllib.urlencode( dict(code=data.code, client_id=web.config.FACEBOOK_APP_ID, client_secret=web.config.FACEBOOK_APP_SECRET, redirect_uri=web.ctx.path_url)), 'GET') if resp['status'] != '200': # XXX flash some message here web.debug(content) raise web.found('/') access_token = urlparse.parse_qs(content) web.ctx.session['facebook_access_token'] = access_token raise web.found(web.ctx.path_url + '/authorized')
def GET(self): if 'facebook_access_token' in web.ctx.session: raise web.found(web.ctx.path_url + '/authorized') data = web.input(error=None, code=None) if data.error: # The client denied permissions to the app # XXX flash some message here raise web.found('/') if data.code is None: raise web.found(AUTHORIZE_URL + '?' + urllib.urlencode( dict(client_id=web.config.FACEBOOK_APP_ID, redirect_uri=web.ctx.path_url, response_type='code', scope='user_events,export_stream,publish_stream'))) consumer = oauth2.Consumer(web.config.FACEBOOK_APP_ID, web.config.FACEBOOK_APP_SECRET) client = oauth2.Client(consumer) (resp, content) = client.request(ACCESS_TOKEN_URL + '?' + urllib.urlencode(dict(code=data.code, client_id=web.config.FACEBOOK_APP_ID, client_secret=web.config.FACEBOOK_APP_SECRET, redirect_uri=web.ctx.path_url)), 'GET') if resp['status'] != '200': # XXX flash some message here web.debug(content) raise web.found('/') access_token = urlparse.parse_qs(content) web.ctx.session['facebook_access_token'] = access_token raise web.found(web.ctx.path_url + '/authorized')
def GET(self): if 'facebook_access_token' not in web.ctx.session: raise web.found('/') access_token = web.ctx.session.pop('facebook_access_token') profile = json.load( urllib.urlopen("https://graph.facebook.com/me?" + urllib.urlencode( dict(access_token=access_token['access_token'][-1])))) newuser = False user = self.current_user() if not user: user = web.ctx.orm.query(User).filter_by(facebook_id=profile['id'], deleted=False).first() if not user: newuser = True user = User(name=profile["name"]) user.facebook_id = profile['id'] web.ctx.orm.add(user) web.ctx.orm.commit() # Merge fying and persistent object: this enables us to read the # automatically generated user id user = web.ctx.orm.merge(user) web.setcookie('user', user.id, COOKIE_EXPIRATION) raise web.found( web.ctx.session.pop('back') if 'back' in web.ctx.session else '/profile' if newuser else '/')
def POST(self, action): token = self.get_token() # Get the form and the form data. form = self.get_form() form.fill(token.dict()) if not form.validates(): # Failed to validate. Display the form again. renderer.addTemplate('action', action) renderer.addTemplate('form', form) errors = form.getnotes() renderer.addDataList('errors', errors) return renderer.render('admin/token/edit.html') else: # Validated - proceed. token.updated = datetime.datetime.now() token.token = form.token.get_value() token.comment = form.comment.get_value() token.put() if renderer.get_mode() == 'html': # Redirect to the list. web.found('/admin/token/') else: # Send back the source data. renderer.addData('token', token) return renderer.render('apionly.html')
def request(self): return_to = self.query.get('return_to', web.ctx.homedomain + web.url('/account')) data = filter(lambda item: item[0] not in ['password'], self.query.items()) form = WebOpenIDLoginForm(password_manager)() session['no_password'] = False if self.method == 'POST': try: if form.validates(self.query): session.login() data.append(('logged_in', True)) return web.found(return_to + '?' + web.http.urlencode(dict(data))) except PasswordManager.NoPassword: session['no_password'] = True session.login() data.append(('logged_in', True)) return web.found(return_to + '?' + web.http.urlencode(dict(data))) web.header('Content-type', 'text/html') return render.login( logged_in=session.logged_in, login_url=web.ctx.homedomain + web.url('/account/login'), logout_url=web.ctx.homedomain + web.url('/account/logout'), change_password_url=web.ctx.homedomain + web.url('/account/change_password'), no_password=session.get('no_password', False), form=form, query=data, )
def POST(self): # Get the form and the form data. form = self.get_form() if not form.validates(): # Failed to validate. Display the form again. renderer.addTemplate('form', form) errors = form.getnotes() renderer.addDataList('errors', errors) return renderer.render('admin/token/login.html') else: # Validated. # Attempt to get an auth token. try: token = AC2DMAuthToken.from_username_password(form.username.get_value(), form.password.get_value()) token.put() if renderer.get_mode() == 'html': # Redirect to the list. web.found('/admin/token/') else: # Send back the source data. renderer.addData('token', token) return renderer.render('apionly.html') except AC2DMTokenException, e: # Failed for some reason! renderer.addData('error', str(e)) renderer.addTemplate('form', form) return renderer.render('admin/token/login.html')
def signupPOST(auth): # artificial delay (to slow down brute force attacks) sleep(auth.config.forced_delay) i = web.input() login = i.get('login', '').strip() password = i.get('password', '').strip() password2 = i.get('password2', '').strip() captcha_on = auth.session.get('captcha_on', False) # if captcha_on: # try: # checkcode_input = i.get('captcha').strip().lower() # checkcode_session = auth.session.captcha_checkcode.lower() # if not checkcode_input == checkcode_session: # raise AuthError('Captcha validation failed: Wrong checkcode!') # except (AttributeError, AuthError): # auth.session.auth_error = 'captcha_wrong' # web.found(auth.config.url_login) # return if password != password2 : print "密码不一致!" return; if password == '' or login == '': return ; user_id = auth.createUser(login, password) web.found("/login") return
def POST(self): # Get the form and the form data. form = self.get_form() if not form.validates(): # Failed to validate. Display the form again. renderer.addTemplate('form', form) errors = form.getnotes() renderer.addDataList('errors', errors) return renderer.render('admin/token/login.html') else: # Validated. # Attempt to get an auth token. try: token = AC2DMAuthToken.from_username_password( form.username.get_value(), form.password.get_value()) token.put() if renderer.get_mode() == 'html': # Redirect to the list. web.found('/admin/token/') else: # Send back the source data. renderer.addData('token', token) return renderer.render('apionly.html') except AC2DMTokenException, e: # Failed for some reason! renderer.addData('error', str(e)) renderer.addTemplate('form', form) return renderer.render('admin/token/login.html')
def resetTokenPOST(auth, email_template=None): template = email_template or auth.config.template_reset_email or render.reset_email i = web.input() login = i.get('login', '').strip() try: if not login: raise AuthError user = auth._db.select('user', where='$login = user_login OR $login = '******'login': login}) if not len(user): raise AuthError user = user[0] from_address = auth.config.email_from to_address = user[auth.config.db_email_field] token = tokens.make_token(user) token_url = '%s%s/%s$%s' % (web.ctx.home, auth.config.url_reset_change, user.user_id, token) print token_url message = template(token_url) subject = message.get('Subject', 'Password reset').strip() headers = dict(message) del headers['__body__'] if 'ContentType' in headers: headers['Content-Type'] = headers['ContentType'].strip() del headers['ContentType'] web.utils.sendmail(from_address, to_address, subject, str(message), headers) except (AuthError, IOError): pass auth.session.auth_token_sent = True web.found(web.ctx.path)
def resetChangePOST(auth, uid, token): # artificial delay (to slow down brute force attacks) sleep(auth.config.forced_delay) i = web.input() password = i.get('password', '').strip() password2 = i.get('password2', '').strip() try: user = auth._db.select('user', where='user_id = $uid', vars={'uid': uid}) if not len(user): raise AuthError, 'expired' user = user[0] if not tokens.check_token(user, token, auth.config.reset_expire_after): raise AuthError, 'expired' if password != password2: raise AuthError, 'match' if len(password) < auth.config.password_minlen: raise AuthError, 'bad password' auth.setPassword(user.user_login, password) auth.login(user) except AuthError, e: auth.session.auth_error = str(e) web.found(web.ctx.path) return
def GET(self): if 'fake_access_token' in web.ctx.session: raise web.found(web.ctx.path_url + '/authorized') web.ctx.session['fake_access_token'] = hashlib.sha256( str(datetime.now())).digest() raise web.found(web.ctx.path_url + '/authorized')
def GET(self): if 'twitter_access_token' not in web.ctx.session: raise web.found('/') access_token = web.ctx.session.pop('twitter_access_token') newuser = False user = self.current_user() if not user: user = web.ctx.orm.query(User).filter_by( twitter_id=access_token['user_id'][-1], deleted=False).first() if not user: newuser = True user = User(name=access_token['screen_name'][-1]) user.twitter_id = access_token['user_id'][-1] web.ctx.orm.add(user) web.ctx.orm.commit() # Merge fying and persistent object: this enables us to read the # automatically generated user id user = web.ctx.orm.merge(user) web.setcookie('user', user.id, COOKIE_EXPIRATION) raise web.found( web.ctx.session.pop('back') if 'back' in web.ctx.session else '/profile' if newuser else '/')
def proxyfunc(iself, *args, **kw): try: # if pars.get('captcha_on', ''): # if self.config.captcha_enabled: # self.session.captcha_on = True # else: # raise AuthError('Captcha is disabled.') print iself, "args=", args, "kw=", kw user = self.session.user if "perm" in pars: if not self.hasPerm(pars["perm"], user): raise PermissionError if "test" in pars: if not pars["test"](user): raise AuthError except (AttributeError, AuthError, SessionExpired): # print sys.exc_info(), " next=", web.ctx.fullpath, " func=", func # pprint(web.ctx) self.session.next = web.ctx.fullpath return web.found(self.config.url_login) except (PermissionError): print "permission deny" return web.found(self.config.permission_deny) return func(iself, *args, **kw)
def GET(self): fpath = xutils.get_argument("path") basename, ext = os.path.splitext(fpath) encoded_fpath = xutils.encode_uri_component(fpath) if xutils.is_text_file(fpath): raise web.found("/code/edit?path=%s" % encoded_fpath) raise web.found("/fs_hex?path=%s" % encoded_fpath)
def GET(self): user = users.get_current_user() if user: # Is logged in. raise web.found('/profile') else: # Not logged in - redirect to login. raise web.found(users.create_login_url(web.url()))
def loginGET(auth, template=None): if auth.session.has_key('user'): web.found(auth.config.url_after_login) return template = template or auth.config.template_login or render.login auth_error = auth.session.get('auth_error', '') if auth_error: del auth.session['auth_error'] return template(error=auth_error, url_reset=auth.config.url_reset_token)
def GET(self, key, value, suffix=''): key = key.lower() if key == 'oclc': key = 'oclc_numbers' elif key == 'ia': key = 'ocaid' if key != 'ocaid': # example: MN41558ucmf_6 value = value.replace('_', ' ') if web.ctx.encoding and web.ctx.path.endswith('.' + web.ctx.encoding): ext = '.' + web.ctx.encoding else: ext = '' if web.ctx.env.get('QUERY_STRING'): ext += '?' + web.ctx.env['QUERY_STRING'] q = {'type': '/type/edition', key: value} result = web.ctx.site.things(q) if result: return web.found(result[0] + ext) elif key == 'ocaid': # Try a range of ocaid alternatives: ocaid_alternatives = [ { 'type': '/type/edition', 'source_records': 'ia:' + value }, { 'type': '/type/volume', 'ia_id': value }, ] for q in ocaid_alternatives: result = web.ctx.site.things(q) if result: return web.found(result[0] + ext) # Perform import, if possible from openlibrary.plugins.importapi.code import ia_importapi, BookImportError from openlibrary import accounts with accounts.RunAs('ImportBot'): try: ia_importapi.ia_import(value, require_marc=True) except BookImportError: logger.exception('Unable to import ia record') # Go the the record created, or to the dummy ia-wrapper record return web.found('/books/ia:' + value + ext) web.ctx.status = '404 Not Found' return render.notfound(web.ctx.path, create=False)
def GET(self): if 'user' in auth.session.keys(): web.found(auth.config.url_after_login) return template = render.login auth_error = auth.session.get('auth_error','') if auth_error: del auth.session['auth_error'] return template(error=auth_error)
def GET(self, path=None): ''' '/(.*)/' redirct to '/(.*)' ''' if path: web.seeother('/' + path) return else: args = web.input() if 'url' in args: web.found(args['url'])
def GET(self,path=None): ''' '/(.*)/' redirct to '/(.*)' ''' if path: web.seeother('/'+path) return else: args = web.input() if 'url' in args: web.found(args['url'])
def GET(self): v = nvdadb.StableVersion.query.order_by(nvdadb.StableVersion.updated_on.desc()).first() i = web.input() if 'type' in i and i.type in ('portable', 'installer'): link = getattr(v, "%s_link" % type) web.found(link) else: d = v.to_dict().copy() d['portable'] = v.portable_link d['installer'] = v.installer_link return d
def GET(self, branch): s = nvdadb.Snapshot.query.filter_by(branch=branch).first() i = web.input() if 'type' in i and i.type in ('portable', 'installer'): link = getattr(s, "%s_link" % type) web.found(link) else: d = s.to_dict().copy() d['portable'] = s.portable_link d['installer'] = s.installer_link return d
def GET(self, key, value, suffix=''): key = key.lower() if key == 'isbn': if len(value) == 13: key = 'isbn_13' else: key = 'isbn_10' elif key == 'oclc': key = 'oclc_numbers' elif key == 'ia': key = 'ocaid' if key != 'ocaid': # example: MN41558ucmf_6 value = value.replace('_', ' ') if web.ctx.encoding and web.ctx.path.endswith('.' + web.ctx.encoding): ext = '.' + web.ctx.encoding else: ext = '' if web.ctx.env.get('QUERY_STRING'): ext += '?' + web.ctx.env['QUERY_STRING'] q = {'type': '/type/edition', key: value} result = web.ctx.site.things(q) if result: return web.found(result[0] + ext) elif key == 'ocaid': # Try a range of ocaid alternatives: ocaid_alternatives = [{ 'type': '/type/edition', 'source_records': 'ia:' + value }, { 'type': '/type/volume', 'ia_id': value }] for q in ocaid_alternatives: result = web.ctx.site.things(q) if result: return web.found(result[0] + ext) # If nothing matched, try this as a last resort: return web.found('/books/ia:' + value + ext) elif key.startswith('isbn'): try: ed_key = create_edition_from_amazon_metadata(value) except Exception as e: logger.error(e) return e.message if ed_key: return web.found(ed_key + ext) web.ctx.status = '404 Not Found' return render.notfound(web.ctx.path, create=False)
def loginGET(auth, template=None): if 'user' in auth.session.keys(): web.found(auth.config.url_after_login) return template = template or auth.config.template_login or render.login auth_error = auth.session.get('auth_error', '') if auth_error: del auth.session['auth_error'] return template(error=auth_error, captcha_on=auth.session.get('captcha_on', False), url_reset=auth.config.url_reset_token)
def GET(self, template=None): if 'user' in auth.session.keys(): web.found(auth.config.url_after_login) return template = template or auth.config.template_login or render.login auth_error = auth.session.get('auth_error', '') if auth_error: del auth.session['auth_error'] return template(error=auth_error, captcha_on=auth.session.get('captcha_on', False), url_reset=auth.config.url_reset_token)
def GET(self, path_key=None): """search files by name and content""" load_rules() key = xutils.get_argument("key", "") title = xutils.get_argument("title", "") category = xutils.get_argument("category", "default") page = xutils.get_argument("page", 1, type=int) user_name = xauth.get_current_name() page_url = "/search/search?key=%s&category=%s&page="\ % (key, category) pagesize = xconfig.SEARCH_PAGE_SIZE offset = (page - 1) * pagesize limit = pagesize if path_key: key = xutils.unquote(path_key) if key == "" or key == None: raise web.found("/search/history") key = key.strip() ctx = Storage() files = self.do_search(ctx, key, offset, pagesize) count = len(files) files = files[offset:offset + limit] fill_note_info(files) return xtemplate.render("search/page/search_result.html", show_aside=False, key=key, html_title="Search", category=category, files=files, title=title, page_max=int(math.ceil(count / pagesize)), page_url=page_url, **ctx)
def request(self): # check for login if not session.logged_in: return WebOpenIDLoginRequired(self.query) form = WebOpenIDChangePasswordForm() if self.method == 'POST': if form.validates(self.query): password_manager.set(self.query['password']) session['no_password'] = False return web.found( homedomain(web.ctx) + web.url('/account')) web.header('Content-type', 'text/html') return render.password( home_url=homedomain(web.ctx) + web.url('/'), logged_in=session.logged_in, logout_url=homedomain(web.ctx) + web.url('/account/logout'), change_password_url=homedomain(web.ctx) + web.url( '/account/change_password'), no_password=session.get('no_password', False), form=form, )
def GET(self): import uuid import datetime db = web.config._db session = web.config._session web.header('Content-Type', 'text/html; charset=utf-8', unique=True) code = web.input().code state = web.input().state cookie_state = web.cookies().get('qqstate') if state != cookie_state: raise web.Forbidden() if code: access_token = self.get_access_token(code) openid = self.get_openid(access_token) nickname = self.get_nickname(access_token, openid) oauth_user_id = 'qq:' + openid user = web.ctx.db.query(db.User).filter_by(oauth_user_id=oauth_user_id).first() if not user: user = db.User(openid) user.app_id = str(uuid.uuid1()) user.user_name = nickname user.oauth_user_id = oauth_user_id user.created_on = datetime.datetime.now() web.ctx.db.add(user) web.ctx.db.commit() session.user = web.storage(app_id=user.app_id, user_id=user.user_id, user_name=user.user_name) logging.info('qq logined:%s', session.user) return web.found('/')
def POST(self): user = self.current_user user.party_id = web.input(party_id=None).party_id web.ctx.orm.add(user) web.ctx.orm.commit() raise web.found('/settings/tubi')
def GET(self): dates = [datetime.today() - timedelta(i) for i in range(1000)] categories = 'foo bar baz qux quux corge grault'.split() notes = [ s.strip() for s in '''Past the sticky heritage relaxes a waved aunt. A widest noise resigns a barred cue. When can the patience stagger? A vowel beards the victory. Her market damages the disposable anarchy. An alcoholic release mounts the preferable routine. The mighty concentrate breathes within the muddle.''' .split('\n') ] amounts = range(-30, 15) for _ in xrange(1000): e = Expense(user_id=self.current_user().id, date=random.choice(dates), category=random.choice(categories), note=random.choice(notes), amount=random.choice(amounts)) web.ctx.orm.add(e) if not Categories.exists(e.category, self.current_user().id): web.ctx.orm.add( Categories.new(e.category, self.current_user().id)) web.ctx.orm.commit() raise web.found('/')
def request(self): # check for login if not session.logged_in: return WebOpenIDLoginRequired(self.query) form = WebOpenIDChangePasswordForm() if self.method == 'POST': if form.validates(self.query): password_manager.set(self.query['password']) session['no_password'] = False return web.found( _secure_homedomain(web.ctx) + web.url('/account')) web.header('Content-type', 'text/html') return render.password( home_url=_secure_homedomain(web.ctx) + web.url('/'), logged_in=session.logged_in, logout_url=_secure_homedomain(web.ctx) + web.url('/account/logout'), change_password_url=_secure_homedomain(web.ctx) + web.url('/account/change_password'), no_password=session.get('no_password', False), form=form, )
def callback(): i = web.input() code = i.get("code", None) if code: # /callback?code=xxx client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET) token = client.request_access_token(code, _CALLBACK_URL) logging.info("got access token: %s" % str(token)) uid = token.uid kw = dict(access_token=token.access_token, expires_in=token.expires_in) # check for update: if 0 == db.update("user", where="uid=$uid", vars=dict(uid=uid), **kw): # create user: client.set_access_token(token.access_token, token.expires_in) user = client.get.users__show(uid=uid) kw["uid"] = uid kw["name"] = user.screen_name kw["gender"] = user.gender kw["province_code"] = user.province kw["city_code"] = user.city kw["image_url"] = user.profile_image_url db.insert("user", **kw) # make a cookie: web.setcookie("weibouser", _make_cookie(uid, token.access_token), int(token.expires_in - time.time())) raise web.found("/index")
def request(self, trusted_id): # check for login if not session.logged_in: return WebOpenIDLoginRequired(self.query) try: trust_root = dict(trust_root_store.items())[trusted_id] except: return web.notfound() if self.method == 'POST': trust_root_store.delete(trust_root) session['trusted_removed_successful'] = True return web.found( _secure_homedomain(web.ctx) + web.url('/account/trusted')) web.header('Content-type', 'text/html') return render.trusted_confirm( home_url=_secure_homedomain(web.ctx) + web.url('/'), logged_in=session.logged_in, logout_url=_secure_homedomain(web.ctx) + web.url('/account/logout'), change_password_url=_secure_homedomain(web.ctx) + web.url('/account/change_password'), check_trusted_url=_secure_homedomain(web.ctx) + web.url('/account/trusted'), trusted_remove_url=_secure_homedomain(web.ctx) + web.url('/account/trusted/%s/delete' % trusted_id), no_password=session.get('no_password', False), trust_root=trust_root, )
def GET(self): items = [item for item in get_ol_dumps() if item.startswith("ol_cdump")] if not items: raise web.notfound() item = items[-1] raise web.found(download_url(item, item + ".txt.gz"))
def request(self, trusted_id): # check for login if not session.logged_in: return WebOpenIDLoginRequired(self.query) try: trust_root = dict(trust_root_store.items())[trusted_id] except: return web.notfound() if self.method == 'POST': trust_root_store.delete(trust_root) session['trusted_removed_successful'] = True return web.found(web.ctx.homedomain + web.url('/account/trusted')) web.header('Content-type', 'text/html') return render.trusted_confirm( logged_in=session.logged_in, logout_url=web.ctx.homedomain + web.url('/account/logout'), change_password_url=web.ctx.homedomain + web.url('/account/change_password'), check_trusted_url=web.ctx.homedomain + web.url('/account/trusted'), trusted_remove_url=web.ctx.homedomain + web.url('/account/trusted/%s/delete' % trusted_id), no_password=session.get('no_password', False), trust_root=trust_root, )
def GET(self): kvdb = sae.kvdb.KVClient() if hasattr(self, 'update_info'): import time time.sleep(8) raise web.found('/howareyou') this_quote = self.update_info else: try: today_quotes = kvdb.get_by_prefix(const.QUOTE_PREFIX) except: today_quotes = Nothing() #else None is not iterable today_quote_probs = 0 if not today_quotes else 3.5 try: weather = kvdb.get('weather') except: weather = Nothing() #else None is not iterable weather_probs = 0 if not weather else 2 this_quote = Howareyou.weighted_pick([(quotes, 1), ([q[1] for q in today_quotes], today_quote_probs), ([weather], weather_probs)]) # this_quote = random.choice(quotes) # if web.input().get('from') == 'poly': # this_quote = '''<p><b>松江天气(<a href='http://www.weather.com.cn/weather/101020900.shtml'>11/21 10:00</a>)</b></p>小雨转小到中雨,东风3-4级,12℃~15℃,当前气温8°。''' web.header('Content-Type', 'text/html; charset=utf-8', unique=True) web.header('Content-Length', len(this_quote), unique=True) web.header('X-How-Are-You', 'fine', unique=True) return this_quote
def proxyfunc(iself, *args, **kw): try: user = self.session.user except (AttributeError, AuthError, SessionExpired): self.session.next = web.ctx.fullpath return web.found(self.config.url_login) return func(iself, *args, **kw)
def GET(self, prefix, date): item = "ol_dump_" + date if item not in get_ol_dumps(): raise web.notfound() else: filename = "ol_dump" + prefix + "_" + date + ".txt.gz" raise web.found(download_url(item, filename))
def GET(self): if auth.get_user(): raise web.found('/?edit') if web.ctx.env.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest': return render_partial.auth.login(loginForm()) else: return render.auth.login(loginForm())
def POST(self): # artificial delay (to slow down brute force attacks) sleep(auth.config.forced_delay) i = web.input() login = i.get('username1', '').strip() password = i.get('password', '').strip() user = auth.authenticate(login, password) if not user: auth.session.auth_error = 'fail' web.found(auth.config.url_login) return else: auth.login(user) web.found(auth.config.url_after_login)
def GET(self, prefix): items = [item for item in get_ol_dumps() if item.startswith("ol_dump")] if not items: raise web.notfound() item = items[-1] filename = item.replace("dump", "dump" + prefix) + ".txt.gz" raise web.found(download_url(item, filename))
def wrapped(self, id, *args): try: server = data.get_server_for_request(id) except data.NotFound: raise web.notfound() if server != config.get('server', 'fqdn'): raise web.found("http://%s%s" % (server, web.ctx.path)) return function(self, id, *args)
def redirect(id): size_part = size and ("-" + size) or "" url = f"/{category}/id/{id}{size_part}.jpg" query = web.ctx.env.get('QUERY_STRING') if query: url += '?' + query raise web.found(url)
def GET(self): client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, callback=CALLBACK_URL) request_token = client.get_request_token() # 保存request_token: self.save_request_token(request_token.oauth_token, request_token.oauth_token_secret) url = client.get_authorize_url(request_token.oauth_token) # redirect to url raise web.found(url)
def GET(self, id): id = int(id) change = web.ctx.site.get_change(id) if not change: web.ctx.status = "404 Not Found" return render.notfound(web.ctx.path) raise web.found(change.url())
def redirect(id): size_part = size and ("-" + size) or "" url = "/%s/id/%s%s.jpg" % (category, id, size_part) query = web.ctx.env.get('QUERY_STRING') if query: url += '?' + query raise web.found(url)
def GET(self): fpath = xutils.get_argument("path") basename, ext = os.path.splitext(fpath) encoded_fpath = xutils.encode_uri_component(fpath) if ext == ".txt": raise web.found("/fs_text?path=%s" % encoded_fpath) if ext in (".html", ".htm"): raise web.found("/fs/%s" % encoded_fpath) if ext in (".md", ".csv"): raise web.found("/code/preview?path=%s" % encoded_fpath) if ext in (".key", ".numbers"): os.system("open %r" % fpath) parent_fpath = os.path.abspath(os.path.dirname(fpath)) encoded_parent = xutils.encode_uri_component(parent_fpath) raise web.found("/fs/%s" % encoded_parent) if ext == ".db": raise web.found("/tools/sql?path=%s" % encoded_fpath) if xutils.is_text_file(fpath): raise web.found("/code/edit?path=%s" % encoded_fpath) raise web.found("/fs/%s" % encoded_fpath)
def GET(self): fpath = xutils.get_argument("path") basename, ext = os.path.splitext(fpath) encoded_fpath = xutils.encode_uri_component(fpath) if ext == ".txt": raise web.found("/fs_text?path=%s" % encoded_fpath) if ext in (".html", ".htm"): raise web.found("/fs/%s" % encoded_fpath) if ext in (".md", ".csv"): raise web.found("/code/preview?path=%s" % encoded_fpath) if xutils.is_text_file(fpath): raise web.found("/code/edit?path=%s" % encoded_fpath) raise web.found("/fs/%s" % encoded_fpath)
def login_required(): if not users.get_current_user(): if renderer.get_mode() == 'html': # Redirect to a login page, coming back here when done. raise web.found(users.create_login_url(web.url())) elif renderer.get_mode() == 'json': # Return an error in JSON. renderer.addData('error', 'Not logged in.') return renderer.render('apionly.html')