1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
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
|