AshCookieConsent.Cookie (AshCookieConsent v0.1.0)

View Source

Cookie management for consent data.

Handles encoding, decoding, setting, and retrieving consent cookies.

Consent is stored as a JSON-encoded map with the following structure:

%{
  "terms" => "v1.0",
  "groups" => ["essential", "analytics"],
  "consented_at" => "2025-11-03T12:00:00Z",
  "expires_at" => "2026-11-03T12:00:00Z"
}

Security

  • Cookies are signed by Plug to prevent tampering
  • HttpOnly is false (JavaScript may need to read)
  • Secure flag enabled in production
  • SameSite: Lax for CSRF protection

Examples

# Set consent cookie
conn = AshCookieConsent.Cookie.put_consent(conn, consent)

# Get consent cookie
consent = AshCookieConsent.Cookie.get_consent(conn)

# Delete consent cookie
conn = AshCookieConsent.Cookie.delete_consent(conn)

Summary

Functions

Decodes consent data from JSON string.

Deletes the consent cookie from the connection.

Encodes consent data to JSON string.

Gets the consent data from the cookie.

Checks if consent cookie exists and is valid.

Sets the consent cookie on the connection.

Functions

decode_consent(json_string)

Decodes consent data from JSON string.

Examples

iex> json = ~s({"terms":"v1.0","groups":["essential"]})
iex> AshCookieConsent.Cookie.decode_consent(json)
{:ok, %{"terms" => "v1.0", "groups" => ["essential"]}}

iex> AshCookieConsent.Cookie.decode_consent("invalid json")
{:error, _}

delete_consent(conn, opts \\ [])

Deletes the consent cookie from the connection.

Examples

conn = AshCookieConsent.Cookie.delete_consent(conn)

encode_consent(consent)

Encodes consent data to JSON string.

Examples

iex> consent = %{terms: "v1.0", groups: ["essential"]}
iex> AshCookieConsent.Cookie.encode_consent(consent)
{:ok, ~s({"groups":["essential"],"terms":"v1.0"})}

iex> AshCookieConsent.Cookie.encode_consent(nil)
{:error, :invalid_consent}

get_consent(conn, opts \\ [])

Gets the consent data from the cookie.

Returns the decoded consent map or nil if cookie doesn't exist or is invalid.

Examples

consent = AshCookieConsent.Cookie.get_consent(conn)
# => %{"terms" => "v1.0", "groups" => ["essential", "analytics"], ...}

has_consent?(conn, opts \\ [])

Checks if consent cookie exists and is valid.

Examples

if AshCookieConsent.Cookie.has_consent?(conn) do
  # Consent cookie exists
end

put_consent(conn, consent, opts \\ [])

Sets the consent cookie on the connection.

Options

  • :cookie_name - Name of the cookie (default: "_consent")
  • :max_age - Cookie lifetime in seconds (default: 1 year)
  • :secure - Require HTTPS (default: false in dev, true in prod)
  • :http_only - Prevent JavaScript access (default: false)
  • :same_site - CSRF protection (default: "Lax")

Examples

conn = AshCookieConsent.Cookie.put_consent(conn, consent)

conn = AshCookieConsent.Cookie.put_consent(conn, consent,
  cookie_name: "my_consent",
  max_age: 30 * 24 * 60 * 60  # 30 days
)