defmodule LinkShortenerWeb.Auth.Guardian do use Guardian, otp_app: :link_shortener alias LinkShortener.Accounts alias LinkShortener.Accounts.User def subject_for_token(user, _claims) do {:ok, to_string(user.id)} end def resource_from_claims(%{"sub" => id}) do user = Accounts.get_user!(id) {:ok, user} rescue Ecto.NoResultsError -> {:error, :resource_not_found} end def authenticate(email, password) do with user <- Accounts.get_user_by_email_and_password(email, password) do case user do %User{} -> create_token(user) nil -> {:error, :unauthorized} end end end defp create_token(user) do {:ok, token, _claims} = encode_and_sign(user) {:ok, user, token} end def after_encode_and_sign(resource, claims, token, _options) do with {:ok, _} <- Guardian.DB.after_encode_and_sign(resource, claims["typ"], claims, token) do {:ok, token} end end def on_verify(claims, token, _options) do with {:ok, _} <- Guardian.DB.on_verify(claims, token) do {:ok, claims} end end def on_refresh({old_token, old_claims}, {new_token, new_claims}, _options) do with {:ok, _, _} <- Guardian.DB.on_refresh({old_token, old_claims}, {new_token, new_claims}) do {:ok, {old_token, old_claims}, {new_token, new_claims}} end end def on_revoke(claims, token, _options) do with {:ok, _} <- Guardian.DB.on_revoke(claims, token) do {:ok, claims} end end end