def logout(req): req.log_error("Input cookies: %s" % repr(req.cookies), state.LOG_DEBUG) cookie = PoorSession(req) cookie.destroy() cookie.header(req, req.headers_out) req.log_error("Output headers: %s" % req.headers_out, state.LOG_DEBUG) redirect(req, '/')
def login(req): # password check is missing ! cookie = PoorSession(req) cookie.data['hash'] = random_string() # cookie data are crypted with poorwsgi secret key cookie.header(req, req.headers_out) redirect(req, '/')
def test_default(self): session = PoorSession(SECRET_KEY) headers = session.header() assert "Expires" not in headers[0][1] assert "Max-Age" not in headers[0][1] assert "Path" in headers[0][1] assert "Domain" not in headers[0][1]
def test_bad_session(self): cookies = SimpleCookie() cookies["SESSID"] = "\0" session = PoorSession(SECRET_KEY) with raises(SessionError): session.load(cookies)
def login(req): req.log_error("Input cookies: %s" % repr(req.cookies), state.LOG_DEBUG) cookie = PoorSession(req) cookie.data['login'] = True cookie.header(req, req.headers_out) req.log_error("Output headers: %s" % req.headers_out, state.LOG_DEBUG) redirect(req, '/')
def login(req): log.debug("Input cookies: %s", repr(req.cookies)) cookie = PoorSession(app.secret_key) cookie.data['login'] = True response = RedirectResponse('/') cookie.header(response) return response
def req_session(): """Instace of Request object with session cookie.""" request = Request() session = PoorSession(request.secret_key) session.data['test'] = True session.write() request.cookies = session.cookie return request
def do_logout(req): cookie = PoorSession(req, compress=None) if "data" not in cookie.data: req.log_error("Login cookie not found.", state.LOG_INFO) return cookie.destroy() cookie.header(req, req.headers_out) req.log_error("Login cookie was be destroyed (Logout).", state.LOG_INFO)
def do_check_login(req): req.login = None cookie = PoorSession(req, compress=None) if "data" not in cookie.data: req.log_error("Login cookie not found.", state.LOG_INFO) return None if "ip" in cookie.data and cookie.data["ip"] != req.get_remote_host(): cookie.destroy() cookie.header(req, req.headers_out) req.log_error("Login cookie was be destroyed (invalid IP address)", state.LOG_INFO) return None __class__, __dict__ = cookie.data["data"] req.login = __class__() req.login.__dict__ = __dict__.copy() req.user_hash = cookie.data["token"] if not req.login.check(req): cookie.destroy() req.login = None req.log_error("Login cookie was be destroyed (check failed)", state.LOG_INFO) cookie.header(req, req.headers_out) # refresh cookie return req.login
def handler(req): session = PoorSession(app.secret_key) try: session.load(req.cookies) except SessionError: pass if 'login' not in session.data: log.info('Login cookie not found.') redirect( "/", message="Login required", ) return fun(req)
def handler(req): cookie = PoorSession(req) if 'login' not in cookie.data: req.log_error('Login cookie not found.', state.LOG_INFO) redirect(req, '/', text='Login required') return fn(req)
def do_login(req, obj, ip=False): cookie = PoorSession(req, compress=None) # so cookie is not so long, just less then 500 chars cookie.data["data"] = (obj.__class__, obj.__dict__) cookie.data["timestamp"] = int(time()) cookie.data["token"] = urandom(24) if ip: cookie.data["ip"] = req.get_remote_host() cookie.header(req, req.headers_out) req.log_error("Login cookie was be set.", state.LOG_INFO)
def logout(req): log.debug("Input cookies: %s", repr(req.cookies)) cookie = PoorSession(app.secret_key) cookie.destroy() response = RedirectResponse('/') cookie.header(response) return response
def do_check_mgc(req): """Check Morias Guest Cookie. Check guest cookie and set req.user_hash. If no cookie was readed, or will be bad. Create new cookie and send it to browser. Return value: Returun None, if req.login exist yet. So no guest cookie could be used. Returun True, if cookie will be readed or False if be created. """ if getattr(req, "login"): return None # req.login exist - user cookie exist cookie = PoorSession(req, SID="MGC") # Morias Guest Cookie if "token" not in cookie.data: req.log_error("Creating new cookie.", state.LOG_INFO) cookie.data["timestamp"] = int(time()) cookie.data["token"] = urandom(24) req.user_hash = cookie.data["token"] cookie.header(req, req.headers_out) return False req.user_hash = cookie.data["token"] return True
def __init__(self, req): # Morias Eshop Orders Shopping Cart self.cookie = PoorSession(req, SID='MEOSC') shopping_cart = self.cookie.data.get('shopping_cart', {}) self.items = shopping_cart.get('items', []) self.billing_address = shopping_cart.get('billing_address', {}) self.shipping_address = shopping_cart.get('shipping_address', {}) self.transportation = shopping_cart.get('transportation', None) self.payment = shopping_cart.get('payment', None) self.email = shopping_cart.get('email', '') self.emailcheck = shopping_cart.get('emailcheck', '') self.message = shopping_cart.get('message', '') if req.login: self._merge_properties(req.login.data.get('shopping_cart', {}), self.email or req.login.email) if self.cookie.data.get('stored', False): # if data is merged from cookie, store data to login # and clean the cookie self.store(req) self.cookie.destroy() self.cookie.header(req, req.headers_out)
def check_login(req): cookie = PoorSession(req) if 'login' not in cookie.data: raise HTTPException(401) return "login ok"
def login(req): cookie = PoorSession(req) cookie.data['login'] = True response = Response(status_code=204) cookie.header(response) return response
class ShoppingCart(object): def __init__(self, req): # Morias Eshop Orders Shopping Cart self.cookie = PoorSession(req, SID='MEOSC') shopping_cart = self.cookie.data.get('shopping_cart', {}) self.items = shopping_cart.get('items', []) self.billing_address = shopping_cart.get('billing_address', {}) self.shipping_address = shopping_cart.get('shipping_address', {}) self.transportation = shopping_cart.get('transportation', None) self.payment = shopping_cart.get('payment', None) self.email = shopping_cart.get('email', '') self.emailcheck = shopping_cart.get('emailcheck', '') self.message = shopping_cart.get('message', '') if req.login: self._merge_properties(req.login.data.get('shopping_cart', {}), self.email or req.login.email) if self.cookie.data.get('stored', False): # if data is merged from cookie, store data to login # and clean the cookie self.store(req) self.cookie.destroy() self.cookie.header(req, req.headers_out) # enddef def _merge_properties(self, cart, email): billing_address = cart.get('billing_address', {}) shipping_address = cart.get('shipping_address', {}) transportation = cart.get('transportation', None) payment = cart.get('payment', None) message = cart.get('message', None) self.merge_items(cart.get('items', [])) if len(billing_address): self.billing_address = billing_address if len(shipping_address): self.shipping_address = shipping_address if transportation is not None: self.transportation = transportation if payment is not None: self.payment = payment self.email = cart.get('email', email) if message is not None: self.message = message # enddef def merge_items(self, items): tmp = OrderedDict(self.items) for item_id, item in items: if item_id in tmp: tmp[item_id]['count'] += item['count'] if tmp[item_id]['count'] <= 0: tmp.pop(item_id) # remove zero less count items elif item['count'] < 0: tmp[item_id].pop('not_enough', False) else: tmp[item_id] = item # endfor self.items = tmp.items() # enddef def set_not_enought(self, ids): for item_id, item in self.items: if item_id in ids: item['not_enough'] = True else: item['not_enough'] = False # enddef def store(self, req): if req.login: req.log_error('storing user data', LOG_INFO) req.login._mod(req, ['data'], [{'shopping_cart': self.dict()}]) else: req.log_error('Sendig shopping_cart cookie....', LOG_INFO) self.cookie.data['shopping_cart'] = self.dict() self.cookie.data['stored'] = True self.cookie.header(req, req.headers_out) # enddef def dict(self): return dict((k, v) for k, v in self.__dict__.items() if k != 'cookie') def calculate(self): self.count = 0 # count of all items in cart self.summary = 0 # summary price of all items for item_id, item in self.items: item['summary'] = item['count'] * item['price'] self.count += item['count'] self.summary += item['summary'] self.total = self.summary # total price of order if self.transportation: # transportation price self.total += self.transportation[1] if self.payment: # payment price self.total += self.payment[1] # enddef def clean(self, req): if req.login: req.log_error('storing user data - cleaning shopping_cart ') req.login._mod(req, ['data'], [{'shopping_cart': {}}]) else: req.log_error('cleaning shopping_cart cookie....') self.cookie.destroy() self.cookie.header(req, req.headers_out) self.items = [] self.billing_address = {} self.shipping_address = {} self.transportation = None self.payment = None self.email = '' self.emailcheck = '' self.message = ''
def test_compatibility(self, req_session): session = PoorSession(req_session) assert session.data == {'test': True}
def test_lax(self): session = PoorSession(SECRET_KEY, same_site="Lax") headers = session.header() assert "; SameSite=Lax" in headers[0][1]
def test_bad_session_compatibility(self, req): req.cookies = SimpleCookie() req.cookies["SESSID"] = "\0" with raises(SessionError): PoorSession(req)
def test_max_age(self): session = PoorSession(SECRET_KEY, max_age=10) headers = session.header() assert "; Max-Age=10;" in headers[0][1]
def test_expires(self): session = PoorSession(SECRET_KEY, expires=10) headers = session.header() assert "; expires=" in headers[0][1]
def test_destroy(self): session = PoorSession(SECRET_KEY) session.destroy() headers = session.header() assert "; expires=" in headers[0][1]
def test_compatibility_empty(self, req): session = PoorSession(req) assert session.data == {}
def test_no_secret_key(self): with raises(SessionError): PoorSession(Empty)
def test_strict(self): session = PoorSession(SECRET_KEY, same_site="Strict") headers = session.header() assert "; SameSite=Strict" in headers[0][1]
def test_none(self): session = PoorSession(SECRET_KEY, same_site="None") headers = session.header() assert "; SameSite=None" in headers[0][1]
def test_http(self): session = PoorSession(SECRET_KEY) headers = session.header() assert "; Secure" not in headers[0][1]
def test_https(self): session = PoorSession(SECRET_KEY, secure=True) headers = session.header() assert "; Secure" in headers[0][1]
def test_no_path(self): session = PoorSession(SECRET_KEY, path=None) headers = session.header() assert "Path" not in headers[0][1]
def test_write_load(self, req_session): """Method write was called in fixture req_session.""" session = PoorSession(SECRET_KEY) session.load(req_session.cookies) assert session.data == {'test': True}
def logout(req): cookie = PoorSession(req) cookie.destroy() cookie.header(req, req.headers_out) redirect(req, '/')
def test_httponly(self): session = PoorSession(SECRET_KEY) headers = session.header() assert "; HttpOnly; " in headers[0][1]
def test_domain(self): session = PoorSession(SECRET_KEY, domain="example.org") headers = session.header() assert "; Domain=example.org; " in headers[0][1]
def test_default(self): session = PoorSession(SECRET_KEY) headers = session.header() assert "; SameSite" not in headers[0][1]