From 658061968b1967de2911d4d0943b2a3d10871772 Mon Sep 17 00:00:00 2001 From: Kovid Goyal Date: Wed, 3 Jun 2015 17:00:55 +0530 Subject: [PATCH] Read cookies --- src/calibre/srv/handler.py | 23 +++++++++++++++++++++-- src/calibre/srv/routes.py | 7 ++++++- 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/src/calibre/srv/handler.py b/src/calibre/srv/handler.py index 8dd4e9f776..1d702ab1cf 100644 --- a/src/calibre/srv/handler.py +++ b/src/calibre/srv/handler.py @@ -6,6 +6,8 @@ from __future__ import (unicode_literals, division, absolute_import, __license__ = 'GPL v3' __copyright__ = '2015, Kovid Goyal ' +import binascii, os, random + from calibre.srv.routes import Router class LibraryBroker(object): @@ -18,13 +20,30 @@ class Context(object): log = None url_for = None - def __init__(self, libraries): + def __init__(self, libraries, opts): + self.opts = opts self.library_broker = LibraryBroker(libraries) + self.secret = bytes(binascii.hexlify(os.urandom(random.randint(20, 30)))) + self.key_order = random.choice(('{0}:{1}', '{1}:{0}')) + + def init_session(self, endpoint, data): + cval = data.inheaders.get('Cookie') or '' + if isinstance(cval, bytes): + cval = cval.decode('utf-8', 'replace') + data.cookies = c = {} + for x in cval.split(';'): + x = x.strip() + if x: + k, v = x.partition('=')[::2] + c[k] = v + + def finalize_session(self, endpoint, data, output): + pass class Handler(object): def __init__(self, libraries, opts): - self.router = Router(ctx=Context(libraries), url_prefix=opts.url_prefix) + self.router = Router(ctx=Context(libraries, opts), url_prefix=opts.url_prefix) self.router.ctx.url_for = self.router.url_for self.dispatch = self.router.dispatch diff --git a/src/calibre/srv/routes.py b/src/calibre/srv/routes.py index 9bd8884e08..e3a61a2052 100644 --- a/src/calibre/srv/routes.py +++ b/src/calibre/srv/routes.py @@ -132,6 +132,8 @@ class Router(object): self.routes = {} self.url_prefix = url_prefix or '' self.ctx = ctx + self.init_session = getattr(ctx, 'init_session', lambda ep, data:None) + self.finalize_session = getattr(ctx, 'finalize_session', lambda ep, data, output:None) def add(self, endpoint): key = route_key(endpoint.route) @@ -170,7 +172,10 @@ class Router(object): endpoint_, args = self.find_route(data.path) if data.method not in endpoint_.methods: raise HTTPSimpleResponse(httplib.METHOD_NOT_ALLOWED) - return endpoint_(self.ctx, data, *args) + self.init_session(endpoint_, data) + ans = endpoint_(self.ctx, data, *args) + self.finalize_session(endpoint_, data, ans) + return ans def url_for(self, route, **kwargs): return self.url_prefix + self.routes[route].url_for(**kwargs)