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