You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
link_shortener/lib/link_shortener_web/auth/guardian.ex

56 lines
1.5 KiB

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