def accesshandler(request): cookies = Cookie.get_cookies(request) # if login ticket cookie does not exist, then deny if not cookies.has_key('login_ticket'): # just refuse access return apache.HTTP_FORBIDDEN ticket = cookies['login_ticket'].value if not ticket: return apache.HTTP_FORBIDDEN server = TacticServerStub.get(protocol='local') expr = "@SOBJECT(sthpw/ticket['ticket','%s'])" % ticket sobject = server.eval(expr, single=True) now = SPTDate.now() expiry = sobject.get("expiry") if expiry and expiry < str(now): return apache.HTTP_FORBIDDEN request.add_common_vars() path = str(request.subprocess_env['REQUEST_URI']) if path == None: return apache.HTTP_FORBIDDEN # FIXME: find some mechanism which is more acceptable ... like /icons #if path.find("_icon_") != -1: # return apache.OK return apache.OK
def outputfilter_watermark(filter): s_in = None s_out = None try: s_in = StringIO(filter.read()) im_in = Image.open(s_in) if im_in.size[0] <= 240 and im_in.size[1] <= 120: filter.write(s_in.getvalue()) return # if this is a sub request, then don't process again req = filter.req if req.main: filter.write(s_in.getvalue()) return cookies = Cookie.get_cookies(req) ticket = cookies['login_ticket'].value query = req.parsed_uri[apache.URI_QUERY] if query == "watermark=false": filter.write(s_in.getvalue()) ticket_sobj = Ticket.get_by_valid_key(ticket) # if this is not a valid ticket, then just exit with no image if not ticket_sobj: return # TODO: need fancier algorithm here if ticket_sobj.get_value("login") == 'admin': filter.write(s_in.getvalue()) return sizex = im_in.size[0] sizey = im_in.size[1] max_res = 240 max_width = 640 im_in = im_in.resize((max_res, int(sizey / (sizex / float(max_res))))) im_in = im_in.resize( (max_width, int(sizey / (sizex / float(max_width))))) # add the watermark watermark = Watermark() now = datetime.today().strftime("%Y/%m/%d, %H:%M") texts = ['Do Not Copy', ticket, now] sizes = [20, 10, 10, 20, 20] mark = watermark.generate(texts, sizes) im_out = watermark.execute(im_in, mark, 'tile', 0.5) s_out = StringIO() im_out.save(s_out, format='jpeg') filter.write(s_out.getvalue()) finally: if s_in: s_in.close() if s_out: s_out.close()
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 init(self): # Parse the HTTP headers for variables and files. for field in self.__field_storage.list: # This is a normal variable. if str(type(field.file)) == "<type 'cStringIO.StringI'>" or \ str(type(field.file)) == "<type 'cStringIO.StringO'>": self.set_var(field.name, field.value) # This is a file. else: # Some browsers give a full path instead of a file name. Some # browsers give an encoded file name. Plan for those cases. # FIXME: is the explanation above and the code below correct? filename = field.filename filename = urllib.unquote_plus(filename) # unquote filename (it should be encoded like an url) filename = re.sub(r'\\+', '/', filename) # some OS use "\" for paths... replace '\' in '/' filename = os.path.basename(filename) # some browsers (IE) send full path.. rip path part and just get file name self.__files[field.name] = KWebFile(filename, field.file) # Store the HTTP headers. for key in self.__req.headers_in: self.__headers_in[key] = self.__req.headers_in[key] # Initialize the cookies. self.__cookies_in = Cookie.get_cookies(self.__req)
def init(self): # Parse the HTTP headers for variables and files. for field in self.__field_storage.list: # This is a normal variable. if str(type(field.file)) == "<type 'cStringIO.StringI'>" or \ str(type(field.file)) == "<type 'cStringIO.StringO'>": self.set_var(field.name, field.value) # This is a file. else: # Some browsers give a full path instead of a file name. Some # browsers give an encoded file name. Plan for those cases. # FIXME: is the explanation above and the code below correct? filename = field.filename filename = urllib.unquote_plus( filename ) # unquote filename (it should be encoded like an url) filename = re.sub( r'\\+', '/', filename ) # some OS use "\" for paths... replace '\' in '/' filename = os.path.basename( filename ) # some browsers (IE) send full path.. rip path part and just get file name self.__files[field.name] = KWebFile(filename, field.file) # Store the HTTP headers. for key in self.__req.headers_in: self.__headers_in[key] = self.__req.headers_in[key] # Initialize the cookies. self.__cookies_in = Cookie.get_cookies(self.__req)
def create_user(): import mod_python.Cookie as Cookie try: c = Cookie.get_cookies(global_variables.g_req, Cookie.MarshalCookie, secret='popcorn') if not 'session_id' in c: return None session_id = c["session_id"].value except (Cookie.CookieError, KeyError, Exception): return None import classes.class_user_factory as user_factory import exceptions.e_notregistered as e_notregistered import scripts.classes.class_dosql as sql dosql = sql.doSql() try: ((username, ), ) = dosql.execqry( "SELECT * FROM getUser('" + str(session_id) + "')", False) return user_factory.UserFactory().createUserFromID(username) except (e_notregistered.ENotRegistered, Exception): return None
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 __init__(self, req=None, mod_python_session=None, FieldStorage_formdata=None): for item in self.attrs: setattr(self, item, None) try: self.remote_ip = req.connection.remote_ip except: self.remote_ip = "1.2.3.4" if req and req.headers_in.has_key("referer"): self.refURL = req.headers_in["referer"] else: self.refURL = None self.cookies = cookieData.cookieData( Cookie.get_cookies(req) ) # XZ: dictionary type. To hold values transfered from mod_python Cookie. # XZ: dictionary type. To hold values transfered from mod_python Session object. We assume that it is always picklable. self.input_session_data = sessionData.sessionData(mod_python_session) # XZ: FieldStorage_formdata may contain item that can't be pickled. Must convert to picklable data. self.formdata = cgiData(FieldStorage_formdata) # get Form ID self.formID = self.formdata.getfirst("FormID") # get rest of the attributes if self.formID: for item in self.attrs: value = self.formdata.getfirst(item) if value != None: setattr(self, item, string.strip(value)) self.ppolar = "" self.mpolar = "" if self.RISet: try: # NL, 07/27/2010. ParInfo has been moved from webqtlForm.py to webqtlUtil.py; f1, f12, self.mpolar, self.ppolar = webqtlUtil.ParInfo[self.RISet] except: f1 = f12 = self.mpolar = self.ppolar = None try: self.nperm = int(self.nperm) self.nboot = int(self.nboot) except: self.nperm = 2000 # XZ: Rob asked to change the default value to 2000 self.nboot = 2000 # XZ: Rob asked to change the default value to 2000 if self.allstrainlist: self.allstrainlist = map(string.strip, string.split(self.allstrainlist)) # self.readGenotype() # self.readData() if self.RISet == "BXD300": self.RISet = "BXD" else: pass
def get_cookie(cls, req, name): """Retreive cookie by name from request object.""" #cookies = mod_python.Cookie.get_cookies(req) cookies = Cookie.get_cookies(req) this_cookie = cookies.get(name) value = cut(str(this_cookie), "{0}=".format(name)) return value
def __init__(self,req,appid=None): self.req = req if appid == None: args = split_args(self.req.args); appid = args['APPID'] self.captureSettings = load_capture_settings(self.req,appid) self.cookie = Cookie.get_cookies(self.req, Cookie.MarshalCookie, secret=str(self.captureSettings["secretKey"]))
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=None, form=None): self.req = req if self.req != None: # mod_python self.form = util.FieldStorage(self.req) self._cookies_in = Cookie.get_cookies(self.req) else: # if we have a form, don't get a new one if form: self.form=form # if we don't have a form, then get one else: self.form = cgi.FieldStorage() self._cookies_in = SimpleCookie() try: self._cookies_in.load(os.environ["HTTP_COOKIE"]) except KeyError: pass self._dispatch = {} self._header_sent = 0 self._header_props = {"Content-Type" : "text/html;charset=UTF-8"} self._header_props = {} self._header_type = "header" self._cookies = [] self._url = "" self._environ = os.environ self.template_dir = 'templates' self.run_mode_param = 'rm' self.start_mode = '' self.__globals__ = {} self.setup()
def check_authen(req, vserver_name): """ If authenticated, return userid """ try: cookies = Cookie.get_cookies(req, Class=RSASignedCookie.RSASignedCookie, secret=_get_pub_key()) except RSASignedCookie.RSASignError: cookies = None if not cookies or not cookies.has_key('openvps-user'): login(req, vserver_name, message='please log in') else: try: login_time, userid = cookies['openvps-user'].value.split(':', 1) if (time.time() - int(login_time)) > TIMEOUT: login(req, vserver_name, message='session time-out, please log in again') return None except: login(req, vserver_name, message='please log in') return None return userid
def isValidSession(req): """ check the Django's session table to decided this is a valid session or not. """ # check for PythonOptions _str_to_bool = lambda s: s.lower() in ('1', 'true', 'on', 'yes') options = req.get_options() permission_name = options.get('DjangoPermissionName', None) staff_only = _str_to_bool(options.get('DjangoRequireStaffStatus', "on")) superuser_only = _str_to_bool( options.get('DjangoRequireSuperuserStatus', "off")) settings_module = options.get('DJANGO_SETTINGS_MODULE', None) if settings_module: os.environ['DJANGO_SETTINGS_MODULE'] = settings_module from django.conf import settings cookieName = settings.SESSION_COOKIE_NAME cookies = Cookie.get_cookies(req) if not cookies.has_key(cookieName): return False #import pdb; pdb.set_trace() sessionId = cookies[cookieName].value # mod_python fakes the environ, and thus doesn't process SetEnv. This fixes # that so that the following import works os.environ.update(req.subprocess_env) from django.contrib.sessions.models import Session from django import db db.reset_queries() try: try: session = Session.objects.get(pk=sessionId) except Session.DoesNotExist: return False sessionData = session.get_decoded() if not sessionData.has_key('_auth_user_id'): # this is not a valid session! return False if session.expire_date > datetime.now(): if isResourcesRequest(req): # just pass return True # this is a valid session, update the expre date! expiry = settings.SESSION_COOKIE_AGE session.expire_date = datetime.now() + timedelta(seconds=expiry) session.save() return True else: return False finally: db.connection.close()
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 get_cookie(my, name): cookies = Cookie.get_cookies(my.request) cookie = cookies[name] if cookie == None: return "" else: my.error("cookie: " + cookie.value) return cookie.value
def get_cookie(self, coname): if self.reallympy: from mod_python import Cookie cookie = Cookie.get_cookies(self.mpyreq) if cookie.has_key(coname): return cookie[coname].value else: return ''
def get_cookie(my, name): cookies = Cookie.get_cookies(my.request) cookie = cookies[name] if cookie == None: return "" else: my.error("cookie: "+cookie.value) return cookie.value
def isValidSession(req): """ check the Django's session table to decided this is a valid session or not. """ # check for PythonOptions _str_to_bool = lambda s: s.lower() in ('1', 'true', 'on', 'yes') options = req.get_options() permission_name = options.get('DjangoPermissionName', None) staff_only = _str_to_bool(options.get('DjangoRequireStaffStatus', "on")) superuser_only = _str_to_bool(options.get('DjangoRequireSuperuserStatus', "off")) settings_module = options.get('DJANGO_SETTINGS_MODULE', None) if settings_module: os.environ['DJANGO_SETTINGS_MODULE'] = settings_module from django.conf import settings cookieName = settings.SESSION_COOKIE_NAME cookies = Cookie.get_cookies(req) if not cookies.has_key(cookieName): return False #import pdb; pdb.set_trace() sessionId = cookies[cookieName].value # mod_python fakes the environ, and thus doesn't process SetEnv. This fixes # that so that the following import works os.environ.update(req.subprocess_env) from django.contrib.sessions.models import Session from django import db db.reset_queries() try: try: session = Session.objects.get(pk=sessionId) except Session.DoesNotExist: return False sessionData = session.get_decoded() if not sessionData.has_key('_auth_user_id'): # this is not a valid session! return False if session.expire_date > datetime.now(): if isResourcesRequest(req): # just pass return True # this is a valid session, update the expre date! expiry = settings.SESSION_COOKIE_AGE session.expire_date = datetime.now() + timedelta(seconds=expiry) session.save() return True else: return False finally: db.connection.close()
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 get_session_info(self): """ checks to see if the user is logged in, via the session cookie. """ cookies = Cookie.get_cookies(self.req) if not cookies.has_key('sessionkey'): return None return cookies['sessionkey'].value
def authorize(req): cookies = Cookie.get_cookies(req) if cookies.has_key("ogtvogh"): user = str(cookies["ogtvogh"]).split('=')[1] f = open('/etc/apache2/passwords') for line in f: if user == line.split(':')[1]: f.close() return 'auth' return ''
def __init__(self, req, appid=None): self.req = req if appid == None: args = split_args(self.req.args) appid = args['APPID'] self.captureSettings = load_capture_settings(self.req, appid) self.cookie = Cookie.get_cookies( self.req, Cookie.MarshalCookie, secret=str(self.captureSettings["secretKey"]))
def _check_csrf(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 not Cookie.SignedCookie or cookie.value != _message_contents(): raise apache.SERVER_RETURN, apache.HTTP_NOT_ACCEPTABLE else: return False return True
def cookie(self, name, default=None): try: cookies = self.Cookies except AttributeError: self.Cookies = Cookie.get_cookies(self.request, Cookie.Cookie) cookies = self.Cookies try: return cookies[name].value except KeyError: return 'no cookie found by name %s' % name
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 get_useful_info(self): """ gets the "state" info for the browser """ cookies = Cookie.get_cookies(self.req) if not cookies.has_key('stateinfo'): return {} info = cookies['stateinfo'].value info = eval(info) return info
def localize(req): cookies = Cookie.get_cookies(req) if cookies.has_key("lezu"): lang = str(cookies["lezu"]).split('=')[1] if languages.count(lang)>0: return lang if not req.headers_in.has_key('Accept-Language'): return "en" for block in req.headers_in['Accept-Language'].split(','): for lang in block.split(';'): if languages.count(lang)>0: return lang return "en"
def log_user_out(): import mod_python.Cookie as Cookie try: c = Cookie.get_cookies(global_variables.g_req, Cookie.MarshalCookie, secret='popcorn') if not 'session_id' in c: return False session_id = c["session_id"].value global_variables.g_sql.execqry("SELECT * FROM deleteSession('" + session_id + "')", True) return True except (Cookie.CookieError, KeyError, Exception): return False
def getLastUser(self): cookies = Cookie.get_cookies(self.apache_request) cookie = cookies.get("mpauth.last_user") if cookie is None: return None words = cookie.value.rsplit("~~", 1) user = words[0] version = None if len(words) == 2: version = words[1] if version != cookie_version or not user: return None return user
def get_browser_info(self): """ gets the "state" info for the browser """ cookies = Cookie.get_cookies(self.req) if not cookies.has_key('browseinfo'): return {} info = cookies['browseinfo'].value #info = eval(base64.decodestring(info)) info = eval(info) return info
def Session_Session(req): from mod_python import Session, Cookie s = Session.Session(req) if s.is_new(): s.save() cookies = Cookie.get_cookies(req) if cookies.has_key(Session.COOKIE_NAME) and s.is_new(): req.write(str(cookies[Session.COOKIE_NAME])) else: req.write("test ok") return apache.OK
def _check_csrf(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 not Cookie.SignedCookie or cookie.value != _message_contents(): raise apache.SERVER_RETURN, apache.HTTP_NOT_ACCEPTABLE else: return False return True
def log_user_out(): import mod_python.Cookie as Cookie try: c = Cookie.get_cookies(global_variables.g_req, Cookie.MarshalCookie, secret='popcorn') if not 'session_id' in c: return False session_id = c["session_id"].value global_variables.g_sql.execqry( "SELECT * FROM deleteSession('" + session_id + "')", True) return True except (Cookie.CookieError, KeyError, Exception): return False
def handler(req): req.content_type = "text/json" all_cookies = Cookie.get_cookies(req) session_id = all_cookies.get(config.get('session', 'cookie_name'), None) if req.method != "POST": return 400 if session_id == None: return apache.HTTP_UNAUTHORIZED try: url = req.path_info.split('/', 2)[2] except: return 400 res = switchuser.switch_user(session_id.value, url, req) if res == 200: return apache.OK return res
def main(req): req.content_type = 'text/html' session = Session.Session(req) cookies = Cookie.get_cookies(req, Cookie.MarshalCookie,secret="cooks") if cookies.has_key('sessid'): cookie = cookies['sessid'] if type(cookie) is Cookie.MarshalCookie: data = cookie.value session['valid'] = password session.save() else: if session.is_new(): util.redirect(req,'./login') if session['valid'] != password: util.redirect(req,'./login') parse(req)
def handler(req): req.content_type = 'text/html' cookies = Cookie.get_cookies(req) brand('header', req) brand('middle', req) session_id = cookies['myemsl_session'].value #FIXME rename myemsl.eus_auth sql = "delete from myemsl.eus_auth where session_id=%(sid)s" try: cnx = myemsldb_connect(myemsl_schema_versions=['1.0']) cursor = cnx.cursor() cursor.execute(sql, {'sid': session_id}) cnx.commit() req.write("You have successfully logged out.") except Exception, e: logger.warning("Unknown exception %s", e) req.write("Unknown issue during logout")
def get(self, var): cookies = Cookie.get_cookies(self.req) if cookies is None: return None cookie = cookies.get(var, None) if cookie is None: return None val = cookie.value st = scs.decode(self.s, val) if st is None: raise Exception, 'failed scs.decode()' return st
def get_info(req): marshal_cookies = Cookie.get_cookies(req, Cookie.MarshalCookie, secret=secret) returned_marshal = marshal_cookies.get('marshal', None) if(returned_marshal): server_info=[] name = returned_marshal.value['key1'] password = returned_marshal.value['key2'] host = returned_marshal.value['key3'] base_dn = returned_marshal.value['key4'] language = returned_marshal.value['key5'] server_info.append(name) server_info.append(password) server_info.append(host) server_info.append(base_dn) server_info.append(language) return server_info else: return 0
def form(req): name = req.form['losername'] coo = Cookie.get_cookies(req) selectedFile = req.form['fisier'] """ great tutorial http://lost-and-found-narihiro.blogspot.ro/2013/07/apache-modpython-upload-files-over-post.html """ s = """\ <html> <body> <h1>Yo! %s %s and file: %s %s</h1> <p>in working dir: %s </p> <p>images folder listing: %s </p> </body> </html> """ path2img = os.path.join('var', 'www', 'soc', 'res', 'img') return s % (name, coo['manca'], req.method, os.path.join(path2img, selectedFile.filename), os.getcwd(), os.listdir(os.path.join(path2img)))
def _get_session_id(self, config): """() -> string Find the ID of the current session by looking for the session cookie in the request. Return None if no such cookie or the cookie has been expired, otherwise return the cookie's value. Since Mod_Python has its own Cookie management system, we use it. """ cookies = Cookie.get_cookies(self.modpython_request) try: sessID = cookies[config.session_cookie_name].value if sessID in ("","*del*"): sessID = None except KeyError: # let's try with pysid sessID = self._get_session_id_from_pysid(cookies) return sessID
def read_cookies(req): req.cookies = Cookie.get_cookies(req)
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 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 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 getCookie(req, key): cookies = Cookie.get_cookies(req) if cookies and cookies.has_key(key): return cookies[key].value return None
def read_cookies(self): self.cookies = Cookie.get_cookies(self.req)