def general_authenhandler(req, req_type, anon_ok=False): pw = req.get_basic_auth_pw() cookies = Cookie.get_cookies(req) if not cookies.has_key('csrftoken'): cookie = Cookie.Cookie( 'csrftoken', hashlib.md5(str(random.randrange(0, 2 << 63))).hexdigest()) cookie.path = '/' if config.get('session', 'cookie_host') != '': cookie.domain = config.get('session', 'cookie_host') Cookie.add_cookie(req, cookie) if cookies.has_key('myemsl_session'): sql = "select user_name from myemsl.eus_auth where session_id = %(sid)s" cnx = myemsldb_connect(myemsl_schema_versions=['1.0']) cursor = cnx.cursor() cursor.execute(sql, {'sid': cookies['myemsl_session'].value}) rows = cursor.fetchall() found = False for row in rows: req.user = row[0] found = True if found: logger.debug("Session: %s", str(cookies['myemsl_session'].value)) #FIXME outage_check seems to be in the wrong place for a myemsl database outage. return outage_check(req, req_type) elif anon_ok: req.user = '' return outage_check(req, req_type) url = urllib.quote(req.unparsed_uri) redirect(req, "/myemsl/auth?url=%s" % (url)) return apache.HTTP_UNAUTHORIZED
def __init__(self, req): """get, extract info, and do upkeep on the session cookie. This determines what the sessid and user are for this request.""" #pass the request in making in so we can edit it later if requested (ACL for example) self.ip = req.connection.remote_ip c = Cookie.get_cookies(req) if not c.has_key('mps'): self.sessid = Uid().new_sid(req) else: c = c['mps'] self.sessid = c.value #make new cookie so the cycle continues c = Cookie.Cookie('mps', self.sessid) c.path = '/' Cookie.add_cookie(req, c) self.session_path = "%s%s"%(path_to_sessions, self.sessid) self.full_session_path = "%s%s"%(self.session_path, db_extension) #use previous authenication until cookie is reevaluated, if they are officially logged in (in Instance) if os.path.exists(self.full_session_path): session = shelve.open(self.session_path, 'rw') self.user = session['USER_'] session.close() else: self.user = self.unauthorized
def set_browser_info(self, info): """ sets the "state" info for the browser """ #info = base64.encodestring(repr(info)) info = repr(info) Cookie.add_cookie(self.req, Cookie.Cookie('browseinfo', info))
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): # 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 _set_cookie(self, value, **attrs): """(session_id : string) Ensure that a session cookie with value 'session_id' will be returned to the client via the response object. Since Mod_Python has its own Cookie management system, we use it. """ config = get_publisher().config name = config.session_cookie_name domain = config.session_cookie_domain if config.session_cookie_path: path = config.session_cookie_path else: path = get_request().get_environ('SCRIPT_NAME') if not path.endswith("/"): path += "/" expires = -1 options = {'expires': expires, 'path': path } if domain is not None: options.update({'domain':domain}) if value: Cookie.add_cookie(self.modpython_request, name, value, **options) return name
def general_authenhandler(req, req_type, anon_ok=False): pw = req.get_basic_auth_pw() cookies = Cookie.get_cookies(req) if not cookies.has_key('csrftoken'): cookie = Cookie.Cookie('csrftoken', hashlib.md5(str(random.randrange(0, 2<<63))).hexdigest()) cookie.path = '/' if config.get('session', 'cookie_host') != '': cookie.domain = config.get('session', 'cookie_host') Cookie.add_cookie(req, cookie) if cookies.has_key('myemsl_session'): sql = "select user_name from myemsl.eus_auth where session_id = %(sid)s" cnx = myemsldb_connect(myemsl_schema_versions=['1.0']) cursor = cnx.cursor() cursor.execute(sql, {'sid':cookies['myemsl_session'].value}) rows = cursor.fetchall() found = False for row in rows: req.user = row[0] found = True if found: logger.debug("Session: %s", str(cookies['myemsl_session'].value)) #FIXME outage_check seems to be in the wrong place for a myemsl database outage. return outage_check(req, req_type) elif anon_ok: req.user = '' return outage_check(req, req_type) url = urllib.quote(req.unparsed_uri) redirect(req, "/myemsl/auth?url=%s" %(url)) return apache.HTTP_UNAUTHORIZED
def logout(req): cookies = Cookie.get_cookies(req) Cookie.add_cookie(req, 'ogtvogh', '', expires=time.time(), path='/') req.status=apache.HTTP_MOVED_TEMPORARILY req.headers_out["Location"] = SITEURL req.send_http_header() return "You have successfully logged out"
def set(self,username): value = { "username": username } cookie = Cookie.MarshalCookie(self.cookie_key, value, secret=str(self.captureSettings["secretKey"])) cookie.path = "/" cookie.expires = time.time() + int(self.captureSettings["sessionCookiesTimeout"]) Cookie.add_cookie(self.req, cookie)
def __write_cookies(self): self.debug(2, "Output cookies:") for key in self.__cookies_out: self.debug( 2, "Outputing cookie: %s ==> %s." % (key, self.__cookies_out[key])) # This is wierd.... Cookie.add_cookie(self.__req, self.__cookies_out[key])
def set_cookie(self, coname, codata, expires=None): if self.reallympy: from mod_python import Cookie cookie = Cookie.Cookie(coname, codata) #for simplicity cookie.path = '/' if expires: cookie.expires = expires Cookie.add_cookie(self.mpyreq, cookie)
def _add_csrf_cookie_if_needed(req): signed_cookies = Cookie.get_cookies(req, Cookie.SignedCookie, secret=_get_secret()) cookie = signed_cookies.get(settings.csrf_cookie_name, None) if cookie: # make sure we aren't altered if type(cookie) is Cookie.SignedCookie and cookie.value == _message_contents(): return Cookie.add_cookie(req, _generate_csrf_cookie())
def index(req): req.content_type = "text/html" html = open("/var/www/html/templates/home.html").read() cookie_string = "False, RmFsc2U=" cookie = Cookie.Cookie("admin", cookie_string) timestamp = time.time() + 300 cookie.expires = timestamp Cookie.add_cookie(req, cookie) req.write(html)
def expire(self): value = {} cookie = Cookie.MarshalCookie(self.cookie_key, value, secret=str( self.captureSettings["secretKey"])) cookie.path = "/" cookie.expires = 0 Cookie.add_cookie(self.req, cookie)
def send_cookies(self): """ sends the http headers for any cookies that need to be set """ if self.req != None: for c in self._cookies: Cookie.add_cookie(self.req,c) else: for c in self._cookies: print c
def set(self, var, val): ck = scs.encode(self.s, val, len(val)) if ck is None: raise Exception, 'failed scs.encode()' c = Cookie.Cookie(var, ck) Cookie.add_cookie(self.req, c) return ck
def index(req): secret = 'my_secret' marshal_cookies = Cookie.get_cookies(req, Cookie.MarshalCookie, secret=secret) returned_marshal = marshal_cookies.get('marshal', None) if(returned_marshal): returned_marshal.expires= time.time() Cookie.add_cookie(req, returned_marshal) return '<html><body>return to main place <a href="./">here</a></body></html>' else: return '<html><title></title><body>there is nothing <a href="./">back</a></body></html>'
def set(self, username): value = {"username": username} cookie = Cookie.MarshalCookie(self.cookie_key, value, secret=str( self.captureSettings["secretKey"])) cookie.path = "/" cookie.expires = time.time() + int( self.captureSettings["sessionCookiesTimeout"]) Cookie.add_cookie(self.req, cookie)
def index(req): # get the network address of the client address = req.get_remote_host(apache.REMOTE_NOLOOKUP, None) # use the path from the request filename to locate the correct template name = req.filename[:req.filename.rindex('/')] + "/exitpage.html" file = open(name, "r") page = file.read() file.close() # load the app settings captureSettings = load_capture_settings(req) # setup the uvm and app objects so we can make the RPC call captureList = load_rpc_manager_list() # track the number of successful calls to userLogout exitCount = 0 # call the logout function for each app instance cookie_key = "__ngfwcp" for app in captureList: exitResult = app.userLogout(address) cookies = Cookie.get_cookie(req, cookie_key) if cookies != None: value = {} cookie = Cookie.MarshalCookie(cookie_key, value, secret=str( captureSettings["secretKey"])) cookie.path = "/" cookie.expires = 0 Cookie.add_cookie(req, cookie) if (exitResult == 0): exitCount = exitCount + 1 if (exitCount == 0): page = replace_marker(page, '$.ExitMessage.$', _('You were already logged out')) page = replace_marker(page, '$.ExitStyle.$', 'styleProblem') else: page = replace_marker(page, '$.ExitMessage.$', _('You have successfully logged out')) page = replace_marker(page, '$.ExitStyle.$', 'styleNormal') page = replace_marker(page, '$.CompanyName.$', captureSettings['companyName']) page = replace_marker(page, '$.PageTitle.$', captureSettings['basicLoginPageTitle']) # return the logout page we just created return (page)
def _add_csrf_cookie_if_needed(req): signed_cookies = Cookie.get_cookies(req, Cookie.SignedCookie, secret=_get_secret()) cookie = signed_cookies.get(settings.csrf_cookie_name, None) if cookie: # make sure we aren't altered if type(cookie ) is Cookie.SignedCookie and cookie.value == _message_contents( ): return Cookie.add_cookie(req, _generate_csrf_cookie())
def Cookie_Cookie(req): from mod_python import Cookie cookies = Cookie.get_cookies(req) for k in cookies: Cookie.add_cookie(req, cookies[k]) req.write("test ok") return apache.OK
def Cookie_MarshalCookie(req): from mod_python import Cookie cookies = Cookie.get_cookies(req, Cookie.MarshalCookie, secret="secret") for k in cookies: Cookie.add_cookie(req, cookies[k]) req.write("test ok") return apache.OK
def logout(self, REQUEST): """ logs out and redirects to main page """ Cookie.add_cookie(self.req, Cookie.Cookie("sessionkey", "", expires=0)) Cookie.add_cookie(self.req, Cookie.Cookie("browseinfo", "", expires=0)) self.info = {} links = {"banner": "menu", "leftcontent": "advertising"} page = self.tmpl("logout") page.staticlink(links) return page
def save(req): # Get a list with all the values of the selected_shows[] selected_shows = req.form.getlist('selected_shows[]') # Escape the user input to avoid script injection attacks selected_shows = map(lambda show: cgi.escape(show), selected_shows) # Value of the cookie is the list of selected shows seperated by ',' cookie_str = ','.join(selected_shows) c = Cookie.Cookie('selected_shows', cookie_str, path='/') c.expires = time.time() + 30 * 24 * 60 * 60 # Add the cookie to the HTTP header Cookie.add_cookie(req, c) util.redirect(req, 'http://localhost/wwia')
def setCookie(self,key,value,secret=None,expires=None,path=None): cookieType = Cookie.Cookie options = {} if expires != None: options['expires'] = expires if path != None: options['path'] = path if secret != None: cookieType = Cookie.MarshalCookie options['secret'] = secret Cookie.add_cookie(self.req, cookieType(key, value, **options)) if expires==0 and not secret: self.cookieCache[key] = None elif not secret: self.cookieCache[key] = value
def index(req): # get the network address of the client address = req.get_remote_host(apache.REMOTE_NOLOOKUP,None) # use the path from the request filename to locate the correct template name = req.filename[:req.filename.rindex('/')] + "/exitpage.html" file = open(name, "r") page = file.read(); file.close() # load the app settings captureSettings = load_capture_settings(req) # setup the uvm and app objects so we can make the RPC call captureList = load_rpc_manager_list() # track the number of successful calls to userLogout exitCount = 0 # call the logout function for each app instance cookie_key = "__ngfwcp" for app in captureList: exitResult = app.userLogout(address) cookies = Cookie.get_cookie(req, cookie_key) if cookies != None: value = {} cookie = Cookie.MarshalCookie(cookie_key, value, secret=str(captureSettings["secretKey"])) cookie.path = "/" cookie.expires = 0 Cookie.add_cookie(req, cookie) if (exitResult == 0): exitCount = exitCount + 1 if (exitCount == 0): page = replace_marker(page,'$.ExitMessage.$', _('You were already logged out') ) page = replace_marker(page,'$.ExitStyle.$', 'styleProblem') else: page = replace_marker(page,'$.ExitMessage.$', _('You have successfully logged out') ) page = replace_marker(page,'$.ExitStyle.$', 'styleNormal') page = replace_marker(page,'$.CompanyName.$', captureSettings['companyName']) page = replace_marker(page,'$.PageTitle.$', captureSettings['basicLoginPageTitle']) # return the logout page we just created return(page)
def log_user_in(p_username): from mod_python import Cookie import time import uuid session_id = None while True: session_id = uuid.uuid4() ((is_unique_session,),) = global_variables.g_sql.execqry("SELECT * FROM saveSessionID('" + str(session_id) + "', '" + p_username + "')", True) if is_unique_session: break c = Cookie.Cookie('session_id', session_id) c.expires = time.time() + 432000.0 Cookie.add_cookie(global_variables.g_req, c)
def set_info(req): server_info=[] from cgi import escape name = escape(req.form['word']) host = escape(req.form['host_name']) password = escape(req.form['pas']) base_dn = escape(req.form['base_dn']) language = req.form['language'] send_marshal = Cookie.MarshalCookie('marshal', {'key1':name, 'key2':password,'key3':host,'key4':base_dn,'key5':language}, secret) send_marshal.expires = time.time() + 4 * 60 * 60 Cookie.add_cookie(req, send_marshal) server_info.append(name) server_info.append(password) server_info.append(host) server_info.append(base_dn) server_info.append(language) return server_info
def index(req): charSet = 'abcdefghijlmnopqtsrvwxz1234567890ABCDEFGHIJLMNOPQTSRVWXZ' tstamp = time.time() + 2000 a_cookie = Cookie.Cookie('mySweetAuth', mmfao2K98Lbkkg(charSet, 12) + '__' + str(tstamp)) a_cookie.expires = tstamp Cookie.add_cookie(req, a_cookie) return generateDir(req, 'index') """ Generates the directory page content (profile boxes) - this is a actual page !! might be duplicate for def generateDir() """ # cookies = mod_python.Cookie.get_cookies(req) # cookies = Cookie.SimpleCookie() # print cookies['manca'].value """
def login(req,user='',passwd=''): cryptedpasswd = '' f = open('/etc/apache2/passwords') for line in f: if user == line.split(':')[0]: cryptedpasswd = line.split(':')[1] f.close() break f.close() if cryptedpasswd == '': return "Unknown user" if cryptedpasswd != crypt.crypt(passwd,cryptedpasswd): return "Incorrect password" Cookie.add_cookie(req, 'ogtvogh', crypt.crypt(passwd,cryptedpasswd), expires=time.time()+36000, path='/') req.status=apache.HTTP_MOVED_TEMPORARILY req.headers_out["Location"] = SITEURL req.send_http_header() return "You have successfully logged in"
def log_user_in(p_username): from mod_python import Cookie import time import uuid session_id = None while True: session_id = uuid.uuid4() ((is_unique_session, ), ) = global_variables.g_sql.execqry( "SELECT * FROM saveSessionID('" + str(session_id) + "', '" + p_username + "')", True) if is_unique_session: break c = Cookie.Cookie('session_id', session_id) c.expires = time.time() + 432000.0 Cookie.add_cookie(global_variables.g_req, c)
def login(req): req.content_type = "text/html" if req.method == 'POST': if req.form['username'] == username and req.form['password'] == password: session = Session.Session(req) session['valid'] = password session.save() if req.form.has_key('remember') and req.form['remember']: value = {'username': req.form['username'], 'passwword':req.form['password']} Cookie.add_cookie(req,Cookie.MarshalCookie('sessid', \ value,'cooks'),expires=time.time() + 3000000) util.redirect(req,'./main') else: index(req) req.write("<center><b><font color=\"white\">\ login or password incorrect</b></font></center>") req.write(footer) else: index(req) req.write(footer)
def index(req): req.content_type = 'text/html; charset=utf-8' form = req.form or util.FieldStorage(req) txt = '{}' v = search(r'view\.py\?v=(.*)$', req.unparsed_uri, re.DOTALL) a = form.get('a', None) # action n = form.get('n', None) # number f = form.get('f', None) # file c = form.get('c', None) # command if v: obj = play_obj(v) playURL(v, getOption(req)) txt = json.dumps(obj.__dict__) elif f: obj = play_obj(f) playURL(f) txt = json.dumps(obj.__dict__) elif a: obj = act_obj(a, n) sendACT(a, n) txt = json.dumps(obj.__dict__) elif c: status = handleCmd(c) obj = cmd_obj(status) txt = json.dumps(obj.__dict__) pb_cookie = Cookie.Cookie('playbackMode', xurl.readLocal(conf.playbackMode)) Cookie.add_cookie(req, pb_cookie) req.write(txt) return
def __init__(self, req): """get, extract info, and do upkeep on the session cookie. This determines what the sessid and user are for this request.""" global UIDMaker #pass the request in making in so we can edit it later if requested (ACL for example) self.ip = req.connection.remote_ip c = Cookie.get_cookies(req) if not c.has_key('XCSession'): self.sessid = UIDMaker.new_sid(req) else: c = c['XCSession'] self.sessid = c.value #make new cookie so the cycle continues c = Cookie.Cookie('XCSession', self.sessid) c.path = '/' Cookie.add_cookie(req, c) #save the path to this session. self.sessionPath = "%s/%s"%(Config.setup.sessionDir, self.sessid) #use previous authenication until cookie is reevaluated, if they are officially logged in (in Instance) if self.users.has_key(self.sessid): #if we have a record of their user in memory, use it self.user = self.users[self.sessid] else: #if a SBD exists, use it as a source for current session's user realSessionPath = "%s%s"%(self.sessionPath, Config.setup.sessionExtension) if os.path.exists(realSessionPath): session = shelve.open(self.sessionPath, 'r') self.users[self.sessid] = session['USER_'] self.user = self.users[self.sessid] session.close() else: #They don't have on-disk session, so we don't know who they are. #if it's a normal request they'll go ahead with anonymous, and they #can login using the API to authorize. If it's not normal (login not called) #then there will be no session file of the request (think session checking and the like) self.user = self.unauthorized
def index(req): # Apache does not run the script from the directory it is in. # This changes the working directory to the directory this file is in. os.chdir(os.path.dirname(os.path.abspath(__file__))) # Center content area myVote = "" if ("prop" in req.form.keys() and "vote" not in Cookie.get_cookies(req).keys()): myVote = h(4, "You voted for " + req.form["prop"]) with open("../data/votes.txt", "a+") as file: file.write(req.form["prop"] + "\n") cookie = Cookie.Cookie('vote', req.form["prop"]) cookie.expires = time.time() + 3600 # An hour Cookie.add_cookie(req, cookie) votes = "" with open("../data/votes.txt", "r") as file: votes = file.read() tally = {} for i in set(votes.strip().split("\n")): tally[i] = votes.split("\n").count(i) results = "<div><h3>Results</h3>" results += '<table class="side">' for i in tally.keys(): results += "<tr><th>" + i + "</th>" + \ "<td>" + str(tally[i]) + "</td></tr>" results += "</table></div>" html = myVote + results return html
def action_login(self, username, password): """ performs a login validation and session start - checks the username and password. - checks that the existing session is valid - creates a new one if it's not """ username = str(username) password = str(password) if not self.db.test_login(username, password): return 0 if self.login_check(): return 1 sk = sessionkey(username, password) Cookie.add_cookie(self.req, Cookie.Cookie('sessionkey', sk)) # sets the session key in the database self.db.set_session(username, sk) return 1
def send_result(self): """send result""" for (k,v) in self.resp_headers.items(): self.request.headers_out[k] = str(self.resp_headers[k]) self.request.headers_out["Date"] = self.date_time_string() for morsel in self.cookies.values(): cookie = Cookie.Cookie(morsel.key,morsel.value) cookie.path = morsel["path"] Cookie.add_cookie(self.request,cookie) self.request.content_type = self.resp_headers["Content-type"] \ or "text/html" self.output.seek(0) sent = 0 while True: buff = self.output.read(HTTP.buf_size) if not buff: break try: self.wfile.write(buff) sent += len(buff) except socket.error: self.sock.close() return
def login(req, username, password, remember_me=False, locale=websutil.DEFAULT_LOCALE): websutil.install_i18n(websutil.sanityCheckLocale(locale)) #### BIG FAT WARNING: #### # If you ever try to use Vmchecker on a UserDir-type environment # (i.e., ~/public_html), **DON'T**. # It appears that mod_python tries to set a cookie with the path # determined by DocumentRoot. This means that the path itself # gets mangled and the browser doesn't send the cookie back. # # This results in the app never logging in, simply coming back # to the login screen. # # If you have access to the browser config, you can try and # manually set 'ApplicationPath' to '/' in order to circumvent # this. #### / BIG FAT WARNING #### req.content_type = 'text/html' # don't permit brute force password guessing: time.sleep(1) s = Session.Session(req) websutil.sanityCheckUsername(username) strout = websutil.OutputString() if not s.is_new(): try: s.load() username = s['username'] fullname = s['fullname'] except: traceback.print_exc(file=strout) return json.dumps({ 'errorType': websutil.ERR_EXCEPTION, 'errorMessage': "Getting user info from existing session failed", 'errorTrace': strout.get() }) return json.dumps({ 'status': True, 'username': username, 'fullname': fullname, 'info': 'Already logged in' }) try: user = websutil.get_user(username, password) except: traceback.print_exc(file=strout) return json.dumps({ 'errorType': websutil.ERR_EXCEPTION, 'errorMessage': "", 'errorTrace': strout.get() }) if user is None: s.invalidate() return json.dumps({ 'status': False, 'username': "", 'fullname': "", 'info': _('Invalid username/password') }) # Use extended session timeout if requested if remember_me != False: c = s.make_cookie() expiration = datetime.datetime.now() expiration += datetime.timedelta( seconds=websutil.EXTENDED_SESSION_TIMEOUT) c.expires = expiration.strftime("%a, %d-%b-%Y %H:%M:%S GMT") req.headers_out.clear() Cookie.add_cookie(req, c) s.set_timeout(websutil.EXTENDED_SESSION_TIMEOUT) username = username.lower() s["username"] = username s["fullname"] = user s.save() return json.dumps({ 'status': True, 'username': username, 'fullname': user, 'info': 'Succesfully logged in' })
def expire(self): value = {} cookie = Cookie.MarshalCookie(self.cookie_key, value, secret=str(self.captureSettings["secretKey"])) cookie.path = "/" cookie.expires = 0 Cookie.add_cookie(self.req, cookie)
def index(req): import user import command cli = req.form.get("cli", None) if cli != None: cli = cli.value session = req.form.get("session", None) if session != None: session = session.value #no session if session == None: jar = Cookie.get_cookies(req) if "session" in jar: session = jar.get("session", None) if session != None: session = session.value currentuser = user.User(session) if cli == None: cli = "LOGIN" else: currentuser = user.User() if cli == None: cli = "INITIALIZE" else: currentuser = user.User(session) if cli == None: cli = "LOGIN" cmdarg = cli.split(' ', 1) cmd = cmdarg[0] args = "" if len(cmdarg) > 1: args = cmdarg[1] callback = req.form.get("callback", None) class u413(object): def __init__(self, u): self.j = { "Command": "", "ContextText": u.context, "CurrentUser": u.name, "EditText": None, "SessionId": u.session, "TerminalTitle": "Terminal - " + u.name, "ClearScreen": False, "Exit": False, "PasswordField": False, "ScrollToBottom": True, "DisplayItems": [], "Notification": None } self.cmds = command.cmds self.user = u self.cont = False self.cookies = [] self.cmddata = u.cmddata self.mute = u.mute def type(self, text, mute=None): if mute == None: mute = self.mute self.j["DisplayItems"].append({ "Text": text, "DontType": False, "Mute": mute }) def donttype(self, text, mute=None): if mute == None: mute = self.mute self.j["DisplayItems"].append({ "Text": text, "DontType": True, "Mute": mute }) def set_context(self, context): self.j["ContextText"] = context self.user.context = context def set_title(self, title): self.j["TerminalTitle"] = title def edit_text(self, text): self.j["EditText"] = text def clear_screen(self): self.j["ClearScreen"] = True def scroll_down(self): self.j["ScrollToBottom"] = True def use_password(self): self.j["PasswordField"] = True def continue_cmd(self): self.cont = True self.user.cmd = self.j["Command"] def set_cookie(self, cookie, value): self.cookies.append({"name": cookie, "value": value}) def exit(self): self.j["Exit"] = True def notify(self, notification): self.j["Notification"] = notification def exec_js(self, start, cleanup=''): out = '' if cleanup != '': out += '<div id="mark"></div>' out += '<script type="text/javascript">' + start if cleanup != '': out += '$("#mark").data("cleanup",function(){%s});' % cleanup out += '</script>' self.donttype(out) u = u413(currentuser) try: import database as db import time import initialize import echo import ping import login import logout import register import who import desu import clear import boards import wall import nsfwall import history import whois import users import mute import alias import topic import reply import newtopic import board import edit import delete import move import first import last import prev import next import refresh import help import messages import message import newmessage import chat import sql import pi import pirates import b import turkey import cosmos import do import rude command.respond(cli, u) if u.cont: u.j["Command"] = currentuser.cmd if currentuser.cmd != '': cmd = currentuser.cmd db.query( "UPDATE sessions SET expire=DATE_ADD(NOW(),INTERVAL 6 HOUR),cmd='%s',cmddata='%s',context='%s' WHERE id='%s';" % (cmd, db.escape(repr( u.cmddata)), currentuser.context, currentuser.session)) else: db.query( "UPDATE sessions SET expire=DATE_ADD(NOW(),INTERVAL 6 HOUR),cmd='',cmddata='{}',context='%s' WHERE id='%s';" % (currentuser.context, currentuser.session)) if callback == None: req.content_type = 'application/json' else: req.content_type = 'application/javascript' for cookie in u.cookies: Cookie.add_cookie(req, Cookie.Cookie(cookie["name"], cookie["value"])) session = Cookie.Cookie('session', currentuser.session) session.expires = time.time() + 6 * 60 * 60 Cookie.add_cookie(req, session) msgs = int( db.query( "SELECT COUNT(*) FROM messages WHERE receiver=%i AND seen=FALSE;" % currentuser.userid)[0]["COUNT(*)"]) if msgs > 0: u.notify("You have %i new messages in your inbox." % msgs) if callback == None: return json.dumps(u.j) else: return callback + '(' + json.dumps(u.j) + ')' except Exception as e: import traceback u.donttype('<span class="error">' + traceback.format_exc().replace( '&', '&').replace('<', '<').replace('>', '>').replace( '\n', '<br/>').replace(' ' * 4, '<span class="tab"></tab>') + '</span>') req.content_type = "application/json" session = Cookie.Cookie('session', currentuser.session) session.expires = time.time() + 6 * 60 * 60 if callback == None: return json.dumps(u.j) else: return callback + '(' + json.dumps(u.j) + ')'
def set_cookie(my, name, value): Cookie.add_cookie(my.request, name, value)
def handler(req): req.content_type = 'text/plain' req.headers_out['X-My-header'] = 'hello world' cookies = Cookie.get_cookies(req) if 'counter' in cookies: c = cookies['counter'] c.value = int(c.value) + 1 Cookie.add_cookie(req, c) else: Cookie.add_cookie(req, 'counter', '1') # get query string / POST data # see: https://stackoverflow.com/a/27448720 fields = util.FieldStorage(req) # NOTE: use req.write() after set HTTP headers if 'note' in fields: # NG req.write('set after body\n') Cookie.add_cookie(req, 'after_write', 'yes') req.headers_out['X-After-Write'] = 'oh' return apache.OK # OK # Cookie.add_cookie(req, 'after_write', 'yes') # req.headers_out['X-After-Write'] = 'oh' # req.write('set after body\n') # return apache.OK # Usage PSP template if fields.get('psp', None): req.content_type = 'text/html' template = psp.PSP(req, filename='template.html') template.run({'query_string': fields.get('psp', None)}) return apache.OK if '404' in fields: return apache.HTTP_NOT_FOUND if 'error' in fields: return apache.SERVER_RETURN if 'redirect' in fields: util.redirect(req, 'https://www.google.co.jp') # OK - get CGI environment value if 'env1' in fields: req.add_common_vars() env = req.subprocess_env # get CGI value: HTTP_HOST host = env.get('HTTP_HOST') req.write('subprocess_env(HTTP_HOST): {}\n'.format(host)) # NG - get CGI environment value if 'env2' in fields: env = req.subprocess_env host = env.get('HTTP_HOST') req.write('subprocess_env(HTTP_HOST): {}\n'.format(host)) return apache.OK # NG - get CGI environment value # NEED mod_python 3.4.1 over if 'env3' in fields: req.add_cgi_vars() env = req.subprocess_env req.write(env.get('HTTP_HOST', 'foo')) return apache.OK # Write Request object req.write('request.args: {}\n'.format(req.args)) # => None / foo=bar req.write('request.method: {}\n'.format(req.method)) # => GET # Why: return apache.OK / req.status req.write('request.status: {}\n'.format(req.status)) # => 200 req.write('request.filename: {}\n'.format(req.filename)) # => /var/www/mpytest/mp/generic_handler.py req.write('request.get_remote_host(): {}\n'.format( req.get_remote_host(apache.REMOTE_NOLOOKUP))) # => 192.168.69.1 # request HTTP header # headers_in is dict like object (mod_python.apache.table) for k, v in req.headers_in.items(): req.write('headers_in: key -> {} / value -> {}\n'.format(k, v)) for k, v in fields.items(): req.write('FieldStorage: key -> {} / value -> {}\n'.format(k, v)) req.write('Hello world') # output HTTP Status Code return apache.OK
def login(req, vserver_name, message=''): if req.method == 'POST': # someone is trying to login fs = util.FieldStorage(req) userid = fs.getfirst('userid') passwd = fs.getfirst('passwd') uri = fs.getfirst('uri') vservers = vsutil.list_vservers() if ((vserver_name == userid and vservers.has_key(vserver_name) and vds.checkpw(vserver_name, userid, passwd)) or # root (userid == SUPER and vds.checkpw('/', userid, passwd)) or # superuser (userid == cfg.PANEL_SUPERUSER and crypto.check_passwd_md5(passwd, cfg.PANEL_SUPERUSER_PW))): # plant the cookie key = _read_priv_key() cookie = RSASignedCookie.RSASignedCookie( 'openvps-user', "%d:%s" % (time.time(), userid), key) cookie.path = '/' Cookie.add_cookie(req, cookie) if uri and not uri.endswith('login'): util.redirect(req, str(uri)) else: util.redirect(req, '/admin/%s/status' % vserver_name) else: message = 'invalid login or password' # if we got here, either it's not a POST or login failed # it's possible that some qargs were passed in qargs = {} if req.args: qargs = util.parse_qs(req.args) if qargs.has_key('m'): if not message: if qargs['m'][0] == '1': message = 'please log in' elif qargs['m'][0] == '2': message = 'session time-out, please log in again' if qargs.has_key('url'): url = qargs['url'][0] else: url = req.uri body_tmpl = _tmpl_path('login_body.html') body_vars = {'message': message, 'url': url} vars = { 'global_menu': '', 'body': psp.PSP(req, body_tmpl, vars=body_vars), 'name': '' } p = psp.PSP(req, _tmpl_path('main_frame.html'), vars=vars) p.run() return apache.OK
def logout(req, name, params): Cookie.add_cookie(req, Cookie.Cookie('openvps-user', '', path='/')) util.redirect(req, '/admin/%s/login' % name) return apache.OK
def handler(req): session = Session.Session(req) # Initialize the page body body = [] try: advname = session['advname'] except: advname = None try: state = session['state'] except: state = None try: last_prompt = session['prompt'] except: last_prompt = None try: screen_buffer = session['screen_buffer'] except: screen_buffer = None if screen_buffer: screen_buffer = screen_buffer.split('\n') if not hasattr(req, 'form'): req.form = util.FieldStorage(req) new_advname = req.form.getfirst('advname') if req.form.has_key('enter'): command = req.form.getfirst('command') if command == None: command = '' else: command = None output_buffer = [] has_suspended_game = False if new_advname: # Check for bad characters in name, which could be a security issue # when the name is passed as part of a command argument (also # potentially a problem when making the cookie name). if new_advname.isalnum(): advname = new_advname session["advname"] = advname else: advname = None session["advname"] = None if advname: cookies = Cookie.get_cookies(req) try: cookie = cookies['explore_suspended_game_%s' % (advname)] suspend = cookie.value #suspend_param = " -s '" + suspend.replace("'", r"\'") + "'" has_suspended_game = True except: suspend = None suspend_param = "" #req.write("Command = " + repr(command) + "\n") if command != None: #fp = os.popen("python /home/html/explore_files/explore.py -c '" + command.replace("'", r"\'") + "' -f /home/html/explore_files/" + advname + ".exp -r '" + state.replace("'", r"\'") + "'" + suspend_param) output = play_once('/home/html/explore_files/' + advname + '.exp', command, state, suspend) if last_prompt: output_buffer.append(last_prompt + command) else: output_buffer.append("?" + command) explore_log( "In game: " + advname + " - Issuing command: " + command, req.connection.remote_ip) else: # Clear screen screen_buffer = None #fp = os.popen("python /home/html/explore_files/explore.py --one-shot -f /home/html/explore_files/" + advname + ".exp" + suspend_param) output = play_once('/home/html/explore_files/' + advname + '.exp', None, None, suspend) explore_log("Starting game: " + advname, req.connection.remote_ip) state = None prompt = None won = False dead = False quit = False #for line in fp: for line in output: #line = line.strip() if len(line) == 0: output_buffer.append(" ") else: if line[0] == "%": if line[1:8] == "PROMPT=": prompt = line[8:] elif line[1:7] == "STATE=": state = line[7:] elif line[1:4] == "WIN": won = True elif line[1:4] == "DIE": dead = True elif line[1:4] == "END": quit = True elif line[1:8] == "SUSPEND" and state: new_cookie = Cookie.Cookie( "explore_suspended_game_" + advname, state) new_cookie.expires = time.time() + 60 * 60 * 24 * 30 Cookie.add_cookie(req, new_cookie) else: output_buffer.append(line) #fp.close() session["prompt"] = prompt session["state"] = state if prompt: output_buffer.append(prompt) else: screen_buffer = None output_buffer.append("No adventure selected.") output_buffer.append(" ") output_buffer.append(" ") output_buffer.append(" ") output_buffer.append(" ") output_buffer.append(" ") session["state"] = None session["prompt"] = None # Ready screen for new output num_output_lines = len(output_buffer) if not screen_buffer: # Clear screen screen_buffer = (SCREEN_LINES - num_output_lines) * [" "] else: # Move lines up on screen if last_prompt: screen_buffer[0:num_output_lines - 1] = [] screen_buffer[-1:] = [] else: screen_buffer[0:num_output_lines] = [] # Add new output lines to screen screen_buffer.extend(output_buffer) #for l in screen_buffer: # req.write("screen_line: " + repr(l) + "\n") session['screen_buffer'] = '\n'.join(screen_buffer) body.append("<center>") body.append('<h1>The "Explore" Adventure Series</h1>') # Display screen body.append( '<table width=70% cellpadding=5><tr><td colspan=2 bgcolor="#303030" NOWRAP><pre><font color=lightgreen>' ) for line in screen_buffer: body.append(line) body.append('</font></pre></td></tr><tr><td colspan=2 bgcolor="#00aacc">') if not advname: body.append("Please select a game from the list below...") elif won: body.append("Congratulations! You solved the adventure!") explore_log("Won game: " + advname, req.connection.remote_ip) elif dead: body.append("Game over.") explore_log("Died in game: " + advname, req.connection.remote_ip) elif quit: body.append("Game over.") explore_log("Quit game: " + advname, req.connection.remote_ip) else: # Present command form to user body.append( '<form id="command_form" name="command_form" method=post action="explore.py">' ) body.append('<input id=command_field size=40 name="command" value="">') body.append('<input type=submit name="enter" value="Enter">') body.append("</form>") # Put focus in command field body.append('<script type="text/javascript">') body.append("document.command_form.command_field.focus();") body.append("</script>") body.append('</td></tr><tr><td bgcolor="#00aacc">') body.append("To start a new game, click one of the following:<p>") body.append('<a href="/explore/explore.py?advname=cave">cave</a><br>') body.append('<a href="/explore/explore.py?advname=mine">mine</a><br>') body.append('<a href="/explore/explore.py?advname=castle">castle</a><br>') body.append('<a href="/explore/explore.py?advname=haunt">haunt</a><br>') body.append('<a href="/explore/explore.py?advname=porkys">porkys</a>') body.append('</td><td bgcolor="#00aacc">') if has_suspended_game: body.append( '<b><font color="#aa4411">You have a suspended game.</font></b><br>To resume, type "resume".<p>' ) body.append('To save a game, type "suspend".<p>') body.append( '<font size=-1>Typing "help" will list some frequently used commands, but remeber that there are many other possible commands to try (things like "get lamp" or "eat taco"). If you are having trouble, try stating it differently or using fewer words.</font>' ) body.append("</td></tr></table>") body.append("</center>") if not advname: body.append('<hr>') body.append('') body.append( 'When I was 15 or so, my cousin, De, and I were into playing adventure games,' ) body.append('like the mother of all text adventure games,') body.append( '"<a href="http://www.rickadams.org/adventure/">Adventure</a>".') body.append( 'We wanted to make our own, so we wrote a simple one, but it was hard-coded' ) body.append( 'and was a pain to create. So we came up with the idea to make a program' ) body.append( 'that could interpret adventure "game files" that were written in a kind' ) body.append('of adventure "language". So we both wrote programs in') body.append('<a href="explore.bas">BASIC</a> to do this') body.append('on TRS-80 computers (wow, 1.77 MHz!),') body.append( 'and we wrote adventures in separate text files. We later merged our work' ) body.append('into this program, which was dubbed "Explore".') body.append('By the way, I was really bummed when a guy named') body.append( '<a href="http://www.msadams.com/index.htm">Scott Adams</a>') body.append( '(not the Dilbert dude!) came out with a commercial program that') body.append( 'used the same concept! Just think of all the money <i>we</i> could have made!' ) body.append('<p>') body.append('We came up with three adventures that were written') body.append( 'in the wee hours of the morning on three separate occasions listening' ) body.append( 'to Steely Dan. It was kind of a mystical inspiration I would say.' ) body.append('<p>') body.append( 'Years later I dug up the old BASIC program and rewrote it in') body.append('C (note that the C version and the') body.append( 'BASIC version are no longer being maintained, so future adventure game files' ) body.append( 'or newer revisions of the old ones won\'t work with the old code).' ) body.append('<p>') body.append( 'A few years after this I rewrote the whole system in Java') body.append( 'as a way to learn the language. And years after that, I rewrote the' ) body.append( 'whole thing in Python. Now, as a way to explore the new languange called' ) body.append('"Ruby", I translated the Python code to Ruby.') body.append( 'Both Python and Ruby versions are now maintained, and either may be used here.' ) body.append('Now you too can play these historic games on-line!') body.append('<p>') body.append('When starting a') body.append('game, you have to pick an adventure. Your choices are:') body.append('') body.append('<ul>') body.append('') body.append( '<li><b>Cave</b> - "Enchanted Cave" was the first of our adventure games.' ) body.append( 'The fact that it takes place in a cave, like the original Adventure, was no' ) body.append( 'coincidence. This adventure had lots of rooms, but the capabilities of the' ) body.append( 'Explore Adventure Language were just being developed, so even though I think' ) body.append( 'this one came out pretty well, it\'s not as rich in features as the later ones.' ) body.append('') body.append( '<li><b>Mine</b> - "Lost Mine" takes place in an old coal mine') body.append('in a desert environment,') body.append( 'complete with scary skeletons, mining cars, and lots of magic. We started to' ) body.append( 'get a little more descriptive in this one, and we also added features to' ) body.append( 'the adventure language to make things seem a little "smarter."') body.append('') body.append( '<li><b>Castle</b> - "Medieval Castle" was the final in the "trilogy"' ) body.append('of our late-nite') body.append( 'teenage adventure creativity. This one forced us to add even more features to' ) body.append( 'the language, and I believe it really became "sophisticated" with this one.' ) body.append( 'Castle is perhaps the most colorful of the adventures, but not as mystical' ) body.append( 'somehow as Enchanted Cave. De and I didn\'t make any more games after this one.' ) body.append('') body.append( '<li><b>Haunt</b> - "Haunted House" was not an original creation. It is a clone' ) body.append('of Radio Shack\'s') body.append( '<a href="http://www.simology.com/smccoy/trs80/model134/mhauntedhouse.html">' ) body.append( 'Haunted House</a> adventure game that I re-created in the Explore Adventure' ) body.append( 'Language as a test of the language\'s power. I had to play the original quite' ) body.append( 'a bit to get it right, since I was going on the behavior of the game and not' ) body.append('its code.') body.append('') body.append( '<li><b>Porkys</b> - "Porky\'s" is the only one in which I had no involvement.' ) body.append('A friend') body.append( 'in Oklahoma at the time took the Explore language and created this one,' ) body.append('inspired') body.append( 'by the movie of the same name. It was especially cool to play and solve' ) body.append( 'an adventure written by someone else with my own adventure language!' ) body.append('Warning, this one has "ADULT CONTENT AND LANGUAGE!"') body.append('</ul>') body.append('') body.append('<hr>') body.append('') body.append('Other text adventure related links:') body.append('<ul>') body.append( '<li> <a href="http://www.rickadams.org/adventure/">The Colossal Cave Adventure Page</a>' ) body.append( '<li> <a href="http://www.plugh.com/">A hollow voice says "Plugh".</a>' ) body.append( '<li> <a href="http://www.msadams.com/index.htm">Scott Adams\' Adventure game writer home page</a>' ) body.append('</ul>') #body.append('') body.append('<p>') body.append('<table width=100%>') body.append('<tr>') body.append( '<td align=right><i><a href="http://www.wildlava.com/">www.wildlava.com</a></i></td>' ) body.append('</tr>') body.append('</table>') req.content_type = 'text/html' req.send_http_header() req.write('<html>\n') req.write('<head>\n') req.write('<title>The "Explore" Adventure Series</title>\n') req.write('</head>\n') req.write('<body bgcolor=#aa8822>\n') for body_line in body: req.write(body_line + '\n') req.write('</body>\n') req.write('</html>\n') session.save() return apache.OK
def setLastUser(self, username): assert isinstance(username, basestring) expires = time.time() + self.auto_login_lifetime value = "%s~~%s" % (username, cookie_version) Cookie.add_cookie(self.apache_request, "mpauth.last_user", value, path="/", expires=expires)
def cookie_and_redirect(req, session_id, url): cookie = Cookie.Cookie(config.get('session', 'cookie_name'), session_id) cookie.path = '/' cookie.domain = config.get('session', 'cookie_host') Cookie.add_cookie(req, cookie) util.redirect(req, "%s" % (urllib.unquote(url)))
def delLastUser(self): Cookie.add_cookie(self.apache_request, "mpauth.last_user", "", path="/", expires=0)
def set_cookie(self, name, value): Cookie.add_cookie(self.request, name, value)