defmodule BerrypodWeb.UnsubscribeController do use BerrypodWeb, :controller alias Berrypod.{Newsletter, Orders} # Unsubscribe links should be long-lived — use 2 years @max_age 2 * 365 * 24 * 3600 def unsubscribe(conn, %{"token" => token}) do case Phoenix.Token.verify(BerrypodWeb.Endpoint, "email-unsub", token, max_age: @max_age) do {:ok, email} -> Orders.add_suppression(email, "unsubscribed") Newsletter.unsubscribe(email) conn |> put_status(200) |> html(""" Unsubscribed

You've been unsubscribed

We've removed #{email} from our marketing emails. You won't hear from us again.

""") {:error, _reason} -> conn |> put_status(400) |> html(""" Invalid link

Link invalid or expired

This unsubscribe link has expired or is invalid. If you'd like to unsubscribe, reply to any email we've sent you.

""") end end end