diff options
author | Paul Duncan <pabs@pablotron.org> | 2016-05-23 00:49:12 -0400 |
---|---|---|
committer | Paul Duncan <pabs@pablotron.org> | 2016-05-23 00:49:12 -0400 |
commit | db967939789333cf7d992900923723160e2d2b2f (patch) | |
tree | c7e1d9fe7f2ed62c03493765ab587f0197fb028a /src | |
parent | 6e69acdadc8ab1473678f0cc5d2203de7905e091 (diff) | |
download | guff-db967939789333cf7d992900923723160e2d2b2f.tar.bz2 guff-db967939789333cf7d992900923723160e2d2b2f.zip |
save sessions to database
Diffstat (limited to 'src')
-rw-r--r-- | src/guff.cr | 68 |
1 files 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 |