def get(self): user = users.get_current_user() if user is None: return self.redirect('/index') else: logout_link = users.create_logout_url(PROTOCOLHTTP + DOMAIN + "/index") if user: loginFlg = 1 num = random.randint(1, 1000000) tooken = num cookie = SimpleCookie(os.environ.get('HTTP_COOKIE', '')) cookie['picturetooken'] = tooken cookie['picturetooken']['expires'] = 3600 print cookie.output() params = { 'logout_link': logout_link, 'loginFlg': loginFlg, 'tooken': tooken } fpath = os.path.join(os.path.dirname(__file__), 'template/user/picture', 'insert.html') html = template.render(fpath, params) self.response.out.write(html) return
def post(self): try: user = users.get_current_user() if user is None: return self.redirect('/index') else: logout_link = users.create_logout_url(PROTOCOLHTTP + DOMAIN + "/index") cookie = SimpleCookie(os.environ.get('HTTP_COOKIE', '')) picturHandlerePage = self.request.get('picturHandlerePage') cookie['picturHandlerePage'] = picturHandlerePage.encode('utf-8') cookie['picturHandlerePage']['expires'] = 3600 print cookie.output() pictureIdList = self.request.POST.getall("pictureid") for pil in pictureIdList: label = self.request.get("label" + pil) if len(label) > 10: raise RuntimeError("labelMax error") data = Picture.get_by_id(long(pil)) data.label = label data.put() return self.redirect('/user/picture/list') except: self.errorFunc()
def set_cookie(self, cookie): """ Set a cookie. The cookie will actually be recorded in the WSGI environ and the 'Set-Cookie' header will be generated with the responses are first sent. 'cookie' can be one of four things: * a string: the value is considered a cookie header value, i.e. the bit that would normally be added after 'Set-Cookie: '. * (name, value) tuple: a persistent cookie is created. * (name, None) tuple: the named cookie will be removed. * cookie instance: e.g. one of the cookie types in Python's Cookie module. """ if isinstance(cookie, str): pass elif isinstance(cookie, tuple): name, value = cookie cookie = SimpleCookie() cookie[name] = value or '' cookie[name]['path'] = self.environ['SCRIPT_NAME'] or '/' if value is None: cookie[name]['expires'] = 0 cookie[name]['max-age'] = 0 cookie = cookie.output(header='').strip() else: cookie = cookie.output(header='').strip() self.headers.append(cookie)
class Browser(object): def __init__(self, Visit=None): if Visit is not None: Visit.createTable(ifNotExists=True) self.visit = True else: self.visit = False self.cookie = SimpleCookie() def goto(self, url, **kargs): params = kargs.get('params') if params: s = '&'.join([ '='.join( [urllib.quote_plus(str(k)), urllib.quote_plus(str(v))]) for k, v in params.items() ]) url += '?' + s del kargs['params'] if self.cookie: headers = kargs.get('headers', {}) headers['Cookie'] = self.cookie.output() kargs['headers'] = headers createRequest(url, **kargs) if cherrypy.response.simple_cookie: self.cookie.update(cherrypy.response.simple_cookie) # Try to handle redirects i = 5 # To prevent infinitive redirects while cherrypy.response.status.startswith('302') and i > 0: response = cherrypy.response.body[0] url = response.split('>')[1].split('<')[0] if self.cookie: headers = kargs.get('headers', {}) headers['Cookie'] = self.cookie.output() kargs['headers'] = headers createRequest(url, **kargs) if cherrypy.response.simple_cookie: self.cookie.update(cherrypy.response.simple_cookie) i -= 1 self.url = url self.response = cherrypy.response try: self.body = cherrypy.response.body[0] except: self.body = None if not self.response.status.startswith('200'): raise ValueError(self.body) def response_contains(self, text): return text in self.body
def post(self): try: user = users.get_current_user() if user is None: return self.redirect('/index') else: logout_link = users.create_logout_url(PROTOCOLHTTP + DOMAIN + "/index") cookie = SimpleCookie(os.environ.get('HTTP_COOKIE', '')) picturHandlerePage = self.request.get('picturHandlerePage') cookie['picturHandlerePage'] = picturHandlerePage.encode('utf-8') cookie['picturHandlerePage']['expires'] = 3600 print cookie.output() email = user.email() userData = db.GqlQuery("SELECT * FROM User WHERE email='" + email + "'") for user in userData: id = user.key().id() user = User.get_by_id(long(id)) pictureIdList = self.request.POST.getall("pictureid") sumBinary = 0 for pil in pictureIdList: picture = Picture.get_by_id(long(pil)) sumBinary = sumBinary + len(picture.binary) / 1000 PcaDatas = PictureConnectAlbum.gql( "WHERE picture = :1 ORDER BY picture", picture) for PcaData in PcaDatas: albumid = PcaData.album.key().id() albumData = Album.get_by_id(long(albumid)) cnt = albumData.picture_counter - 1 albumData.picture_counter = cnt albumData.put() picture.delete() contentPicture = user.contentPicture contentPicture = contentPicture - sumBinary user.contentPicture = contentPicture user.put() return self.redirect('/user/picture/list') except: self.errorFunc()
def set_cookie(name, _, *args): cookie = SimpleCookie() cookie[name] = base64.b64encode(":".join(args)) cookie[name]['path'] = "/" cookie[name]["expires"] = _expiration(5) # 5 minutes from now logger.debug("Cookie expires: %s" % cookie[name]["expires"]) return tuple(cookie.output().split(": ", 1))
def make_cookie(name, load, seed, expire=0, domain="", path="", timestamp=""): """ Create and return a cookie :param name: Cookie name :param load: Cookie load :param seed: A seed for the HMAC function :param expire: Number of minutes before this cookie goes stale :param domain: The domain of the cookie :param path: The path specification for the cookie :return: A tuple to be added to headers """ cookie = SimpleCookie() if not timestamp: timestamp = str(int(time.mktime(time.gmtime()))) signature = cookie_signature(seed, load, timestamp) cookie[name] = "|".join([load, timestamp, signature]) if path: cookie[name]["path"] = path if domain: cookie[name]["domain"] = domain if expire: cookie[name]["expires"] = _expiration(expire, "%a, %d-%b-%Y %H:%M:%S GMT") return tuple(cookie.output().split(": ", 1))
class CookieScraper(object): "Scraper that keeps track of getting and setting cookies." def __init__(self): self._cookies = SimpleCookie() def get_page(self, url, post_data=None, headers=()): """ Helper method that gets the given URL, handling the sending and storing of cookies. Returns the requested page as a string. """ opener = urllib.URLopener() opener.addheader('Cookie', self._cookies.output(attrs=[], header='').strip()) for k, v in headers: opener.addheader(k, v) try: f = opener.open(url, post_data) except IOError, e: if e[1] == 302: # Got a 302 redirect, but check for cookies before redirecting. # e[3] is a httplib.HTTPMessage instance. if e[3].dict.has_key('set-cookie'): self._cookies.load(e[3].dict['set-cookie']) return self.get_page(e[3].getheader('location')) else: raise if f.headers.dict.has_key('set-cookie'): self._cookies.load(f.headers.dict['set-cookie']) return f.read()
def cookie(name, sid, seed, expire=0, domain="", path=""): """ Create and return a cookie :param sid: Session identifier :param seed: A seed for the HMAC function :param expire: Number of minutes before this cookie goes stale :param domain: The domain of the cookie :param path: The path specification for the cookie :return: A tuple to be added to headers """ cookie = SimpleCookie() timestamp = str(int(time.mktime(time.gmtime()))) #print >> sys.stderr, "COOKIE create '%s' '%s' '%s'" % (seed, sid, # timestamp) signature = cookie_signature(seed, sid, timestamp) #print >> sys.stderr, ">>", signature cookie[name] = "|".join([sid, timestamp, signature]) if path: cookie[name]["path"] = path if domain: cookie[name]["domain"] = domain if expire: cookie[name]["expires"] = _expiration(expire, "%a, %d-%b-%Y %H:%M:%S GMT") return tuple(cookie.output().split(": ", 1))
def set_cookie( self, key, value, max_age=None, expires=None, path='/', domain=None ): """ Adds the given cookie to the response, so it will be set on the user's browser. """ cookies = Cookie() cookies[key] = value if isinstance(max_age, timedelta): max_age = max_age.seconds + max_age.days*24*60*60 if max_age is not None and expires is None: expires = datetime.utcnow() + timedelta(seconds=max_age) if isinstance(expires, timedelta): expires = datetime.utcnow() + expires if isinstance(expires, datetime): expires = '"'+datetime_utils._serialize_cookie_date(expires)+'"' for var_name, var_value in [('max-age', max_age), ('path', path), ('domain', domain), ('expires', expires)]: if var_value is not None: cookies[key][var_name] = str(var_value) cookies = cookies.output(header='').lstrip() if cookies: self.extra_headers.append(('Set-Cookie', cookies))
class CookiesProvider(object): """ CookiesProvider class""" def __init__(self): """ Init interface """ self._cookies = None @property def _is_cookie_fetched(self): """ Check if cookies has been fetched from response :return: bool """ return False if None is self._cookies else True def _fetch_cookies(self, headers): """ Fetch cookies from response :param dict headers: response header :return: None """ if 'set-cookie' in headers: self._cookies = SimpleCookie(headers['set-cookie']) def _push_cookies(self): """ Push cookies to request :return: str cookies """ return self._cookies.output(attrs=[], header='').strip()
def set_cookie(name, _, *args): cookie = SimpleCookie() cookie[name] = base64.b64encode(":".join(args)) cookie[name]['path'] = "/" cookie[name]["expires"] = _expiration(5) # 5 minutes from now logger.debug("Cookie expires: %s", cookie[name]["expires"]) return tuple(cookie.output().split(": ", 1))
class CookieScraper(object): "Scraper that keeps track of getting and setting cookies." def __init__(self): self._cookies = SimpleCookie() def get_page(self, url, post_data=None, headers=()): """ Helper method that gets the given URL, handling the sending and storing of cookies. Returns the requested page as a string. """ socket.timeout(300) opener = urllib.URLopener() opener.addheader('Cookie', self._cookies.output(attrs=[], header='', sep=';').strip()) for k, v in headers: opener.addheader(k, v) try: f = opener.open(url, post_data) except IOError, e: if e[1] == 302: # Got a 302 redirect, but check for cookies before redirecting. # e[3] is a httplib.HTTPMessage instance. if e[3].dict.has_key('set-cookie'): self._cookies.load(e[3].dict['set-cookie']) return self.get_page(e[3].getheader('location')) else: raise if f.headers.dict.has_key('set-cookie'): self._cookies.load(f.headers.dict['set-cookie']) return f.read()
def set_cookie(name, _, value): cookie = SimpleCookie() cookie[name] = value cookie[name]['path'] = "/" cookie[name]["expires"] = _expiration(5) # 5 minutes from now logger.debug("Cookie expires: %s" % cookie[name]["expires"]) return tuple(cookie.output().split(": ", 1))
def __init__(self, hnd, name = session.COOKIE_NAME, timeout = 0): super(DatastoreSession, self).__init__(hnd, name, timeout) SessionStore.clear() # check from cookie if not timeout: config = Config() timeout = config.get('session_timeout', 60*60) elif timeout == -1: timeout = 356*24*60*60*50 if name in hnd.request.cookies: self._id = hnd.request.cookies[name] res = SessionStore.gql("WHERE id = :1", self._id).get() if res: self._store = res session_data = self._store.value if session_data: self.update(pickle.loads(session_data)) else: self._create_store(self._id) else: # not in the cookie, set it c = SimpleCookie() c[name] = self._id c[name]['path'] = '/' c[name]['expires'] = rfc822.formatdate(time()+timeout) cs = c.output().replace('Set-Cookie: ', '') hnd.response.headers.add_header('Set-Cookie', cs) self._create_store(self._id)
def get(self, mode=''): if mode == 'login': if 'allowed' in self.request.cookies and \ self.request.cookies['allowed'].count('_'): _twitter_id, _login_hash = \ self.request.cookies['allowed'].split('_', 1) user_info = UserInfo.all().filter('twitter_id =', _twitter_id).get() if user_info and _sha512(user_info.acc_key) == _login_hash: self.session = Session() self.session['twitter_id'] = _twitter_id return self.redirect('/home') auth = _oauth_handler() auth_url = auth.get_authorization_url() memcache.set(auth.request_token.key, auth.request_token.secret, 3600) return self.redirect(auth_url) elif mode == 'verify': auth = _oauth_handler() ver = self.request.get('oauth_verifier') req_key = self.request.get('oauth_token') req_sec = memcache.get(req_key) auth.set_request_token(req_key, req_sec) acc_token = auth.get_access_token(ver) api = tweepy.API(auth_handler=auth) me = api.me() if not UserInfo.all().filter('twitter_id =', str(me.id)).get(): user_info = UserInfo(twitter_id=str(me.id), screen_name=me.screen_name, name=me.name, image=me.profile_image_url, acc_key=acc_token.key, acc_sec=acc_token.secret) user_info.put() self.session = Session() self.session.delete_item('twitter_id') self.session['twitter_id'] = str(me.id) c = SimpleCookie() c['allowed'] = '%d_%s' % (me.id, _sha512(acc_token.key)) c['allowed']['path'] = '/auth' c['allowed']['expires'] = 86400 * 10 self.response.headers.add_header('Set-Cookie', c.output(header='')) return self.redirect('/home') elif mode == 'logout': user_info = _login_user(self) if user_info: self.session = Session() self.session.delete_item('twitter_id') return self.redirect('/')
def get(self, mode = ''): if mode == 'login': if 'allowed' in self.request.cookies and \ self.request.cookies['allowed'].count('_'): _twitter_id, _login_hash = \ self.request.cookies['allowed'].split('_', 1) user_info = UserInfo.all().filter('twitter_id =', _twitter_id).get() if user_info and _sha512(user_info.acc_key) == _login_hash: self.session = Session() self.session['twitter_id'] = _twitter_id return self.redirect('/home') auth = _oauth_handler() auth_url = auth.get_authorization_url() memcache.set(auth.request_token.key, auth.request_token.secret, 3600) return self.redirect(auth_url) elif mode == 'verify': auth = _oauth_handler() ver = self.request.get('oauth_verifier') req_key = self.request.get('oauth_token') req_sec = memcache.get(req_key) auth.set_request_token(req_key, req_sec) acc_token = auth.get_access_token(ver) api = tweepy.API(auth_handler = auth) me = api.me() if not UserInfo.all().filter('twitter_id =', str(me.id)).get(): user_info = UserInfo(twitter_id = str(me.id), screen_name = me.screen_name, name = me.name, image = me.profile_image_url, acc_key = acc_token.key, acc_sec = acc_token.secret) user_info.put() self.session = Session() self.session.delete_item('twitter_id') self.session['twitter_id'] = str(me.id) c = SimpleCookie() c['allowed'] = '%d_%s' % (me.id, _sha512(acc_token.key)) c['allowed']['path'] = '/auth' c['allowed']['expires'] = 86400 * 10 self.response.headers.add_header('Set-Cookie', c.output(header = '')) return self.redirect('/home') elif mode == 'logout': user_info = _login_user(self) if user_info: self.session = Session() self.session.delete_item('twitter_id') return self.redirect('/')
class TestClient(object): def __init__(self): self.cookies = SimpleCookie() def get_request(self, path, method="GET", body=None, **extra): env = StubWSGIRequest(path) env['REQUEST_METHOD'] = method env['wsgi.input'] = StringIO(body) env['HTTP_COOKIE'] = self.cookies.output(header='', sep='; ') env.update(extra) return Request.from_wsgi(env) def perform_request(self, request, user): request.website = test_website if user is not None: user = User.from_username(user) # Note that Cookie needs a bytestring. request.headers.cookie[str('session')] = user.session_token response = test_website.handle_safely(request) if response.headers.cookie: self.cookies.update(response.headers.cookie) return response def post(self, path, data, user=None, content_type=MULTIPART_CONTENT, **extra): """Perform a dummy POST request against the test website. :param path: The url to perform the virutal-POST to. :param data: A dictionary or list of tuples to be encoded before being POSTed. :param user: The user id performing the POST. Any additional parameters will be sent as headers. NOTE that in Aspen (request.py make_franken_headers) only headers beginning with ``HTTP`` are included in the request - and those are changed to no longer include ``HTTP``. There are currently 2 exceptions to this: ``'CONTENT_TYPE'``, ``'CONTENT_LENGTH'`` which are explicitly checked for. """ post_data = data if content_type is MULTIPART_CONTENT: post_data = encode_multipart(BOUNDARY, data) request = self.get_request(path, "POST", post_data, CONTENT_TYPE=str(content_type), **extra) return self.perform_request(request, user) def get(self, path, user=None, **extra): request = self.get_request(path, "GET") return self.perform_request(request, user)
def clearCookie(self, name): """ cache the cookie set until response sent. """ c = SimpleCookie() c[name] = '' c[name]['path'] = '/' c[name]['expires'] = 0 self.__cached_cookie[name] = c.output(header='')
def writeCookie(self, name, value, path = '/', days_from_now = 30): """ cache the cookie set until response sent. """ c = SimpleCookie() c[name] = value c[name]['path'] = path c[name]['expires'] = GetCacheExpires(days_from_now) self.__cached_cookie[name] = c.output(header='')
def logout(_request): body = base_body % ("<p>Logged out</p>") res = Response() c = SimpleCookie() c["authhash"] = "" res.set_header(*c.output().split(': ')) res.set_body(body) return res
def writeCookie(self, name, value, path='/', days_from_now=30): """ cache the cookie set until response sent. """ c = SimpleCookie() c[name] = value c[name]['path'] = path c[name]['expires'] = GetCacheExpires(days_from_now) self.__cached_cookie[name] = c.output(header='')
def logout(_request): body = base_body % ('<p>Logged out</p>') res = Response() c = SimpleCookie() c['authhash'] = '' res.set_header(*c.output().split(': ')) res.set_body(body) return res
def logout(_request): body=get_htmltemplate() % ('<p>Logged out</p>') res=Response() c=SimpleCookie() c['authhash']='' res.set_header(*c.output().split(': ')) res.set_body(body) return res
def confirm(theform, userdir, thisscript): """Confirm a login. Either from an invite or from a user who has registered.""" from dataenc import pass_dec, pass_enc from login import encodestring fail = False try: theval, daynumber, timestamp = pass_dec(theform['id'].value) except: # FIXME: bare except.... newloginfail() tempstore = ConfigObj(userdir + 'temp.ini') if not tempstore.has_key(theval): newloginfail() uservals = tempstore[theval] del tempstore[theval] username = uservals['username'] if username in tempstore['pending']: tempstore['pending'].remove(username) tempstore.write() # newconfig = ConfigObj(userdir + 'default.ini') newpath = userdir + username + '.ini' if os.path.isfile(newpath): newloginfail() newconfig.filename = newpath # FIXME: should this be '' ? action = None for entry in uservals: if entry == 'action': action = uservals[entry] elif entry == 'password': password = uservals[entry] newconfig[entry] = pass_enc(password, timestamp=True, daynumber=True) else: newconfig[entry] = uservals[entry] newconfig.write() # # next we need to create the cookie header to return it from Cookie import SimpleCookie thecookie = SimpleCookie() thecookie['userid'] = encodestring(newconfig['username'], password) config = ConfigObj(userdir + 'config.ini') maxage = newconfig['max-age'] cookiepath = config['cookiepath'] if maxage and int(maxage): # possible cause of error here if the maxage value in a users file isn't an integer !! thecookie['userid']['max-age'] = int(maxage) if cookiepath: thecookie['userid']['path'] = cookiepath if config['adminmail']: msg = 'A new user has created a login - "%s".\n\n' % thisscript for entry in newconfig: if entry != 'password': msg += entry + ' : ' + newconfig[entry] + '\n' # FIXME: should be mailme sendmailme(config['adminmail'], msg, config['email_subject'], config['adminmail'], html=False) return action, newconfig, thecookie.output()
def delete_cookie(environ, name): c = SimpleCookie() c[name] = '' c[name]['expires'] = \ d=date.today()-timedelta(days=30) s = c.output() (key, value) = s.split(': ') return (key, value)
def set_cookie(self, user): uid = rndstr(32) self.uid2user[uid] = user cookie = SimpleCookie() cookie[self.cookie_name] = uid cookie[self.cookie_name]['path'] = "/" cookie[self.cookie_name]["expires"] = _expiration(480) logger.debug("Cookie expires: %s" % cookie[self.cookie_name]["expires"]) return cookie.output().split(": ", 1)
def __get_request_data(app, request, session): """Get request data. """ try: parameters = request.json or {} except: parameters = {"INVALID_JSON": request.data} form = request.form.to_dict(flat=False) for key, value in form.iteritems(): if len(value) == 1: parameters[key] = value[0] else: parameters[key] = value files = request.files.to_dict(flat=False) for key, value in files.iteritems(): if len(value) == 1: parameters[key] = value[0].filename else: parameters[key] = [file.filename for file in value] if request.cookies: cookies = Exceptional.__filter(app, request.cookies, "EXCEPTIONAL_COOKIE_FILTER") headers = Headers(request.headers) # Get a mutable dictionary. cookie = SimpleCookie() for key, value in cookies.iteritems(): cookie[key] = value headers["Cookie"] = cookie.output(header='', sep=';').strip() else: headers = request.headers return { "session": Exceptional.__filter(app, session, "EXCEPTIONAL_SESSION_FILTER"), "remote_ip": request.remote_addr, "parameters": Exceptional.__filter(app, parameters, "EXCEPTIONAL_PARAMETER_FILTER"), "action": request.endpoint.split('.', 1)[-1] if request.endpoint else None, "url": request.url, "request_method": request.method, "controller": request.blueprint if hasattr(request, "blueprint") else request.module, "headers": Exceptional.__filter(app, headers, "EXCEPTIONAL_HEADER_FILTER") }
def login(): confdir = findconffolder() conf = ConfigParser.ConfigParser() conf.read(join(confdir, "config")) # make the url and credentials url = join(conf.get("resources", "url"), "authenticate/login") username = raw_input("Username: "******"Password: "******"username": username, "password": password}) parsed_url = urlparse(url) host = parsed_url.netloc if parsed_url.scheme == "https": conn = httplib.HTTPSConnection(host) else: conn = httplib.HTTPConnection(host) response = conn.request("POST", parsed_url.path, creds, {"Content-type": "application/x-www-form-urlencoded"}) response = conn.getresponse() if response.status > 400: raise LoginError( "Login to %s failed with the following message: %s %s (%s)" % (url, response.status, response.reason, response.msg) ) response.read() setcookie = response.getheader("Set-Cookie") if setcookie == None: raise LoginError( "Login failed. This is usually because of " "invalid username/password, but might be " "caused by wrong login urlprefix or server errors. " "Technical error message: Login urlprefix did not " "respond with any authorization cookies." ) cookie = SimpleCookie() cookie.load(setcookie) cookieout = cookie.output().replace("Set-Cookie: ", "") session = open(join(confdir, "session"), "w") session.write(cookieout) session.close() chmod(join(confdir, "session"), stat.S_IRUSR | stat.S_IWUSR) conf.set("resources", "user", username) with open(join(confdir, "config"), "wb") as f: conf.write(f) return cookieout
def destroyCookieHeader(id): cur.execute("""DELETE FROM SESSION WHERE ID='%s'""" % (id)) con.commit() c = SimpleCookie() c['username'] = '' s = c.output() (key, value) = s.split(': ') return (key, value)
def post(self): try: user = users.get_current_user() if user is None: return self.redirect('/index') else: logout_link = users.create_logout_url(PROTOCOLHTTP + DOMAIN + "/index") cookie = SimpleCookie(os.environ.get('HTTP_COOKIE', '')) if cookie.has_key('picturetooken'): tooken = cookie['picturetooken'].value cookie = SimpleCookie(os.environ.get('HTTP_COOKIE', '')) cookie['picturetooken'] = "" cookie['picturetooken']['expires'] = 3600 print cookie.output() hiddenToken = self.request.get('tooken') if tooken != hiddenToken: #return self.redirect('/user/picture/insert') raise i = 0 while (i < 9): binary = self.request.get('binary_' + str(i)) #print len(binary) if not binary: break name = self.request.body_file.vars['binary_' + str(i)].filename mime = self.request.body_file.vars[ 'binary_' + str(i)].headers['content-type'] self.registerPicture(binary, name, mime, user) i += 1 if user: loginFlg = 1 params = {'logout_link': logout_link, 'loginFlg': loginFlg} fpath = os.path.join(os.path.dirname(__file__), 'template/user/picture', 'insertend.html') html = template.render(fpath, params) self.response.out.write(html) except: self.errorFunc()
def session_start_response(status, headers, exc_info=None): """ A start_response function that append a session cookie to the response headers if necessary. """ if session.stored(): cookie = SimpleCookie() cookie['session_id'] = session.get_id() cookiestr = cookie.output().replace('Set-Cookie: ', '', 1) headers.append(('Set-Cookie', cookiestr)) return start_response(status, headers, exc_info)
def create_session(cls, user): """ creates a session for a given user """ s = Session(cls._core, user) cookie = SimpleCookie() cookie["session_id"] = s.get_id() cls._core.response_header.append(("Set-Cookie", cookie.output().replace("Set-Cookie: ", "", 1))) s.store() return s
def clear_username(cookie): c = SimpleCookie() c.load(cookie) expires = datetime.datetime(2000, 2, 14, 18, 30, 14) + datetime.timedelta(hours=1) c["username"]["expires"] = expires.strftime("%a, %d %b %Y %H:%M:%S") s = c.output() (key, value) = s.split(": ") return (key, value)
def delete_cookie(environ, name): kaka = environ.get("HTTP_COOKIE", "") if kaka: cookie_obj = SimpleCookie(kaka) morsel = cookie_obj.get(name, None) cookie = SimpleCookie() cookie[name] = morsel cookie[name]["expires"] = _expiration("now", "%a, %d-%b-%Y %H:%M:%S CET") return tuple(cookie.output().split(": ", 1)) return None
def set(self, name, string, seconds=None): if seconds == None: seconds = self.DEFAULT_EXPIRATION from Cookie import SimpleCookie import datetime cookie = SimpleCookie() cookie[name] = string cookie[name]["path"] = "/" cookie[name]["expires"] = (datetime.datetime.now()+datetime.timedelta(seconds=seconds)).strftime('%a, %d %b %Y %H:%M:%S') self.webapp2instance.response.headers.add_header("Set-Cookie", cookie.output(header=''))
def clear_username(cookie): c = SimpleCookie() c.load(cookie) expires = datetime.datetime(2000, 2, 14, 18, 30, 14) + datetime.timedelta(hours=1) c['username']['expires'] = expires.strftime('%a, %d %b %Y %H:%M:%S') s = c.output() (key, value) = s.split(': ') return (key, value)
def emptycookie(cookiepath=None): """Return an empty cookie with max-age 0. Used for logout features. """ from Cookie import SimpleCookie thecookie = SimpleCookie() thecookie['userid'] = '' thecookie['userid']['max-age'] = 0 if cookiepath: thecookie['userid']['path'] = cookiepath return thecookie.output() # XXXX may need to be able to return the cookie object
def delete_cookie(environ, name): kaka = environ.get("HTTP_COOKIE", '') if kaka: cookie_obj = SimpleCookie(kaka) morsel = cookie_obj.get(name, None) cookie = SimpleCookie() cookie[name] = morsel cookie[name]["expires"] = \ _expiration("now", "%a, %d-%b-%Y %H:%M:%S CET") return tuple(cookie.output().split(": ", 1)) return None
class ManageCookie(object): def __init__(self): self.ck = SimpleCookie() self.ck.load(os.environ.get("HTTP_COOKIE","")) def assemble_ck2dict(self): d = {} for i in self.ck: d[i] = self.ck[i].value return d def destroy_ck(self,*args): for i in args: if(i in self.ck): self.ck[i]["expires"] = "Tue, 31-Dec-2001 00:00:00 GMT" def destroy_allck(self): for i in self.ck: self.ck[i] = "-1" self.ck[i]["expires"] = "Tue, 31-Dec-2001 00:00:00 GMT" def set_ck(self,**kws): cktime = time.time() + 86400 for i in kws: self.ck[i] = urllib2.quote(kws[i]) self.ck[i]["expires"] = time.strftime(''' %a, %d %b %Y %H:%M:%S GMT''', time.gmtime(cktime)) def reset_ck(self): cktime = time.time() + 86400 for i in self.ck: self.ck[i]["expires"] = time.strftime(''' %a, %d %b %Y %H:%M:%S GMT''', time.gmtime(cktime)) def check_ses_reg(self): if(not ("regid" in self.ck) or not ("seskey" in self.ck)): return False,None else: tmp_ses = self.ck["seskey"].value tmp_reg = self.ck["regid"].value if(not check_id_seskey(mregid=tmp_reg,mseskey=tmp_ses)): return False,None else: return tmp_ses,tmp_reg def print_ck(self): for i in self.ck: print(self.ck.output(i))
def delete_cookie(environ, name): kaka = environ.get("HTTP_COOKIE", '') if kaka: cookie_obj = SimpleCookie(kaka) morsel = cookie_obj.get(name, None) cookie = SimpleCookie() cookie[name] = "" cookie[name]['path'] = "/" logger.debug("Expire: %s" % morsel) cookie[name]["expires"] = _expiration("dawn") return tuple(cookie.output().split(": ", 1)) return None
def create_session(cls, user): """ creates a session for a given user """ s = Session(cls._core,user) cookie = SimpleCookie() cookie["session_id"] = s.get_id() cls._core.response_header.append( ("Set-Cookie", cookie.output().replace("Set-Cookie: ","",1)) ) s.store() return s
def __get_request_data(app, request, session): """Get request data. """ try: parameters = request.json or {} except: parameters = {"INVALID_JSON": request.data} form = request.form.to_dict(flat=False) for key, value in form.iteritems(): if len(value) == 1: parameters[key] = value[0] else: parameters[key] = value files = request.files.to_dict(flat=False) for key, value in files.iteritems(): if len(value) == 1: parameters[key] = value[0].filename else: parameters[key] = [file.filename for file in value] if request.cookies: cookies = Exceptional.__filter(app, request.cookies, "EXCEPTIONAL_COOKIE_FILTER") headers = Headers(request.headers) # Get a mutable dictionary. cookie = SimpleCookie() for key, value in cookies.iteritems(): cookie[key] = value headers["Cookie"] = cookie.output(header='', sep=';').strip() else: headers = request.headers return { "session": Exceptional.__filter(app, session, "EXCEPTIONAL_SESSION_FILTER"), "remote_ip": request.remote_addr, "parameters": Exceptional.__filter(app, parameters, "EXCEPTIONAL_PARAMETER_FILTER"), "action": request.endpoint.split('.', 1)[-1] if request.endpoint \ else None, "url": request.url, "request_method": request.method, "controller": request.blueprint if hasattr(request, "blueprint") \ else request.module, "headers": Exceptional.__filter(app, headers, "EXCEPTIONAL_HEADER_FILTER") }
def __init__(self, request): """retrieves session id from cookie and push it back into the cookie after recreating it if session has expired""" self._request = request cookie = SimpleCookie(request.headers.get("cookie", "")) name = request.server.version_name if name in cookie: request.id = cookie[name].value cookie[name] = request.session["id"] cookie[name]["expires"] = 30 * 24 * 60 * 60 # 30 days request.id = cookie[name].value self._headers = {"Content-Type": "text/html", "Set-Cookie": cookie.output(header="")}
def delete_cookie(self, environ, name): cookie = environ.get("HTTP_COOKIE", '') logger.debug("delete KAKA: %s" % cookie) if cookie: cookie_obj = SimpleCookie(cookie) morsel = cookie_obj.get(name, None) cookie = SimpleCookie() cookie[name] = "" cookie[name]['path'] = "/" logger.debug("Expire: %s" % morsel) cookie[name]["expires"] = self._expiration("dawn") return tuple(cookie.output().split(": ", 1)) return None
def delete_cookie(environ, name): kaka = environ.get("HTTP_COOKIE", '') logger.debug("delete KAKA: %s" % kaka) if kaka: cookie_obj = SimpleCookie(kaka) morsel = cookie_obj.get(name, None) cookie = SimpleCookie() cookie[name] = "" cookie[name]['path'] = "/" logger.debug("Expire: %s" % morsel) cookie[name]["expires"] = _expiration("dawn") return tuple(cookie.output().split(": ", 1)) return None
def login(): # grab the config file confdir = utils.findconffolder() conf = ConfigParser.ConfigParser() conf.read(join(confdir, 'config')) if exists(join(confdir, 'session')): session = open(join(confdir, 'session'), 'r') cookieout = session.read() session.close() return cookieout # make the url and credentials url = join(conf.get('URL', 'url'), 'authenticate/login') creds = urllib.urlencode({'username': '******', 'password': '******'}) parsed_url = urlparse(url) host = parsed_url.netloc if parsed_url.scheme == "https": conn = httplib.HTTPSConnection(host) else: conn = httplib.HTTPConnection(host) response = conn.request( 'POST', parsed_url.path, creds, {'Content-type': "application/x-www-form-urlencoded"}) response = conn.getresponse() if response.status > 400: raise LoginError( "Login to %s failed with the following message: %s %s (%s)" % (url, response.status, response.reason, response.msg)) response.read() setcookie = response.getheader('Set-Cookie') if setcookie == None: raise LoginError("Login failed. This is usually because of " "invalid username/password, but might be " "caused by wrong login urlprefix or server errors. " "Technical error message: Login urlprefix did not " "respond with any authorization cookies.") cookie = SimpleCookie() cookie.load(setcookie) cookieout = cookie.output().replace('Set-Cookie: ', '') session = open(join(confdir, 'session'), 'w') session.write(cookieout) session.close() return cookieout
def make_set_cookie_header(name, value, path='/'): """ Makes a 'Set-Cookie' header. """ c = SimpleCookie() c[name] = value c[name]['path'] = path # can also set expires and other stuff. See # Examples under http://docs.python.org/library/cookie.html. s = c.output() (key, value) = s.split(': ') return (key, value)
def delete_cookie(self, environ): cookie = environ.get("HTTP_COOKIE", '') logger.debug("delete cookie: %s" % cookie) if cookie: _name = self.cookie_name cookie_obj = SimpleCookie(cookie) morsel = cookie_obj.get(_name, None) cookie = SimpleCookie() cookie[_name] = "" cookie[_name]['path'] = "/" logger.debug("Expire: %s" % morsel) cookie[_name]["expires"] = _expiration("now") return cookie.output().split(": ", 1) return None
def ready_cookie(request_handler): """ Readies a PHP-like cookie - not to be part of the final codebase """ host = request_handler.headers.get('Host') cookie = SimpleCookie() cookie['PHPSESSID'] = "21345" cookie['PHPSESSID']['Domain'] = host cookie['PHPSESSID']['path'] = "/" cookie['PHPSESSID']['version'] = "1" request_handler.new_headers.append(( 'Set-Cookie', cookie.output(header=''), ))
def _build_authorization_headers(self, username, password, session_id): """Adds the HTTP header for HTTP basic authentication if username and password were given.""" headers = dict() if session_id is not None: cookie = SimpleCookie() cookie['trac_auth'] = session_id header_value = cookie.output(header='').strip() headers['Cookie'] = header_value elif username is not None and password is not None: userinfo = base64.encodestring('%s:%s' % (username, password)) header_value = 'Basic ' + userinfo # Case matters for trac! headers['AUTHORIZATION'] = header_value return headers
def __init__(self, request): """retrieves session id from cookie and push it back into the cookie after recreating it if session has expired""" self._request = request cookie = SimpleCookie(request.headers.get("cookie", "")) name = request.server.version_name if name in cookie: request.id = cookie[name].value cookie[name] = request.session["id"] cookie[name]["expires"] = 30 * 24 * 60 * 60 # 30 days request.id = cookie[name].value self._headers = { "Content-Type": "text/html", "Set-Cookie": cookie.output(header="") }
def makecookie(userconfig, password, cookiepath): """ Return the current valid cookie heaader for the values supplied in the userconfig, the straight password and the cookiepath. """ from login import encodestring from Cookie import SimpleCookie thecookie = SimpleCookie() cookiestring = encodestring(userconfig['username'],password) maxage = userconfig['max-age'] thecookie['userid'] = cookiestring if maxage and int(maxage): # possible cause of error here if the maxage value in a users file isn't an integer !! thecookie['userid']['max-age'] = int(maxage) if cookiepath: thecookie['userid']['path'] = cookiepath return thecookie.output() # XXXX may need to be able to return the cookie object