def index(req): # check if cookie is set for respondent who already participated client_cookie = Cookie.get_cookie(req, 'rm-group-a') if client_cookie is None: Cookie.add_cookie(req, 'rm-group-a', 'true', expires=time.time() + 31 * 24 * 3600) # expires after 1 month else: return 'You already participated.' # load current respondent conditions with open(PATH, 'r') as f: respondents = yaml.load(f) if respondents is None: respondents = [] no_avatar_count = count_str_in_seq(NO_AVATAR, respondents) avatar_count = count_str_in_seq(AVATAR, respondents) if no_avatar_count <= MIN_RESPONDENTS and avatar_count >= MIN_RESPONDENTS: condition = NO_AVATAR elif no_avatar_count >= MIN_RESPONDENTS and avatar_count <= MIN_RESPONDENTS: condition = AVATAR else: condition = random.choice([NO_AVATAR, AVATAR]) # write new condition entry with open(PATH, 'w') as f: respondents.append(condition) yaml.dump(respondents, f) util.redirect(req, 'welcome' + '-' + condition + '.html')
def index(req): req.content_type = "text/html" sess = Session.Session(req) redirectionSiNonConnecte(req, sess) id_util = sess["id_util"] id_contact = req.form["id_contact"] conn = connexionBD() cur = conn.cursor() sql = "select * from contact where id_contact={} and id_util={};".format( id_contact, id_util) cur.execute(sql) conn.commit() data = cur.fetchall() if not data: req.write( codeHTML( "Erreur !", """ <p>Ce contact ne vous appartient pas.</p> """ + lien('menu.py', "Retour au menu"))) conn.close() else: sql = "delete from contact where id_contact={};".format(id_contact) cur.execute(sql) conn.commit() conn.close() util.redirect(req, "liste.py")
def jump2(req): (status,output)=commands.getstatusoutput('/var/www/script/addUser.sh Jane 123 2.htpasswd') #return output if status==0: util.redirect(req,"/FlowControl/2.html") return apache.OK
def jump4(req): (status,output)=commands.getstatusoutput('/var/www/script/addUser.sh Jane 123 4.htpasswd') if status==0: (status,output)=commands.getstatusoutput('/var/www/script/removeUser.sh Jane 2.htpasswd') (status,output)=commands.getstatusoutput('/var/www/script/removeUser.sh Jane 3.htpasswd') util.redirect(req,"/FlowControl/4.html") return apache.OK
def use_handler(self, func): if self.profile_flag: self.profile("start of app handler") # Call the application callback function. func(self) if self.profile_flag: self.profile("end of app handler") # If a redirect has been requested, redirect now. if self.__redirect_url != None: util.redirect(self.__req, self.__redirect_url) # If no data has been written to the client yet, write any buffered # headers and data. if not self.__data_written: if self.__content_type: self.__req.content_type = self.__content_type self.__write_headers() self.__write_cookies() self.__req.write(self.__buf_data) if self.profile_flag: self.profile("end of mp handler") # Tell Apache the request has been handled successfully. raise apache.SERVER_RETURN, self.get_status_mod_python( self.__http_status)
def metadata(req,scene=None,filename=None): """ show auxilliary metadata files for scenes """ # init AWS module aws = AWS() aws.set_scene(scene) attr = aws.get_scene_attributes() # make sure that name of scene is valid if not aws.is_valid_scene_name(scene): return "Error: invalid scene requested." # make sure that filename is valid if not filename in aws.get_metadata_filenames(): return "Error: invalid filename requested" # strip qi/ subdirectory from cloudmask filename = re.sub('qi/','',filename) # link original file to temporary directory and redirect in_path = "%s/%s/metadata/%s_%s" % (aws.get_basedir(),attr['tile'],scene,filename) out_path = "/home/institut/www/html/data/sentinel2/metatmp/%s_%s" % (scene,filename) out_url = re.sub('/home/institut/www/html','',out_path) if os.path.exists(in_path): if not os.path.exists(out_path): os.symlink(in_path,out_path) redirect(req,out_url) else: return "Error: File %s for scene %s does not exist." % (filename,scene)
def addfield(req,pagelet,field): system = getSystem() system.addField(pagelet,Field(field)) setSystem(system) util.redirect(req,"/pantoto-research/pagelets.py")
def authorize(self): # already authorized if self.get('request_token_key') and self.get('access_token_key'): return # connections to oauth server httpconn = httplib.HTTPConnection('%s:%d'%(self.get('oauth_server'), self.get('oauth_port'))) consumer = liboauth.OAuthConsumer(self.get('consumer_key'), self.get('consumer_secret')) signmeth = liboauth.OAuthSignatureMethod_HMAC_SHA1() # get request token oauth_request = liboauth.OAuthRequest.from_consumer_and_token(consumer, http_url=REQUEST_TOKEN_URL) oauth_request.sign_request(signmeth, consumer, None) httpconn.putrequest(oauth_request.http_method, oauth_request.http_url) for k, v in oauth_request.to_header().items(): httpconn.putheader(k, v) httpconn.putheader('Content-Length', 0) httpconn.endheaders() data = httpconn.getresponse().read() token = liboauth.OAuthToken.from_string(data) self.set('request_token_key', token.key) self.set('request_token_secret', token.secret) # add return uri to row self.set('data_uri', self._req.uri) # authorize token util.redirect(self._req, "%s?oauth_token=%s"%(AUTHORIZATION_URL,token.key))
def authenhandler(req): logger.info("Authentication username: %s", req.user) password = req.get_basic_auth_pw() if req.user == None: util.redirect(req, "/myemsl/error/nopersonid") return apache.HTTP_UNAUTHORIZED user = req.user if user.find('@') != -1: #FIXME Make this fail on error better res = eus2login.eus2login(user, password) if not res.has_key('person_id') or not res['person_id']: return apache.HTTP_UNAUTHORIZED logger.info("Authentication username: %s personid: %s", req.user, res['person_id']) #FIXME add myemsl_id mapping in when we have it req.user = res['person_id'] else: service = 'myemsl' auth = pam.BasicPAMAuth(service, user, password) if not auth.authenticated: return apache.HTTP_UNAUTHORIZED newuser = getuserremote.get_user_remote(user, map='fs_map') if not newuser: logger.error("Failed to get user id for user %s", user) return apache.HTTP_UNAUTHORIZED req.user = newuser return apache.OK
def use_handler(self, func): if self.profile_flag: self.profile("start of app handler") # Call the application callback function. func(self) if self.profile_flag: self.profile("end of app handler") # If a redirect has been requested, redirect now. if self.__redirect_url != None: util.redirect(self.__req, self.__redirect_url) # If no data has been written to the client yet, write any buffered # headers and data. if not self.__data_written: if self.__content_type: self.__req.content_type = self.__content_type self.__write_headers() self.__write_cookies() self.__req.write(self.__buf_data) if self.profile_flag: self.profile("end of mp handler") # Tell Apache the request has been handled successfully. raise apache.SERVER_RETURN, self.get_status_mod_python(self.__http_status)
def addfield(req, pagelet, field): system = getSystem() system.addField(pagelet, Field(field)) setSystem(system) util.redirect(req, "/pantoto-research/pagelets.py")
def handler(req): req.send_http_header() req.content_type = 'text/html;charset=UTF-8' session = Session.Session(req, timeout=3600) session.load() session = session_init(session) oauth_manager = oauthmanager.OAuth_manager(session) calender_api = calenderapi.Calender_api(oauth_manager) #request parameter formValueList = util.FieldStorage(req) #URL에서 파일명 추출 real_file_name = req.filename[req.filename.rfind('/') + 1:] if real_file_name == 'index.html': #등록된 accessToken이 있는지 판단 if oauth_manager.check_access_token(): template = file(config.index_file).read() search_date = formValueList.get( 'date', '%s-%s' % (time.localtime().tm_year, time.localtime().tm_mon)) try: content = createcalender.Create_calender( int(search_date.split('-')[0]), int(search_date.split('-')[1]), calender_api) except ValueError, error: #data 형식이 잘못 되었을 경우 req.write("ValueError -> %s" % error) else: req.write(template % content) else: #등록된 accessToken이 없다면 인증페이지로 util.redirect(req, 'oauth.py')
def delItem(req): config=getConfig(req,req.form['dbname'].value) try: action=req.form['delItem'].lower() except: try: action=req.form['cancel'].lower() except: action='cancel' config=getConfig(req,req.form['dbname']) itemID=req.form['itemID'] selectedHost=config["selectedHost"] tableName=config['itemTable'] idField=config['itemIDfield'] dbname=config['dbname'] # util.redirect(req,"../testValue.py/testvalue?test="+str(req.form)+"*****"+str(action)) if action!='cancel': # delete the record what=doSql(req,"DELETE",itemID,idField,dbname,tableName,selectedHost,"") if what[0]: parameter="?popup=93&errorMessage="+what[0] else: # tell the routine where to return to, home. parameter='' else: # just go home, where ever that is. parameter='' util.redirect(req,"/3t/index.py"+parameter)
def jump3(req): (status, output) = commands.getstatusoutput( '/var/www/script/addUser.sh Jane 123 3.htpasswd') #return output if status == 0: util.redirect(req, "/FlowControl/3.html") return apache.OK
def delSupport(req): # util.redirect(req,"../testValue.py/testvalue?test="+str(req.form.list)) config=getConfig(req,req.form['dbname'].value) supportID=req.form['supportID'] supportTableName=req.form['supportTableName'] # itemID=req.form['itemID'] fieldInfo=getFieldInfo3(req,config['selectedHost'],config['dbname'],supportTableName) try: action=req.form['delSupport'].lower() except: try: action=req.form['cancel'].lower() except: action='cancel' config=getConfig(req,req.form['dbname']) # util.redirect(req,"../testValue.py/testvalue?test="+str(req.form)+"*****"+str(action)) if action!='cancel': # delete the record what=doSql(req,"DELETE",supportID,fieldInfo['idField'],config['dbname'],supportTableName,config["selectedHost"],"") if what[0]: parameter="?popup=93&errorMessage="+what[0] else: # parameter="?media="+mediaRecord parameter="?action=23&supportTableName="+supportTableName else: # parameter="?media="+mediaRecord parameter="?action=23&supportTableName="+supportTableName util.redirect(req,"/3t/index.py"+parameter)
def createUser(req, **args): _startPage(req) _printMenu(req) # req.write(str(args)) if not args.has_key('confirm'): template = psp.PSP(req, filename='templates/template_manage_user.html') template.run({ 'userAdd_URI': (req.parsed_uri[apache.URI_PATH], 'Create'), 'userInfo': [('Name:', 'text', 'name', '', '20', '20'), ('First Name:', 'text', 'first_name', '', '20', '20'), ('UserName:'******'text', 'username', '', '15', '15'), ('Affiliation:', 'textbox', 'affiliation', '', '100', '15', '6'), ('CERN tel. no.:', 'text', 'cern_tel', '', '12', '12'), ('CERN GSM no.:', 'text', 'cern_gsm', '', '12', '12'), ('Known languages:', 'text', 'known_langs', '', '50', '25')] }) else: if args['confirm'] == 'Create': msg = lib.doCreateUser(args) req.write(msg) elif args['confirm'] == 'Modify': if lib.doUpdateUser(args) == SUCCESS: util.redirect(req, SHIFTDB_SCRIPTNAME + '/manageUsers') else: req.write( '<center>Error when trying to modify %s [%s]...</center>' % (args['username'], args['user_id'])) else: req.write('<center>Bad function call...</center>') _endPage(req)
def index(req,page="README"): # make sure the html fetch operation doesn't timeout too early sess = Session(req) sess.set_timeout(20) sess.save() # use the README page as the course index if page == "index": page = "README" # fetch the markdown text from dropbox link = "%s%s"%(githubRoot,page) #req.write(link) try: if page.endswith('.md') or page == 'README': # this is an HTML page req.content_type = "text/html" # give the page a title req.write("<title>ACCAD 5102</title>") # grab the stylesheet req.write("<style>%s</style>"%urllib2.urlopen("%sscreen.css"%webRoot).read()) response = urllib2.urlopen(link) #req.write(response.read()) req.write(markdown.markdown(response.read(), ['tables'])) else: util.redirect(req, link) except: ## raise ## req.write("error") ## e = sys.exc_info()[0] ## req.write(e) req.write("<br>This page does not exist yet")
def GetImage(req, dsname): req.content_type = "image/gif" req.send_http_header() directory = os.path.dirname(req.filename) infofile = os.path.join(directory,'info_files/' + dsname ) try: info = open(infofile , 'r') status = str(info.readline())[0:-1] info.close() if status=='GOOD': util.redirect(req, '../img/green.gif') elif status=='BAD': util.redirect(req, '../img/red.gif') elif status=='DUBIOUS': util.redirect(req, '../img/yellow.gif') else: util.redirect(req, '../img/blue.gif') except IOError: util.redirect(req, '../img/white.gif') return apache.OK
def index(req): """Näytä kirjautumislomake tai tarkista ohjaa etusivulle jos löytyy kelvolliset kirjautumistiedot.""" dom = minidom.parse(htmlpath) # Jos login-lomakkeen tiedot pyynnössä mukana, tehdään tarkistukset. if req.form.getfirst("submit") != None: tunnus = req.form.getfirst("tunnus", "") salasana = req.form.getfirst("salasana", "") virhe = dbutil.verify(tunnus, salasana) # Tallennetaan kirjautuminen ja ohjataan etusivulle jos tiedot ok. if virhe == 0: req.session["kirjautunut"] = "1" req.session.save() modutil.redirect(req, "index.py") # Ilmoitetaan virheistä, jos tiedot väärin. if virhe == 1: msg = u"Virheellinen salasana!" else: msg = u"Käyttäjätunnusta ei löydy!" dom_errmsg = domutil.getContentElementById("error_text", dom) dom_p = dom.createElement("p") dom_errmsg.appendChild(dom_p) dom_p.appendChild(dom.createTextNode(msg)) req.content_type = "application/xhtml+xml; charset=utf-8" html = dom.toxml("utf-8") return html
def handler(req): req.send_http_header() req.content_type = 'text/html;charset=UTF-8' session = Session.Session(req,timeout=3600) session.load() session = session_init(session) oauth_manager = oauthmanager.OAuth_manager(session) calender_api = calenderapi.Calender_api(oauth_manager) #request parameter formValueList = util.FieldStorage(req) #URL에서 파일명 추출 real_file_name = req.filename[ req.filename.rfind('/')+1:] if real_file_name == 'index.html': #등록된 accessToken이 있는지 판단 if oauth_manager.check_access_token(): template = file(config.index_file).read() search_date = formValueList.get('date', '%s-%s'%(time.localtime().tm_year,time.localtime().tm_mon)) try: content = createcalender.Create_calender(int(search_date.split('-')[0]), int(search_date.split('-')[1]), calender_api) except ValueError, error: #data 형식이 잘못 되었을 경우 req.write ("ValueError -> %s" % error) else: req.write (template % content) else: #등록된 accessToken이 없다면 인증페이지로 util.redirect(req,'oauth.py');
def status_img(req, id = 0, style = 0): db = msgrme_read_db() try: style = int(style) except: style = 0 id = db.check_id(id) if not bool(id): util.redirect(req, "%s%02d_fln.png" % (IMGDIR, style)) return "" info = db.get_info(id) s = info[3] db.close() del db if s == "NLN": util.redirect(req, "%s%02d_nln.png" % (IMGDIR, style)) elif s == "BSY" or s == 'PHN': util.redirect(req, "%s%02d_bsy.png" % (IMGDIR, style)) elif s == "IDL" or s == "AWY" or s == "BRB" or s == "LUN": util.redirect(req, "%s%02d_awy.png" % (IMGDIR, style)) else: util.redirect(req, "%s%02d_fln.png" % (IMGDIR, style)) return ""
def sessionCheck(session, req): """ensure the session is valid What this does depends on config.AUTH_TYPE. For config.AUTH_TYPE=='NONE', do nothing. For config.AUTH_TYPE=='HTTP', raise an exception if req.user is None. For config.AUTH_TYPE=='FORM', if user is not logged in, redirect to a login page (the login page should redirect back to the caller's url). Due to the latter case, this must be called before any output is written to the client. """ log("sessionCheck called", session, req) if config.AUTH_TYPE=='NONE': log("sessionCheck passed", session, req) pass elif config.AUTH_TYPE=='HTTP': if req.user is None: log("sessionCheck failed", session, req) raise Exception("HTTP authentication misconfiguration (req.user is None)") else: log("sessionCheck passed", session, req) elif config.AUTH_TYPE=='FORM': if session.is_new() or not session.has_key('username'): log("sessionCheck failed", session, req) try: util.redirect(req, 'login.psp?redirect=%s' % urllib.quote_plus(req.unparsed_uri)) except apache.SERVER_RETURN: #fix for pre-3.3.1 bug where it uses apache.OK instead of apache.DONE (https://issues.apache.org/jira/browse/MODPYTHON-140) raise apache.SERVER_RETURN, apache.DONE else: log("sessionCheck passed", session, req) else: raise Exception("sanity check")
def index(req): # check if cookie is set for respondent who already participated client_cookie = Cookie.get_cookie(req, 'rm-group-a') if client_cookie is None: Cookie.add_cookie(req, 'rm-group-a', 'true', expires=time.time()+31*24*3600) # expires after 1 month else: return 'You already participated.' # load current respondent conditions with open(PATH, 'r') as f: respondents = yaml.load(f) if respondents is None: respondents = [] no_avatar_count = count_str_in_seq(NO_AVATAR, respondents) avatar_count = count_str_in_seq(AVATAR, respondents) if no_avatar_count <= MIN_RESPONDENTS and avatar_count >= MIN_RESPONDENTS: condition = NO_AVATAR elif no_avatar_count >= MIN_RESPONDENTS and avatar_count <= MIN_RESPONDENTS: condition = AVATAR else: condition = random.choice([NO_AVATAR, AVATAR]) # write new condition entry with open(PATH, 'w') as f: respondents.append(condition) yaml.dump(respondents, f) util.redirect(req, 'welcome' + '-' + condition + '.html')
def authorize(self): # already authorized if self.get('request_token_key') and self.get('access_token_key'): return # connections to oauth server httpconn = httplib.HTTPConnection( '%s:%d' % (self.get('oauth_server'), self.get('oauth_port'))) consumer = liboauth.OAuthConsumer(self.get('consumer_key'), self.get('consumer_secret')) signmeth = liboauth.OAuthSignatureMethod_HMAC_SHA1() # get request token oauth_request = liboauth.OAuthRequest.from_consumer_and_token( consumer, http_url=REQUEST_TOKEN_URL) oauth_request.sign_request(signmeth, consumer, None) httpconn.putrequest(oauth_request.http_method, oauth_request.http_url) for k, v in oauth_request.to_header().items(): httpconn.putheader(k, v) httpconn.putheader('Content-Length', 0) httpconn.endheaders() data = httpconn.getresponse().read() token = liboauth.OAuthToken.from_string(data) self.set('request_token_key', token.key) self.set('request_token_secret', token.secret) # add return uri to row self.set('data_uri', self._req.uri) # authorize token util.redirect(self._req, "%s?oauth_token=%s" % (AUTHORIZATION_URL, token.key))
def logout(req): # util.redirect(req,"../testValue.py/testvalue?test="+repr(req.form)) config=getConfig(req,req.form['dbname'].value) action=req.form['action'].value try: req.form['logout'].value data=kooky2.myCookies(req,'get','',config['dbname'],config['selectedHost']) data['username']='' data['userpass']='' kookied=kooky2.myCookies(req,'save',data,config['dbname'],config['selectedHost']) #~ util.redirect(req,"../testValue.py/testvalue?test="+repr(kookied)) except: pass if action=='15': parameter='?media='+req.form['media'] else: # parameter='?media='+req.form['media'] parameter='?action='+req.form['action'] util.redirect(req,"../index.py"+parameter)
def xvmpilomarCreate(req): """ Called when creating a new user; On success it should generate the directory with a proper success message """ """ conn = sqlite3.connect("/var/www/m/site.db") cur = conn.cursor() cur.execute("insert into newusers (usrname, imgsrc, createdate, occupation, authcookie, password, email, phone, language, gender)\ values(req.form['usrname']+ req.form['passwd'] +\ req.form[''] +\ req.form[''] +\ req.form[''] +\ )") """ if req.method != "POST": util.redirect(req, location = '/m/hell', permanent = False, text = "Only POST accepted") forAuthCookie = ['z', '7', 'x', 'O', 'L', 'n', 'M', 'k', 'w', 'a', '1', '3', '2'] newUsername = req.form['usrname'] newFulluser = req.form['fullusr'] newPassword = req.form['passwd'] newEmail = req.form['email'] newPhone = req.form['phone'] newOccup = req.form['occupation'] newGender = req.form['gender_radio'] newLang = req.form['langSelect'] newImage = req.form['picturefile'] newGenAuthCookie = mmfao2K98Lbkkg(forAuthCookie, 17) newCreatedate = '24-06-2014_23:40:01' uploadImg(newImage) ret = newImage.filename +" :: " + newUsername + ":: " + newFulluser + ":: " + newPassword + ":: " + newEmail + ":: " + newPhone + ":: " + newOccup + ":: " + newGender + ":: " + newLang + ":: " + newGenAuthCookie + ":: " """ """ conn = sqlite3.connect("/var/www/m/site.db") # conn = sqlite3.connect("/var/www/m/site.db") """ conn.execute(""INSERT INTO newusers (usrname, imgsrc, createdate, password, email) VALUES(?, ?, ?, ?, ?);"", (newUsername, 'uidpics/'+newImage, newCreatedate, newPassword, newEmail)) """ conn.execute("""INSERT INTO newusers (usrname, imgsrc, createdate, lastlogin,\ occupation, authcookie, password, email, phone, language, gender)\ VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);""", (newUsername,\ 'uidpics/'+newImage.filename, newCreatedate, 'noLoginYet', newOccup, newGenAuthCookie, newPassword,\ newEmail, newPhone, newLang, newGender)) conn.commit() conn.close() return generateDir(req, 'createUser') # return "tot:"+ ret + "-- " +os.getcwd() """
def addhandler(req,username,action,user,pagelet,field,perm): system = getSystem() system.addHookToAction(username, action,{user:{pagelet:{field:perm}}}) setSystem(system) util.redirect(req,"/pantoto-research/transitions.py")
def reqHTML(req): s = Session.Session(req) if s.has_key("username") and s["username"] == "root": req.content_type = "text/html" req.send_http_header() req.write("<link rel=\"stylesheet\" href=\"../styles.css\">") else: util.redirect(req, "../../index.html")
def redirect(self, url, twice=False): if twice: # Redirecting twice can possibly fix some problems. FIXME. self.sd.redirect_twice = 1 self.debug(2, "Redirecting from '%s' to '%s'." % ( self.build_url(), url ) ) self.__write_headers() self.__write_cookies() self.profile("redirect: url='%s', twice='%s'" % (url, str(twice))) util.redirect(self.__req, url)
def index(req, username, password): if not (username=="admin" and password==""): util.redirect (req, "index.html") sess = Session.Session(req) sess["login"] = 1 sess.save() util.redirect (req, "home.py")
def index(req, username, password): if not (username == "admin" and password == ""): util.redirect(req, "index.html") sess = Session.Session(req) sess["login"] = 1 sess.save() util.redirect(req, "home.py")
def edit2(req,name="",roomno="",hostel="",rollno="",loginid=""): se=Session.Session(req); if se.is_new()!=1: h=req.form.getlist("hostel"); curs.execute("update account set name='%s', roomno='%s', hostel='%s', rollno='%s', email='%s' where email='%s'"%(name,roomno,h[0],rollno,loginid,se['user'])) se['user']=loginid redirect(req,"home") else: redirect(req,"login")
def edit1(req,courid=0,name="",roomno="",hostel="",type="",fromaddr="",date="",receiver=""): s1=Session.Session(req); if s1.is_new()!=1: w=req.form.getlist("taken"); h=req.form.getlist("hostel"); curs.execute("update courier set name='%s', roomno='%s', hostel='%s', type='%s', fromaddr='%s', date_arrvd='%s', recvd='%s', receiver='%s' where courierid='%s'"%(name,roomno,h[0],type,fromaddr,date,w[0],receiver,courid)) redirect(req,"secpage"); else: redirect(req,"seclogin")
def rediriger(self, location): """ Permet de faire une redirection de page. Utilise la fonction standard de mod_python mais est interfacee pour eviter d'importer le module nessesaire et pour penser a sauvegarder la session. Peut etre surchargee au besoin. """ if str(self.session)!=str({}): self.session.save() util.redirect(self.requete, location)
def login_redirect(req, realm): url = urllib.quote(req.unparsed_uri) if realm == "SetupWizard": realm = "Administrator" realm_str = urllib.quote(realm) redirect_url = '/auth/login?url=%s&realm=%s' % (url, realm_str) util.redirect(req, redirect_url)
def jump4(req): (status, output) = commands.getstatusoutput( '/var/www/script/addUser.sh Jane 123 4.htpasswd') if status == 0: (status, output) = commands.getstatusoutput( '/var/www/script/removeUser.sh Jane 2.htpasswd') (status, output) = commands.getstatusoutput( '/var/www/script/removeUser.sh Jane 3.htpasswd') util.redirect(req, "/FlowControl/4.html") return apache.OK
def redirect(self, url, twice=False): if twice: # Redirecting twice can possibly fix some problems. FIXME. self.sd.redirect_twice = 1 self.debug(2, "Redirecting from '%s' to '%s'." % (self.build_url(), url)) self.__write_headers() self.__write_cookies() self.profile("redirect: url='%s', twice='%s'" % (url, str(twice))) util.redirect(self.__req, url)
def logout(req, url=None, realm='Administrator'): sess = Session.Session(req) sess.set_timeout(uvmlogin.SESSION_TIMEOUT) uvmlogin.delete_session_user(sess, realm) sess.save() sess.unlock() if url == None: return apache.OK else: util.redirect(req, url, text="Logout Successfull")
def handler(req): """Ohjaa kirjautumattomat käyttäjät aina kirjautumissivulle.""" # Päästetään suoraan eteenpäin jos kirjauduttu. if req.session["kirjautunut"] == "1": return apache.OK # Jos kirjautumatta, päästetään vain login-sivulle. ps varo rekursiivisia uudelleenohjauksia if req.filename != loginpath: modutil.redirect(req, "login.py") return apache.OK
def record_and_redirect(request): query = request.parsed_uri[apache.URI_QUERY] logging.debug("got a submit request with query string = %s" % (str(query))) try: log_submission_in_db(request) except: logging.exception("got exception storing this submission in db:\n%s\n" % (str(query))) redirect_url = BASE_HIT_SUBMIT_URL + query util.redirect(request, redirect_url)
def authpost(req,username,password,method,nonce,appid,host,uri): # get the network address of the client address = req.get_remote_host(apache.REMOTE_NOLOOKUP,None) # load the app settings captureSettings = load_capture_settings(req,appid) # setup the uvm and retrieve the app object so we can make the RPC call captureApp = load_rpc_manager(appid) # call the app to authenticate the user authResult = captureApp.userAuthenticate(address, username, urllib.quote(password)) # on successful login redirect to the redirectUrl if not empty # otherwise send them to the page originally requested if (authResult == 0): if captureSettings.get("sessionCookiesEnabled") == True: # Hand the user a cookie cookie = HandlerCookie(req,appid) cookie.set(username) redirectUrl = captureSettings.get('redirectUrl') if (redirectUrl != None and len(redirectUrl) != 0 and (not redirectUrl.isspace())): target = str(redirectUrl) else: if ((host == 'Empty') or (uri == 'Empty')): page = "<HTML><HEAD><TITLE>Login Success</TITLE></HEAD><BODY><H1>Login Success</H1></BODY></HTML>" return(page) raw = urllib.unquote(uri).decode('utf8') if (nonce == 'a1b2c3d4e5f6'): target = str("https://" + host + raw) else: target = str("http://" + host + raw) util.redirect(req, target) return # authentication failed so re-create the list of args that # we can pass to the login page generator args = {} args['METHOD'] = method args['NONCE'] = nonce args['APPID'] = appid args['HOST'] = host args['URI'] = uri # pass the request object and post arguments to the page generator if (authResult == 1): page = generate_page(req,captureSettings,args, _("Invalid username or password. Please try again.") ) elif (authResult == 2): page = generate_page(req,captureSettings,args, _("You are already logged in from another location.") ) else: page = generate_page(req,captureSettings,args, _("The server returned an unexpected error.") ) # return the login page we just created return(page)
def kill(req): req.content_type = 'text/html' if check(req): try: if req.form['cn'] is not None: cmd="kill "+req.form['cn'] sock=connexion(host, port, vpnpasswd, cmd) sock.interact() util.redirect(req,"./main") except Exception, e: raise(str(e))
def handler_html(req): directory = os.path.dirname(__file__) file = "../../../articles/modpython-001.html" target = os.path.join(directory,file) target = os.path.normpath(target) if not os.path.exists(target): return apache.DECLINED util.redirect(req,file,permanent=1)
def util_redirect(req): from mod_python import util if req.main: # Sub request for ErrorDocument. req.write("test failed") return apache.DONE else: if req.phase == "PythonFixupHandler": util.redirect(req, location="/dummy", text="test ok") else: req.write('test failed') return apache.OK
def authzhandler(req): """This handles authorization""" try: user = get_user_remote(req.user) if user: req.user = user return apache.OK else: util.redirect(req, "/myemsl/error/nopersonid") return apache.UNAUTHORIZED except Exception, e: pass
def stop(req, name, params): req.log_error('Stopping vserver %s at request of %s' % (name, req.user)) if vsutil.is_running(name): vsutil.stop(name) time.sleep(3) # note - this redirect is relative because absolute won't work with # our proxypass proxy util.redirect(req, 'status')
def infopost(req, method, nonce, appid, host, uri, agree='empty'): # get the network address of the client address = req.get_remote_host(apache.REMOTE_NOLOOKUP, None) # load the app settings captureSettings = load_capture_settings(req, appid) # setup the uvm and app objects so we can make the RPC call captureApp = load_rpc_manager(appid) # call the app to authenticate the user authResult = captureApp.userActivate(address, agree) # on successful login redirect to the redirectUrl if not empty # otherwise send them to the page originally requested if (authResult == 0): redirectUrl = captureSettings.get('redirectUrl') if (redirectUrl != None and len(redirectUrl) != 0 and (not redirectUrl.isspace())): target = str(redirectUrl) else: if ((host == 'Empty') or (uri == 'Empty')): page = "<HTML><HEAD><TITLE>Login Success</TITLE></HEAD><BODY><H1>Login Success</H1></BODY></HTML>" return (page) raw = urllib.unquote(uri).decode('utf8') if (nonce == 'a1b2c3d4e5f6'): target = str("https://" + host + raw) else: target = str("http://" + host + raw) util.redirect(req, target) return # authentication failed so re-create the list of args that # we can pass to the login page generator args = {} args['METHOD'] = method args['NONCE'] = nonce args['APPID'] = appid args['HOST'] = host args['URI'] = uri # pass the request object and post arguments to the page generator if (authResult == 1): page = generate_page( req, captureSettings, args, _("You must enable the checkbox above to continue.")) else: page = generate_page(req, captureSettings, args, _("The server returned an unexpected error.")) # return the login page we just created return (page)
def logout(self, req): # Invalidate the active session object, thereby # effectively logging out the user. req.session.invalidate() # Redirect the client back to the login page. config = vampire.loadConfig(req, ".vampire") util.redirect(req, config.get("Access", "login_page"))
def puri(req, uri): # XXX: [-1:0] didn't work if req.uri[len(req.uri) - 1] != '/': path = req.uri + '/' user = req.user if anon(user) and luri(path) == None: return apache.HTTP_NOT_FOUND else: util.redirect(req, path) return apache.OK page = luri(uri) return show(req, uri, page)
def login_redirect(req, realm, token=None): url = urllib.quote(req.unparsed_uri) if realm == "SetupWizard": realm = "Administrator" realm_str = urllib.quote(realm) if token != None: redirect_url = '/auth/login?url=%s&realm=%s&token=%s' % (url, realm_str, token) else: redirect_url = '/auth/login?url=%s&realm=%s' % (url, realm_str) util.redirect(req, redirect_url)
def start(req, name, params): req.log_error('Starting vserver %s at request of %s' % (name, req.user)) if not vsutil.is_running(name): if not os.path.exists(os.path.join(cfg.VAR_DB_OPENVPS, 'suspend', name)): vsutil.start(name) time.sleep(3) # note - this redirect is relative because absolute won't work with # our proxypass proxy util.redirect(req, 'status')
def logout(req, url=None, realm='Administrator'): sess = Session.Session(req, lock=0) sess.lock() sess.set_timeout(uvm_login.SESSION_TIMEOUT) uvm_login.delete_session_user(sess, realm) sess.save() sess.unlock() if url == None: return apache.OK else: url = re.sub('[^A-Za-z0-9-_/.#?=]', '', url) # sanitize input util.redirect(req, url) return
def login(req): req.add_common_vars() password = req.form.getfirst('Password', '') if password != '123456': return False username = req.form.getfirst('Username', '') if re.match('^test[0-9]{1,5}$', username) == None: return False util.redirect( req, 'zone.py?serverid=1&openid=' + username + '&openkey=123456&pf=bdtest') return True
def _jumpGame(self): factUrl = config.server_urls.get(str(self._serverid), None) if factUrl == None: self._printError() return pf = 'game' s = pf + str(self._serverid) + self._user + str(self._time) + comm_config.keys['game'] pfkey = md5.new(s).hexdigest().lower() mirrorid = factUrl['mirrorid'] data = 'mid=%d&pf=%s&serverid=%d&openid=%s&time=%d&pfkey=%s'%(mirrorid, pf, self._serverid, self._user, self._time, pfkey) url = factUrl['url'] + '/zone.py?data=%s'%(safe_b64encode(data)) Register.get('LastLoginDB').appendLastServerId(self._user, self._serverid) util.redirect(self._req, url)
def handler(req): req.send_http_header() req.content_type = 'text/html;charset=UTF-8' session = Session.Session(req, timeout=3600) session.load() session = session_init(session) oauth_manager = oauthmanager.OAuth_manager(session) calender_api = calenderapi.Calender_api(oauth_manager) #URL에서 파일명 추출 real_file_name = req.filename[req.filename.rfind('/') + 1:] if real_file_name == 'index.html': #등록된 accessToken이 있는지 판단 if oauth_manager.check_access_token(): util.redirect(req, 'access_resource.py') else: #등록된 accessToken이 없다면 인증페이지로 util.redirect(req, 'oauth.py') elif real_file_name == 'oauth.py': oauth_template = file(config.oauth_file).read() req.write(oauth_template) elif real_file_name == 'request_token.py': #request_token 생성 및 사용자 인증 URL redirect util.redirect(req, oauth_manager.create_reqeust_token()) elif real_file_name == 'callback.py': #callback_url 처리 oauth_manager.create_access_token(req) util.redirect(req, 'index.html') elif real_file_name == 'access_resource.py': for title in calender_api.load_event_by_all('2011-5-1', '2011-5-31'): req.write('일정 제목 -> %s<br>' % (title.encode('utf-8'))) return apache.OK
def _restoreSession(req): '''Tries to restore a new session. If unsuccessful redirects to the login page ''' if not hasattr(req, 'session'): req.session = Session.Session(req) try: req.session['hits'] += 1 if req.session['user_ip'] != req.get_remote_host(): raise Exception("") # initialise session parameters.... # # print session parameters: req.write(str(req.session.items())) except: # could not restore session so we redirect to a login page util.redirect(req, SHIFTDB_SCRIPTNAME + '/login') return req.session