-
Notifications
You must be signed in to change notification settings - Fork 11
/
session.cr
138 lines (113 loc) · 2.75 KB
/
session.cr
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
require "json"
require "random"
require "./session/message_verifier"
require "./session/message_encryptor"
class ActionController::Session
Log = ::Log.for("action-controller.session")
# (~20 years in seconds)
NEVER = 622_080_000
# Cookies can typically store 4096 bytes.
MAX_COOKIE_SIZE = 4096
Habitat.create do
setting key : String
setting secret : String
setting max_age : Int32 = NEVER
setting secure : Bool = false
setting encrypted : Bool = true
setting path : String = "/"
setting domain : String? = nil
end
# Returns whether any key-value pair is modified.
getter? modified : Bool
def modified
@modified
end
property domain : String?
@encoder : MessageEncryptor | MessageVerifier
@store : Hash(String, String | Int64 | Float64 | Bool)
forward_missing_to @store
def initialize
@modified = false
@existing = false
@domain = settings.domain
if settings.encrypted
@encoder = MessageEncryptor.new(settings.secret)
else
@encoder = MessageVerifier.new(settings.secret)
end
@store = {} of String => String | Int64 | Float64 | Bool
end
def self.from_cookies(cookies)
session = ActionController::Session.new
begin
session.parse(cookies)
rescue error
Log.warn(exception: error) { "error parsing session" }
end
session
end
def parse(cookies)
cookie = cookies[settings.key]?
if cookie
data = @encoder.extract(cookie.value).to_s
self.merge!(Hash(String, String | Int64 | Float64 | Bool).from_json(data))
@modified = false
@existing = true
end
end
def encode(cookies)
# If there was no existing session and
return if !@existing && self.empty?
if @existing && self.empty?
data = ""
age = 0
else
data = @encoder.prepare(self.to_json)
age = settings.max_age
raise CookieSizeExceeded.new("#{data.size} > #{MAX_COOKIE_SIZE}") if data.size > MAX_COOKIE_SIZE
end
@modified = false
cookies[settings.key] = HTTP::Cookie.new(
settings.key,
data,
settings.path,
Time.utc + age.seconds,
@domain,
settings.secure,
http_only: true,
extension: "SameSite=Lax"
)
end
def []=(key, value)
if value.nil?
delete(key)
else
@store[key] = value
@modified = true
end
value
end
def clear
@modified = true if @existing
@store.clear
end
def delete(key)
@modified = true
@store.delete(key)
end
def delete(key, &block)
@modified = true
@store.delete(key, &block)
end
def delete_if(&block)
@modified = true
@store.reject(&block)
end
def reject(&block)
@modified = true
@store.reject(&block)
end
def touch
@modified = true
end
end