espresso/session

Module that handles interacting with a session cookie.

The session cookie is a signed erlang term that is base64 encoded. Signatures are performed with gleam/crypto and the secret is read from the environment variable ESPRESSO_SIGNING_SECRET.

Example

pub type Session {
  Session(username: String)
}
pub fn main() {
  let router =
    router.new()
    |> get(
      "/",
      fn(req: Request(BitString, assigns, Session)) {
        case req.session {
          Ok(Session(username)) -> send(202, "Welcome back " <> username)
          _ -> send(202, "You don't have a session")
        }
      },
    )
    |> get(
      "/login",
      fn(_req: Request(BitString, assigns, Session)) {
        202
        |> send("Logged in")
        |> session.set(Session("your_username_here"))
      },
    )
    |> get(
      "/logout",
      fn(_req: Request(BitString, assigns, Session)) {
        "/"
        |> redirect()
        |> session.clear()
      },
    )
  start(router)
}

Types

pub type Session(session) =
  Result(session, SessionState)
pub type SessionState {
  EncodeError(String)
  InvalidSignature
  InvalidSecret
  Unset
}

Constructors

  • EncodeError(String)
  • InvalidSignature
  • InvalidSecret
  • Unset

Functions

pub fn clear(res: Response(a)) -> Response(a)

Clears out the session cookie on the response. Subsequent requests will have a session of Error(Unset)

pub fn decode(session: String) -> Result(a, SessionState)
pub fn encode(session: Result(a, SessionState)) -> Result(
  String,
  SessionState,
)
pub fn session_key() -> String
pub fn set(res: Response(a), session: b) -> Response(a)

Sets the session cookie on the response based on the session state.

Search Document