diff --git a/spec/session_spec.cr b/spec/session_spec.cr index 88cf1f1..b097039 100644 --- a/spec/session_spec.cr +++ b/spec/session_spec.cr @@ -7,6 +7,7 @@ describe "Session" do get "/" do |env| sess = env.session existing = sess["token"]? + sess.delete("token") sid = sess.id sess["token"] = "abc" "Hello" diff --git a/src/kemal/session.cr b/src/kemal/session.cr index 1e0e9e2..9b1685f 100644 --- a/src/kemal/session.cr +++ b/src/kemal/session.cr @@ -3,6 +3,17 @@ require "secure_random" module Kemal # Kemal's default session is in-memory only and holds simple String values only. # The client-side cookie stores a random ID. + # + # Kemal handlers can access the session like so: + # + # get("/") do |env| + # env.session["abc"] = "xyz" + # uid = env.session["user_id"]? + # end + # + # Note that only String values are allowed. + # + # Sessions are pruned hourly after 48 hours of inactivity. class Sessions NAME = "SessionId" @@ -44,6 +55,11 @@ module Kemal @last_access_at = Time.now.epoch_ms @store[key] = value end + + def delete(key : String) + @last_access_at = Time.now.epoch_ms + @store.delete(key) + end end getter! id : String @@ -76,6 +92,10 @@ module Kemal STORE[@id]?.try &.[key]? end + def delete(key : String) + STORE[@id]?.try &.delete(key) + end + def self.prune!(before = (Time.now - Kemal::Sessions::TTL).epoch_ms) Kemal::Sessions::STORE.delete_if { |id, entry| entry.last_access_at < before } nil