class HTTPSession::Manager(T)

Defined in:

manager.cr

Constructors

Class Method Summary

Instance Method Summary

Constructor Detail

def self.new(storage : Storage(T), cookie_prototype : HTTP::Cookie = HTTP::Cookie.new("session_id", "", secure: true, http_only: true, samesite: :strict)) #

Creates a new session handler.

cookie_prototype configures the basic properties of the cookie used for communicating the session id to the client. It uses a secure configuration by default. This configuration can be even more restricted (for example via Domain and Path properties) depending on use case. Lifting the default restrictions is not recommended. Cookies are not persistent by default, thus they are expected to disappear at the end of a browser session. Add Max-Age or Expires header for persistent cookies.


[View source]

Class Method Detail

def self.new_session_id(session_id_length : Int32 = 16, & : String -> Bool) #

Generates a new session_id.

Potential values are passed to the block which is supposed to return true when the session_id is good and unused.


[View source]
def self.random : Random #

Random source for generating session IDs.

This should be a cryptographically secure pseudorandom number generator (CSPRNG).


[View source]
def self.random=(random : Random) #

Random source for generating session IDs.

This should be a cryptographically secure pseudorandom number generator (CSPRNG).


[View source]

Instance Method Detail

def cookie_name #

Returns the name of the cookie used to communicate the session id to the client.

This value is configurable through #cookie_prototype.


[View source]
def cookie_prototype : HTTP::Cookie #

Configures the basic properties of the cookie used for communicating the session id to the client.


[View source]
def delete(context : HTTP::Server::Context) #

Terminates the session associated with the context.

Removes the session cookie and deletes the session from storage.


[View source]
def get(context : HTTP::Server::Context) : T | Nil #

[View source]
def set(context : HTTP::Server::Context, session : T) : Nil #

Sets the session for context to session.


[View source]
def set(context : HTTP::Server::Context, session : T, & : String -> _) : Nil #

Sets the session for context to session. Yields if context has a session_id that doesn't exist in the backend. This can be useful for detecting malicious behaviour or entirely rejecting requests with a bad session_id.

manager.set(context, user_session) do |bad_session_id|
  Log.warn &.emit("Bad session_id used", bad_session_id: bad_session_id)
end

[View source]
def storage : StorageInterface(T) #

Returns the storage engine.


[View source]