diff options
author | Paul Duncan <pabs@pablotron.org> | 2016-03-15 00:11:28 -0400 |
---|---|---|
committer | Paul Duncan <pabs@pablotron.org> | 2016-03-15 00:11:28 -0400 |
commit | 9ebc1a57335e3b183be9a0494cdc377a19219222 (patch) | |
tree | 1a38b83945320c5c19a26c7b652315e8a1897dea /src/guff/models | |
parent | cf34c28f84b9c47bdd03cf8011a5c40495c2b289 (diff) | |
download | old-guff-9ebc1a57335e3b183be9a0494cdc377a19219222.tar.bz2 old-guff-9ebc1a57335e3b183be9a0494cdc377a19219222.zip |
initial session support
Diffstat (limited to 'src/guff/models')
-rw-r--r-- | src/guff/models/session.cr | 93 |
1 files changed, 93 insertions, 0 deletions
diff --git a/src/guff/models/session.cr b/src/guff/models/session.cr new file mode 100644 index 0000000..1b88002 --- /dev/null +++ b/src/guff/models/session.cr @@ -0,0 +1,93 @@ +require "secure_random" +require "../model" + +class Guff::SessionModel < Guff::Model + SQL = TemplateCache.new({ + add: " + INSERT INTO sessions(session_id) VALUES (:session_id) + ", + + delete: " + DELETE FROM sessions WHERE session_id = :session_id + ", + + get: " + SELECT data + + FROM sessions + + WHERE session_id = :session_id + AND strftime('%s', datetime(updated_at, :age)) >= + strftime('%s', 'now') + + ", + + set: " + UPDATE sessions + + SET data = :data, + updated_at = CURRENT_TIMESTAMP + + WHERE session_id = :session_id + AND strftime('%s', datetime(updated_at, :age)) >= + strftime('%s', 'now') + + ", + + scrub: " + DELETE FROM sessions + WHERE strftime('%s', datetime(updated_at, :age)) < + strftime('%s', 'now') + ", + }) + + # maximum session age + AGE = "24 hours" + + def initialize(models : Models) + super(models, SQL) + + # TODO: make this configurable + @age = AGE + end + + def add : String + # create sid + r = SecureRandom.hex(16) + + # add session + query(:add, { + "session_id": r + }, nil) + + # return sid + r + end + + def get(session_id : String) : String? + one(:get, { + "session_id": session_id, + "age": @age, + }, nil) + end + + def set(session_id : String, data : String) + query(:set, { + "session_id": session_id, + "age": @age, + "data": data, + }, nil) + end + + def delete(session_id : String) + query(:delete, { + "session_id": sesion_id, + }, nil) + end + + private def scrub + query(:scrub, { + "age": @age, + }, nil) + end +end |