async def connect(self): tc = self.testclient app = tc.application headers, path, query_string_bytes = make_test_headers_path_and_query_string( app, self.path, self.headers ) if self.cookies is None: # use TestClient.cookie_jar cookie_jar = tc.cookie_jar else: cookie_jar = SimpleCookie(self.cookies) if cookie_jar and cookie_jar.output(header=""): headers.add("Cookie", cookie_jar.output(header="")) scope = { "type": "websocket", "headers": flatten_headers(headers), "path": path, "query_string": query_string_bytes, "root_path": "", "scheme": "http", "subprotocols": [], } create_monitored_task( app(scope, self.input_queue.get, self.output_queue.put), self.output_queue.put_nowait, ) await self._send({"type": "websocket.connect"}) msg = await self._receive() assert msg["type"] == "websocket.accept"
async def logout(self, scope, receive, send): headers = [["location", "/"]] output_cookies = SimpleCookie() output_cookies[self.cookie_name] = "" output_cookies[self.cookie_name]["path"] = "/" output_cookies[self.cookie_name]["max-age"] = 0 output_cookies[self.cookie_name]["expires"] = 0 headers.append(["set-cookie", output_cookies.output(header="").lstrip()]) output_cookies = SimpleCookie() output_cookies[self.logout_cookie_name] = "stay-logged-out" output_cookies[self.logout_cookie_name]["path"] = "/" headers.append(["set-cookie", output_cookies.output(header="").lstrip()]) await send_html(send, "", 302, headers)
def handleRequest(self, request, response): # Skip handling request if authorization is disabled if not self._brewer.config.authorizationEnabled: return False session = None # Get the session ID from cookie, or create one if it doesn't exist if HDR_COOKIE in request.headers: # Session exists in cookie cookie = SimpleCookie() cookie.load(request.headers[HDR_COOKIE]) # Extract ID from cookie sessionId = cookie['id'].value # Check if session is valid session = self._sessionHandler.getSession(sessionId) if not session: # Session not valid, create a new one below logger.debug('invalid session %r' % sessionId) session = None else: logger.debug('session valid %r' % sessionId) if not session: # Create new session session = self._sessionHandler.createSession() # Create a cookie cookie = SimpleCookie() cookie['id'] = session.id cookie['id']["max-age"] = session.maxAge # Get a string representation cookie = cookie.output(header='')[1:] logger.debug('new cookie: %r' % cookie) response.addHeader(HDR_SET_COOKIE, cookie) # If session is not authorized let the login servlet handle this if not session.authorized: logger.debug('session not authorized: %r' % str(session)) # Allow only specific REST calls if request.url.path in self.LOGGED_OUT_REST_WHITELIST: return False # TODO Find a better way of redirecting to login servlet for i in self._brewer.server.servlets: if isinstance( i, PageServlet ) and i.manifestEntry.filePath == self.LOGIN_PAGE: return i.handleRequest(request, response) # Let the other servlets handle the request return False
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 _write_messages_to_response(self, request, response): if getattr(request, "_messages", None): # Set those messages cookie = SimpleCookie() cookie["ds_messages"] = self.sign(request._messages, "messages") cookie["ds_messages"]["path"] = "/" # TODO: Co-exist with existing set-cookie headers assert "set-cookie" not in response.headers response.headers["set-cookie"] = cookie.output(header="").lstrip() elif getattr(request, "_messages_should_clear", False): cookie = SimpleCookie() cookie["ds_messages"] = "" cookie["ds_messages"]["path"] = "/" # TODO: Co-exist with existing set-cookie headers assert "set-cookie" not in response.headers response.headers["set-cookie"] = cookie.output(header="").lstrip()
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 Session(SyncCallMixin): def __init__(self, cookies=None): self.cookie = SimpleCookie(cookies) def _get_cookie(self, response): for c in response.headers.get_list("Set-Cookie"): self.cookie.load(c) def cookie_output(self, keys=None): if keys: _ck = SimpleCookie({ k: v for k, v in self.cookie.items() if k in keys }) return _ck.output(attrs=[], header="", sep=";") else: return self.cookie.output(attrs=[], header="", sep=";") async def call(self, client, *args, **kwargs): headers = kwargs.get('headers', {}) if self.cookie: headers['Cookie'] = self.cookie_output() kwargs['headers'] = headers cli = client() data = await cli.call(*args, **kwargs) self._get_cookie(cli.response) return data
async def test_auth_callback_calls_github_apis_and_sets_cookie( redirect_path, require_auth_app): cookie = SimpleCookie() cookie["asgi_auth_redirect"] = redirect_path cookie["asgi_auth_redirect"]["path"] = "/" instance = ApplicationCommunicator( require_auth_app, { "type": "http", "http_version": "1.0", "method": "GET", "path": "/-/auth-callback", "query_string": b"code=github-code-here", "headers": [[b"cookie", cookie.output(header="").lstrip().encode("utf8")]], }, ) await instance.send_input({"type": "http.request"}) output = await instance.receive_output(1) assert_redirects_and_sets_cookie(require_auth_app, output, redirect_path)
def create_wsdl_request(self, wsdl_url): sid_cookie = SimpleCookie() sid_cookie['sid'] = self.SESSION_ID sid_header = sid_cookie.output(header='') headers = {'content-type': 'text/xml', 'Cookie': sid_header} req = request.Request(url=wsdl_url, method='GET', headers=headers) return req
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 _get_cookies(self, *args, **kwargs): u''' Override method in superclass to ensure HttpOnly is set appropriately. ''' super_cookies = super(CkanAuthTktCookiePlugin, self). \ _get_cookies(*args, **kwargs) cookies = [] for k, v in super_cookies: cookie = SimpleCookie(str(v)) morsel = list(cookie.values())[0] # SameSite was only added on Python 3.8 morsel._reserved['samesite'] = 'SameSite' # Keep old case as it's the one used in tests, it should make no # difference in the browser morsel._reserved['httponly'] = 'HttpOnly' morsel._reserved['secure'] = 'Secure' if self.httponly: cookie[self.cookie_name]['HttpOnly'] = True if self.samesite == 'none': cookie[self.cookie_name]['SameSite'] = 'None' elif self.samesite == 'strict': cookie[self.cookie_name]['SameSite'] = 'Strict' else: cookie[self.cookie_name]['SameSite'] = 'Lax' cookies.append((k, cookie.output().replace('Set-Cookie: ', ''))) return cookies
def _build_cookie_header(session, cookies, cookie_header, url): url, _ = strip_auth_from_url(url) all_cookies = session._cookie_jar.filter_cookies(url) if cookies is not None: tmp_cookie_jar = CookieJar() tmp_cookie_jar.update_cookies(cookies) req_cookies = tmp_cookie_jar.filter_cookies(url) if req_cookies: all_cookies.load(req_cookies) if not all_cookies and not cookie_header: return None c = SimpleCookie() if cookie_header: c.load(cookie_header) for name, value in all_cookies.items(): if isinstance(value, Morsel): mrsl_val = value.get(value.key, Morsel()) mrsl_val.set(value.key, value.value, value.coded_value) c[name] = mrsl_val else: c[name] = value return c.output(header="", sep=";").strip()
def set_cookie( self, key, value="", max_age=None, expires=None, path="/", domain=None, secure=False, httponly=False, samesite="lax", ): assert samesite in SAMESITE_VALUES, "samesite should be one of {}".format( SAMESITE_VALUES) cookie = SimpleCookie() cookie[key] = value for prop_name, prop_value in ( ("max_age", max_age), ("expires", expires), ("path", path), ("domain", domain), ("samesite", samesite), ): if prop_value is not None: cookie[key][prop_name.replace("_", "-")] = prop_value for prop_name, prop_value in (("secure", secure), ("httponly", httponly)): if prop_value: cookie[key][prop_name] = True self._set_cookie_headers.append(cookie.output(header="").strip())
def __init__(self, path, query_string, cookie, method, post, url_scheme, host): self._routes = dict() self.pattern_url = "" self.path = path self.full_path = path self.query_string = query_string self.method = method self.post = post self.url_scheme = url_scheme self.host = host self.matchdict = {} self.reinit() if settings.SQLITE_DBNAME: self.db = db.Database(settings.SQLITE_DBNAME) if cookie: request_cookie = SimpleCookie(cookie) if request_cookie.get("session"): session_id = request_cookie["session"].value if session_id: self.session_id = session_id if not self.session_id: self.session_id = uuid.uuid4().hex self.db.insert_session(self.session_id) session = self.db.get_session(self.session_id) self.session, self.session_expires = session if self.session_expires > datetime.datetime.utcnow().replace( tzinfo=datetime.timezone.utc) - timedelta(days=1): cookie = SimpleCookie() cookie["session"] = self.session_id cookie["session"]["expires"] = settings.SESSION_LENGTH self.set_cookie = tuple(cookie.output().split(": ", 1)) self.user = self.db.get_user_by_session(self.session_id)
def update_cookies(self, cookies: Optional[LooseCookies]) -> None: """Update request cookies header.""" if not cookies: return c = SimpleCookie() if hdrs.COOKIE in self.headers: c.load(self.headers.get(hdrs.COOKIE, '')) del self.headers[hdrs.COOKIE] if isinstance(cookies, Mapping): iter_cookies = cookies.items() else: iter_cookies = cookies # type: ignore for name, value in iter_cookies: if isinstance(value, Morsel): # Preserve coded_value mrsl_val = value.get(value.key, Morsel()) mrsl_val.set(value.key, value.value, value.coded_value) # type: ignore # noqa c[name] = mrsl_val else: c[name] = value # type: ignore self.headers[hdrs.COOKIE] = c.output(header='', sep=';').strip()
def test_get_cookie(self): cookie = SimpleCookie() cookie["dpx"] = "test-cookie" expected_api_resp = "Cookie is successfully set to {'dpx': 'test-cookie'}" client = Client(HTTP_COOKIE=cookie.output(header='', sep='; ')) resp = client.get('/home_loans/cookie/get_cookie/') self.assertEqual(resp.data, expected_api_resp) self.assertEqual(resp.status_code, 200)
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 setCookie(sessid): expiration = datetime.datetime.now() + datetime.timedelta( hours=-4, seconds=60 * 60) #current EST + 1 hour c = SimpleCookie() c["session"] = sessid c["session"]["secure"] = True c["session"]["expires"] = expiration.strftime("%a, %d-%b-%Y %H:%M:%S EST") return c.output()
def user2kaka(self, user): uid = rndbytes(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 tuple(cookie.output().split(": ", 1))
def output_with_args_sep(self): """output()を使う時に、引数sepを指定する場合""" print('[{}]:'.format(inspect.getframeinfo(inspect.currentframe())[2])) data = { 'foo': 'ham', 'bar': 'spam', } cookie = SimpleCookie(data) print(cookie.output(sep='++++'))
def cookies_partial(self, match): cookies = SimpleCookie() cookies['c1'] = 'other_cookie1' resp = self._start_response(200) for cookie in cookies.output(header='').split('\n'): resp.add_header('Set-Cookie', cookie.strip()) return self._response(resp)
def application1(environ,start_response): try: request_body_size = remainbytes = int(environ.get('CONTENT_LENGTH',0)) except ValueError: request_body_size = remainbytes = 0 if remainbytes > 0: CONTENT_TYPE = environ.get('CONTENT_TYPE','') boundary = re.findall('multipart/form-data.*boundary=(.*)',CONTENT_TYPE)[0].encode('ascii') wsgi_input = environ['wsgi.input'] line = wsgi_input.readline() remainbytes -= len(line) if not boundary in line: return (False,"Content NOT begin with boundary") line = wsgi_input.readline() remainbytes -= len(line) line = line.decode('ascii') fn = re.findall(r'Content-Disposition.*name="file"; filename="(.*)"', line)[0] line = wsgi_input.readline() remainbytes -= len(line) line = wsgi_input.readline() remainbytes -= len(line) blocksize = 8192 out = open(fn,'wb') preline = wsgi_input.readline() remainbytes -= len(line) while remainbytes > 0: line = wsgi_input.readline() remainbytes -= len(line) if boundary in line: preline = preline[0:-1] if preline.endswith(b'\r'): preline = preline[0:-1] out.write(preline) out.close() break else: out.write(preline) preline = line cookie = SimpleCookie(environ.get('HTTP_COOKIE','')) if 'sid' in cookie: sid = cookie['sid'].value message = 'already session' else: sid = hashlib.sha224(repr(time.time()).encode('ascii')).hexdigest() cookie['sid'] = sid message = 'new session' cookie['sid']['expires'] = 60 response_body = html % ("OK" if request_body_size else "Empty",message,sid) status = '200 OK' response_headers = [('Set-Cookie',cookie.output(header="")), ('Content-Type','text/html'), ('Content-Length',str(len(response_body))) ] start_response(status,response_headers) #response_body = response_body.encode('ascii') return [response_body.encode('ascii')]
def get_cookie_string(token=None): cookie = SimpleCookie() cookie[CONFIG['CookieName']] = token if token: cookie[CONFIG['CookieName']]['expires'] = CONFIG[ 'CookieDurationInSeconds'] else: cookie[CONFIG['CookieName']]['expires'] = 0 cookie[CONFIG['CookieName']]['domain'] = CONFIG['CookieDomain'] return cookie.output(header='')
def logout(uid=112): expiration = datetime.datetime.now() + datetime.timedelta( hours=-4, seconds=-60 * 60) #current EST - 1 hour c = SimpleCookie() c["session"] = "" c["session"]["expires"] = expiration.strftime("%a, %d-%b-%Y %H:%M:%S EST") ibm_db.exec_immediate(conn, f"DELETE from session WHERE USER_ID = {uid}") return c.output()
def cookie_output(self, keys=None): if keys: _ck = SimpleCookie({ k: v for k, v in self.cookie.items() if k in keys }) return _ck.output(attrs=[], header="", sep=";") else: return self.cookie.output(attrs=[], header="", sep=";")
def logout(request): if request.user_id is None: return session_table = Table.get_table('sessions', 'auth') session_table.remove(session_table.all.get(user_id=request.user_id)) session_table.save() cookie = SimpleCookie() cookie['session_id'] = '' request.send_header('Set-Cookie', cookie.output(header='', sep='')) request.user_id = None
def _set_common_domain_cookie(self, internal_response, http_args, context): """ """ # Find any existing common domain cookie and deconsruct it to # obtain the list of IdPs. cookie = SimpleCookie(context.cookie) if '_saml_idp' in cookie: common_domain_cookie = cookie['_saml_idp'] satosa_logging(logger, logging.DEBUG, "Found existing common domain cookie {}".format(common_domain_cookie), context.state) space_separated_b64_idp_string = unquote(common_domain_cookie.value) b64_idp_list = space_separated_b64_idp_string.split() idp_list = [urlsafe_b64decode(b64_idp).decode('utf-8') for b64_idp in b64_idp_list] else: satosa_logging(logger, logging.DEBUG, "No existing common domain cookie found", context.state) idp_list = [] satosa_logging(logger, logging.DEBUG, "Common domain cookie list of IdPs is {}".format(idp_list), context.state) # Identity the current IdP just used for authentication in this flow. this_flow_idp = internal_response.auth_info.issuer # Remove all occurrences of the current IdP from the list of IdPs. idp_list = [idp for idp in idp_list if idp != this_flow_idp] # Append the current IdP. idp_list.append(this_flow_idp) satosa_logging(logger, logging.DEBUG, "Added IdP {} to common domain cookie list of IdPs".format(this_flow_idp), context.state) satosa_logging(logger, logging.DEBUG, "Common domain cookie list of IdPs is now {}".format(idp_list), context.state) # Construct the cookie. b64_idp_list = [urlsafe_b64encode(idp.encode()).decode("utf-8") for idp in idp_list] space_separated_b64_idp_string = " ".join(b64_idp_list) url_encoded_space_separated_b64_idp_string = quote(space_separated_b64_idp_string) cookie = SimpleCookie() cookie['_saml_idp'] = url_encoded_space_separated_b64_idp_string cookie['_saml_idp']['path'] = '/' # Use the domain from configuration if present else use the domain # from the base URL for the front end. domain = urlparse(self.base_url).netloc if isinstance(self.config['common_domain_cookie'], dict): if 'domain' in self.config['common_domain_cookie']: domain = self.config['common_domain_cookie']['domain'] # Ensure that the domain begins with a '.' if domain[0] != '.': domain = '.' + domain cookie['_saml_idp']['domain'] = domain cookie['_saml_idp']['secure'] = True # Set the cookie. satosa_logging(logger, logging.DEBUG, "Setting common domain cookie with {}".format(cookie.output()), context.state) http_args['headers'].append(tuple(cookie.output().split(": ", 1)))
def set_cookie(self, cookies): cookie = SC() for k, v, expires, path, domain in cookies: if not path: path = '/' k = UE(k) v = UE(v) cookie[k] = v cookie[k]['expires'] = expires cookie[k]['path'] = path cookie[k]['domain'] = domain return cookie.output()
def do_GET(self): """Handle GET requests.""" # Craft multiple cookies cookie = SimpleCookie() cookie['hello'] = 'world' cookie['hello']['path'] = self.path cookie['oatmeal_raisin'] = 'is the best' cookie['oatmeal_raisin']['path'] = self.path # Send HTTP headers self.send_response(200) self.send_header('Set-Cookie', cookie.output()) self.end_headers()
def test_falcon_middleware_beaker(client): response = client.simulate_get('/') assert response.status == falcon.HTTP_OK assert response.content == b'1' response = client.simulate_get('/') assert response.status == falcon.HTTP_OK assert response.content == b'1' cookie = SimpleCookie() cookie.load(response.headers['set-cookie']) headers = [('Cookie', cookie.output(header=''))] response = client.simulate_get('/', headers=headers) assert response.status == falcon.HTTP_OK assert response.content == b'2'
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 do_GET(self): c = SimpleCookie() c['name'] = '张三' c['cartid'] = '123' c['amount'] = '2' self.send_response(200) self.wfile.write(c.output().encode(encoding='utf_8')) self.send_header('content-type', 'text/plain;charset=utf-8') #print(c.output()) self.end_headers() resp = "你好!" self.wfile.write(resp.encode('utf-8'))
def cookie(environ, start_response): visit_in_html = 1 headers = [('Content-Type', 'text/plain'),] if app.cookie: visit_in_html = int(app.cookie['http_only'].value) + 1 else: http_only = SimpleCookie('http_only=1') http_only['http_only']['max-age'] = 5 headers.append(('Set-Cookie', http_only.output(header=''))) start_response('200 OK', headers) return ["Hello, No.{}".format(visit_in_html).encode('utf-8')]
def cookie(environ, start_response): visit_in_html = 1 headers = [ ('Content-Type', 'text/plain'), ] # 今回、"visit"というCookieは一つしかない前提、実際には複数設定されることもある # http://www.yunabe.jp/docs/cookie_and_security.html#cookie- if app.cookie: if 'visit' in app.cookie: app.cookie['visit'] = visit_in_html = int( app.cookie['visit'].value) + 1 else: app.cookie['visit'] = 1 # RFC6265より、UAからはCookieの属性は送信されないため、サーバ側で毎回属性をセットする # https://triple-underscore.github.io/RFC6265-ja.html#section-4.2.2 app.cookie['visit']['httponly'] = True # 複数のCookieへのサーバ側での対応 # RFC6265より、複数のCookieがある場合、その分Set-Cookie応答ヘッダを用意する必要がある # https://triple-underscore.github.io/RFC6265-ja.html#section-4.1.1 # そこで、複数のCookieがあるapp.cookie(SimpleCookieオブジェクト)の値を、output(header='')で確認すると、 # http://docs.python.jp/3/library/http.cookies.html#http.cookies.BaseCookie.output print('-' * 10) print('app_cookie:\n{}\n'.format(app.cookie.output(header=''))) print('-' * 10) # """ # ---------- # app_cookie: # hoge=fuga # visit=2; HttpOnly # # ---------- # """ # と、「CRLF + 半角スペース」で連結された状態で取得できる # 今回、HTTPレスポンスヘッダは # "headers.append(('Set-Cookie', '<Cookie名>=<Cookie値>'))" # のようにして作ることから、以下のような処理となる server_cookies = app.cookie.output(header='').split('\r\n') for sc in server_cookies: headers.append(('Set-Cookie', sc)) else: cookie_visit = SimpleCookie('visit=1') cookie_visit['visit']['httponly'] = True headers.append(('Set-Cookie', cookie_visit.output(header=''))) headers.append(('Set-Cookie', 'hoge=fuga')) start_response('200 OK', headers) return ["Hello, No.{}".format(visit_in_html).encode('utf-8')]
def cookie(environ, start_response): visit_in_html = 1 headers = [('Content-Type', 'text/plain'),] # 今回、"visit"というCookieは一つしかない前提、実際には複数設定されることもある # http://www.yunabe.jp/docs/cookie_and_security.html#cookie- if app.cookie: if 'visit' in app.cookie: app.cookie['visit'] = visit_in_html = int(app.cookie['visit'].value) + 1 else: app.cookie['visit'] = 1 # RFC6265より、UAからはCookieの属性は送信されないため、サーバ側で毎回属性をセットする # https://triple-underscore.github.io/RFC6265-ja.html#section-4.2.2 app.cookie['visit']['httponly'] = True # 複数のCookieへのサーバ側での対応 # RFC6265より、複数のCookieがある場合、その分Set-Cookie応答ヘッダを用意する必要がある # https://triple-underscore.github.io/RFC6265-ja.html#section-4.1.1 # そこで、複数のCookieがあるapp.cookie(SimpleCookieオブジェクト)の値を、output(header='')で確認すると、 # http://docs.python.jp/3/library/http.cookies.html#http.cookies.BaseCookie.output print('-'*10) print('app_cookie:\n{}\n'.format(app.cookie.output(header=''))) print('-'*10) # """ # ---------- # app_cookie: # hoge=fuga # visit=2; HttpOnly # # ---------- # """ # と、「CRLF + 半角スペース」で連結された状態で取得できる # 今回、HTTPレスポンスヘッダは # "headers.append(('Set-Cookie', '<Cookie名>=<Cookie値>'))" # のようにして作ることから、以下のような処理となる server_cookies = app.cookie.output(header='').split('\r\n') for sc in server_cookies: headers.append(('Set-Cookie', sc)) else: cookie_visit = SimpleCookie('visit=1') cookie_visit['visit']['httponly'] = True headers.append(('Set-Cookie', cookie_visit.output(header=''))) headers.append(('Set-Cookie', 'hoge=fuga')) start_response('200 OK', headers) return ["Hello, No.{}".format(visit_in_html).encode('utf-8')]
def login(_request, username='', password=''): res = Response() values, errors = loginform.validate({'username': username, 'password': password}) if errors or fixeduser != username or fixedpass != password: return login_form(_request, values, errors) c = SimpleCookie() m = hashlib.md5((username+':'+password).encode('utf-8')) c['authhash'] = m.hexdigest() c['authhash']['expires'] = 'Thu, 1-Jan-2030 00:00:00 GMT' res.set_header(*c.output().split(': ')) res.status = 302 res.set_header('Location', '/') res.set_body('') return res
def http_error_302(self, request, fp, code, message, headers): cookie = SimpleCookie() request_cookie = request.headers.get('Cookie') if request_cookie: cookie.load(request_cookie) set_cookie = headers.get('set-cookie') if set_cookie: for value in set_cookie: cookie.load(value) headers['Cookie'] = cookie.output(header='', sep='; ') redirect_handler = HTTPRedirectHandler.http_error_302(self, request, fp, code, message, headers) return inesHTTPError(request, redirect_handler, code, message, headers)
def set_cookie(self, key, value, path="/", **params): """domain=None, path='/', expires=None, max_age=None, secure=None, httponly=None, comment=None, version=None """ expires = params.get("expires") if expires: params["expires"] = utc_time(expires) max_age = params.get("max_age") if max_age and isinstance(max_age, datetime.timedelta): params["max_age"] = timedelta_to_seconds(max_age) cookie = SimpleCookie({key: value}) cookie[key]["path"] = path for option, v in params.items(): cookie[key][option.replace("_", "-")] = v self.headers.parse_header_line(cookie.output())
def update_cookies(self, cookies): """Update request cookies header.""" if not cookies: return c = SimpleCookie() if hdrs.COOKIE in self.headers: c.load(self.headers.get(hdrs.COOKIE, '')) del self.headers[hdrs.COOKIE] for name, value in cookies.items(): if isinstance(value, Morsel): # Preserve coded_value mrsl_val = value.get(value.key, Morsel()) mrsl_val.set(value.key, value.value, value.coded_value) c[name] = mrsl_val else: c[name] = value self.headers[hdrs.COOKIE] = c.output(header='', sep=';').strip()
def _cookie_value(key, value): m = SimpleCookie() m[key] = value return m.output(header='')
def _complete_authz(self, user, areq, sid, **kwargs): _log_debug = logger.debug _log_debug("- in authenticated() -") # Do the authorization try: permission = self.authz(user, client_id=areq['client_id']) self.sdb.update(sid, "permission", permission) except Exception: raise _log_debug("response type: %s" % areq["response_type"]) if self.sdb.is_revoked(sid): return error_response("access_denied", descr="Token is revoked") try: info = self.create_authn_response(areq, sid) except UnSupported as err: return error_response(*err.args) if isinstance(info, Response): return info else: aresp, fragment_enc = info try: redirect_uri = self.get_redirect_uri(areq) except (RedirectURIError, ParameterError) as err: return BadRequest("%s" % err) # Must not use HTTP unless implicit grant type and native application info = self.aresp_check(aresp, areq) if isinstance(info, Response): return info headers = [] try: _kaka = kwargs["cookie"] except KeyError: pass else: if _kaka: if isinstance(_kaka, dict): for name, val in _kaka.items(): _c = SimpleCookie() _c[name] = val _x = _c.output() if PY2: _x = str(_x) headers.append(tuple(_x.split(": ", 1))) else: _c = SimpleCookie() _c.load(_kaka) for x in _c.output().split('\r\n'): if PY2: x = str(x) headers.append(tuple(x.split(": ", 1))) if self.cookie_name not in _kaka: # Don't overwrite header = self.cookie_func(user, typ="sso", ttl=self.sso_ttl) if header: headers.append(header) else: header = self.cookie_func(user, typ="sso", ttl=self.sso_ttl) if header: headers.append(header) # Now about the response_mode. Should not be set if it's obvious # from the response_type. Knows about 'query', 'fragment' and # 'form_post'. if "response_mode" in areq: try: resp = self.response_mode(areq, fragment_enc, aresp=aresp, redirect_uri=redirect_uri, headers=headers) except InvalidRequest as err: return error_response("invalid_request", str(err)) else: if resp is not None: return resp return aresp, headers, redirect_uri, fragment_enc
class HttpSession: def hack_httplib2_response(): original_init = httplib2.Response.__init__ info_key = HTTPLIB2_ORG_RESPONSE_KEY def hacked_init(self, info): self[info_key] = info original_init(self, info) httplib2.Response.__init__ = hacked_init hack_httplib2_response() def __init__( self, host, initial_cookies=None, default_encoding="utf-8", disable_ssl_certificate_validation=False): self.http = httplib2.Http(disable_ssl_certificate_validation=disable_ssl_certificate_validation) self.host = host self.url_template_parts = urlparse(host) self.cookies = SimpleCookie() self.default_headers = {} if initial_cookies: self.cookies.load(initial_cookies) self.default_encoding = default_encoding self.debug = False def make_url(self, path): parts = urlparse(path) new_parts = [] for name in ParseResult._fields: input_value = getattr(parts, name) template_value = getattr(self.url_template_parts, name) if input_value: new_parts.append(input_value) else: new_parts.append(template_value) return urlunparse(new_parts) def debug_print(self, *args, **kwargs): if self.debug: print(*args, **kwargs) def request( self, path, method, body=None, query={}, headers={}, encoding=None, data_type="text", update_cookies=True): self.debug_print("*** request start ***") self.debug_print("method:", method) url = self.make_url(path) self.debug_print("url:", url) if isinstance(body, dict): body = urlencode(body) new_headers = dict(self.default_headers) new_headers.update(headers) headers = new_headers self.debug_print("headers:", headers) if body: has_content_type = False for key in headers.keys(): if key.lower() == "content-type": has_content_type = True break if not has_content_type: headers["Content-Type"] = "application/x-www-form-urlencoded" self.debug_print("body:", body) if query: sep = "?" in url and "&" or "?" if isinstance(query, dict): query = urlencode(query) url = url + sep + query self.debug_print("query:", query) cookie_content = self.cookies.output(attrs=[], header='', sep=';') cookie_content = cookie_content.strip() if cookie_content: headers["Cookie"] = cookie_content self.debug_print("cookie:", cookie_content) resp, content = self.http.request( url, method, headers=headers, body=body) self.debug_print("") self.debug_print("response:", content) content_type = "text/plain" resp_headers = resp[HTTPLIB2_ORG_RESPONSE_KEY].getheaders() for k, v in resp_headers: lowered_k = k.lower() if lowered_k == "set-cookie" and update_cookies: self.cookies.load(v) if lowered_k == "content-type": content_type = v return handle_data( content, data_type=data_type, mime=content_type, encoding=encoding or self.default_encoding) def get(self, path, query=None, **kwargs): return self.request(path, method="GET", query=query, **kwargs) def post(self, path, body, **kwargs): return self.request(path, body=body, method="POST", **kwargs) def post_multipart(self, path, body, headers={}, **kwargs): encoded_body, content_type = encode_multipart_formdata(body) new_headers = dict(headers) new_headers["Content-Type"] = content_type return self.post(path, encoded_body, headers=new_headers, **kwargs)
def make_cookie(name, load, seed, expire=0, domain="", path="", timestamp="", enc_key=None): """ Create and return a cookie The cookie is secured against tampering. If you only provide a `seed`, a HMAC gets added to the cookies value and this is checked, when the cookie is parsed again. If you provide both `seed` and `enc_key`, the cookie gets protected by using AEAD encryption. This provides both a MAC over the whole cookie and encrypts the `load` in a single step. The `seed` and `enc_key` parameters should be byte strings of at least 16 bytes length each. Those are used as cryptographic keys. :param name: Cookie name :type name: text :param load: Cookie load :type load: text :param seed: A seed key for the HMAC function :type seed: byte string :param expire: Number of minutes before this cookie goes stale :type expire: int :param domain: The domain of the cookie :param path: The path specification for the cookie :param timestamp: A time stamp :type timestamp: text :param enc_key: The key to use for cookie encryption. :type enc_key: byte string :return: A tuple to be added to headers """ cookie = SimpleCookie() if not timestamp: timestamp = str(int(time.time())) bytes_load = load.encode("utf-8") bytes_timestamp = timestamp.encode("utf-8") if enc_key: # Make sure the key is 256-bit long, for AES-128-SIV # # This should go away once we push the keysize requirements up # to the top level APIs. key = _make_hashed_key((enc_key, seed)) # Random 128-Bit IV iv = os.urandom(16) crypt = AEAD(key, iv) # timestamp does not need to be encrypted, just MAC'ed, # so we add it to 'Associated Data' only. crypt.add_associated_data(bytes_timestamp) ciphertext, tag = crypt.encrypt_and_tag(bytes_load) cookie_payload = [bytes_timestamp, base64.b64encode(iv), base64.b64encode(ciphertext), base64.b64encode(tag)] else: cookie_payload = [ bytes_load, bytes_timestamp, cookie_signature(seed, load, timestamp).encode('utf-8')] cookie[name] = (b"|".join(cookie_payload)).decode('utf-8') 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 Response(object): """An HTTP Response, including status, headers, and body.""" status = '' """The HTTP Status-Code and Reason-Phrase.""" header_list = [] """ A list of the HTTP response headers as (name, value) tuples. In general, you should use response.headers (a dict) instead. This attribute is generated from response.headers and is not valid until after the finalize phase.""" headers = httputil.HeaderMap() """ A dict-like object containing the response headers. Keys are header names (in Title-Case format); however, you may get and set them in a case-insensitive manner. That is, headers['Content-Type'] and headers['content-type'] refer to the same value. Values are header values (decoded according to :rfc:`2047` if necessary). .. seealso:: classes :class:`HeaderMap`, :class:`HeaderElement` """ cookie = SimpleCookie() """See help(Cookie).""" body = ResponseBody() """The body (entity) of the HTTP response.""" time = None """The value of time.time() when created. Use in HTTP dates.""" stream = False """If False, buffer the response body.""" def __init__(self): self.status = None self.header_list = None self._body = [] self.time = time.time() self.headers = httputil.HeaderMap() # Since we know all our keys are titled strings, we can # bypass HeaderMap.update and get a big speed boost. dict.update(self.headers, { 'Content-Type': 'text/html', 'Server': 'CherryPy/' + cherrypy.__version__, 'Date': httputil.HTTPDate(self.time), }) self.cookie = SimpleCookie() def collapse_body(self): """Collapse self.body to a single string; replace it and return it.""" new_body = b''.join(self.body) self.body = new_body return new_body def _flush_body(self): """ Discard self.body but consume any generator such that any finalization can occur, such as is required by caching.tee_output(). """ consume(iter(self.body)) def finalize(self): """Transform headers (and cookies) into self.header_list. (Core)""" try: code, reason, _ = httputil.valid_status(self.status) except ValueError: raise cherrypy.HTTPError(500, sys.exc_info()[1].args[0]) headers = self.headers self.status = '%s %s' % (code, reason) self.output_status = ntob(str(code), 'ascii') + \ b' ' + headers.encode(reason) if self.stream: # The upshot: wsgiserver will chunk the response if # you pop Content-Length (or set it explicitly to None). # Note that lib.static sets C-L to the file's st_size. if dict.get(headers, 'Content-Length') is None: dict.pop(headers, 'Content-Length', None) elif code < 200 or code in (204, 205, 304): # "All 1xx (informational), 204 (no content), # and 304 (not modified) responses MUST NOT # include a message-body." dict.pop(headers, 'Content-Length', None) self._flush_body() self.body = b'' else: # Responses which are not streamed should have a Content-Length, # but allow user code to set Content-Length if desired. if dict.get(headers, 'Content-Length') is None: content = self.collapse_body() dict.__setitem__(headers, 'Content-Length', len(content)) # Transform our header dict into a list of tuples. self.header_list = h = headers.output() cookie = self.cookie.output() if cookie: for line in cookie.split('\r\n'): name, value = line.split(': ', 1) if isinstance(name, str): name = name.encode('ISO-8859-1') if isinstance(value, str): value = headers.encode(value) h.append((name, value))
def send(self, anyway=False, prefetch=False): """Sends the request. Returns True of successful, false if not. If there was an HTTPError during transmission, self.response.status_code will contain the HTTPError code. Once a request is successfully sent, `sent` will equal True. :param anyway: If True, request will be sent, even if it has already been sent. """ # Logging if self.config.get('verbose'): self.config.get('verbose').write('%s %s %s\n' % ( datetime.now().isoformat(), self.method, self.url )) # Build the URL url = self.full_url # Nottin' on you. body = None content_type = None # Multi-part file uploads. if self.files: if not isinstance(self.data, str): try: fields = self.data.copy() except AttributeError: fields = dict(self.data) for (k, v) in list(self.files.items()): fields.update({k: (guess_filename(k) or k, v.read())}) (body, content_type) = encode_multipart_formdata(fields) else: pass # TODO: Conflict? else: if self.data: body = self._enc_data if isinstance(self.data, str): content_type = None else: content_type = 'application/x-www-form-urlencoded' # Add content-type if it wasn't explicitly provided. if (content_type) and (not 'content-type' in self.headers): self.headers['Content-Type'] = content_type if self.auth: auth_func, auth_args = self.auth # Allow auth to make its changes. r = auth_func(self, *auth_args) # Update self to reflect the auth changes. self.__dict__.update(r.__dict__) _p = urlparse(url) proxy = self.proxies.get(_p.scheme) if proxy: conn = poolmanager.proxy_from_url(proxy) else: # Check to see if keep_alive is allowed. if self.config.get('keep_alive'): conn = self._poolmanager.connection_from_url(url) else: conn = connectionpool.connection_from_url(url) if not self.sent or anyway: if self.cookies: # Skip if 'cookie' header is explicitly set. if 'cookie' not in self.headers: # Simple cookie with our dict. c = SimpleCookie() for (k, v) in list(self.cookies.items()): c[k] = v # Turn it into a header. cookie_header = c.output(header='').strip() # Attach Cookie header to request. self.headers['Cookie'] = cookie_header try: # Send the request. r = conn.urlopen( method=self.method, url=self.path_url, body=body, headers=self.headers, redirect=False, assert_same_host=False, preload_content=prefetch, decode_content=False, retries=self.config.get('max_retries', 0), timeout=self.timeout, ) except MaxRetryError as e: if not self.config.get('safe_mode', False): raise ConnectionError(e) else: r = None except (_SSLError, _HTTPError) as e: if not self.config.get('safe_mode', False): raise Timeout('Request timed out.') self._build_response(r) # Response manipulation hook. self.response = dispatch_hook('response', self.hooks, self.response) # Post-request hook. r = dispatch_hook('post_request', self.hooks, self) self.__dict__.update(r.__dict__) # If prefetch is True, mark content as consumed. if prefetch: self.response._content_consumed = True return self.sent