From db967939789333cf7d992900923723160e2d2b2f Mon Sep 17 00:00:00 2001 From: Paul Duncan Date: Mon, 23 May 2016 00:49:12 -0400 Subject: save sessions to database --- src/guff.cr | 68 +++++++++++++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 53 insertions(+), 15 deletions(-) diff --git a/src/guff.cr b/src/guff.cr index 923f8f6..5fa461e 100644 --- a/src/guff.cr +++ b/src/guff.cr @@ -478,28 +478,50 @@ module Guff end end + # TODO: handle session expiration class SessionModel < Model - def initialize(context : Context) - super(context) - @sessions = {} of String => String - end + SQL = { + load: " + SELECT data + + FROM sessions + + WHERE id = ? + -- TODO: + -- AND strftime('%s', created_at, '1 week') > strftime('%s') + -- AND strftime('%s', updated_at, '2 hours') > strftime('%s') + ", + + save: " + UPDATE sessions + + SET updated_at = CURRENT_TIMESTAMP, + data = ? + + WHERE id = ? + ", + + delete: " + DELETE FROM sessions WHERE id = ? + ", + + create: " + INSERT INTO sessions(id, data) VALUES (?, ?) + ", + } def load(id : String) : String? - @sessions[id]? + @context.dbs.ro.one(SQL[:load], [id]) end def save(id : String, data : String) - if @sessions.has_key?(id) - @sessions[id] = data - true - else - false - end + @context.dbs.rw.query(SQL[:save], [data, id]) + nil end def delete(id : String?) - @sessions.delete(id) if id - false + @context.dbs.rw.query(SQL[:delete], [id]) if id + nil end def create(data : String) : String @@ -507,7 +529,7 @@ module Guff r = SecureRandom.hex(32) # save session - @sessions[r] = data + @context.dbs.rw.query(SQL[:create], [r, data]) # return session id r @@ -656,7 +678,7 @@ module Guff def save if valid? - @context.models.session.save(@session_id, to_json) + @context.models.session.save(@session_id.not_nil!, to_json) # return success true @@ -941,6 +963,10 @@ module Guff end call_next(context) + + if @context.session.valid? + @context.session.save + end end end @@ -1618,6 +1644,18 @@ module Guff layout_id INTEGER NOT NULL REFERENCES layouts(layout_id) ) + }, %{ + CREATE TABLE sessions ( + id TEXT PRIMARY KEY, + + created_at TIMESTAMP WITH TIME ZONE NOT NULL + DEFAULT CURRENT_TIMESTAMP, + + updated_at TIMESTAMP WITH TIME ZONE NOT NULL + DEFAULT CURRENT_TIMESTAMP, + + data TEXT NOT NULL + ) }] def run -- cgit v1.2.3