aboutsummaryrefslogtreecommitdiff
path: root/src/guff/models
diff options
context:
space:
mode:
Diffstat (limited to 'src/guff/models')
-rw-r--r--src/guff/models/session.cr93
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