generate session cookie

This commit is contained in:
Jakob Ketterl 2020-02-23 21:39:12 +01:00
parent a70c51193b
commit fb7422e5a8
2 changed files with 38 additions and 3 deletions

View File

@ -20,8 +20,10 @@ class Controller(object):
content = content.encode() content = content.encode()
self.handler.wfile.write(content) self.handler.wfile.write(content)
def send_redirect(self, location, code=303, cookies=[]): def send_redirect(self, location, code=303, cookies=None):
self.handler.send_response(code) self.handler.send_response(code)
if cookies is not None:
self.handler.send_header("Set-Cookie", cookies.output(header=''))
self.handler.send_header("Location", location) self.handler.send_header("Location", location)
self.handler.end_headers() self.handler.end_headers()

View File

@ -1,10 +1,41 @@
from .template import WebpageController from .template import WebpageController
from urllib.parse import parse_qs from urllib.parse import parse_qs
from uuid import uuid4
from http.cookies import SimpleCookie
import logging import logging
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class SessionStorage(object):
sharedInstance = None
@staticmethod
def getSharedInstance():
if SessionStorage.sharedInstance is None:
SessionStorage.sharedInstance = SessionStorage()
return SessionStorage.sharedInstance
def __init__(self):
self.sessions = {}
def generateKey(self):
return str(uuid4())
def startSession(self, data):
key = self.generateKey()
self.updateSession(key, data)
return key
def getSession(self, key):
if key not in self.sessions:
return None
return self.sessions[key]
def updateSession(self, key, data):
self.sessions[key] = data
class SessionController(WebpageController): class SessionController(WebpageController):
def loginAction(self): def loginAction(self):
self.serve_template("login.html", **self.template_variables()) self.serve_template("login.html", **self.template_variables())
@ -17,8 +48,10 @@ class SessionController(WebpageController):
# TODO actually check user and password # TODO actually check user and password
if data["user"] == "admin" and data["password"] == "password": if data["user"] == "admin" and data["password"] == "password":
# TODO pass the final destination # TODO pass the final destination
# TODO actual session cookie key = SessionStorage.getSharedInstance().startSession({"user": data["user"]})
self.send_redirect("/settings", cookies=["session-cookie"]) cookie = SimpleCookie()
cookie["session"] = key
self.send_redirect("/settings", cookies=cookie)
else: else:
self.send_redirect("/login") self.send_redirect("/login")
else: else: