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

32 lines
723 B

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
sub = to_string(user.id)
{:ok, sub}
end
def resource_from_claims(claims) do
id = claims["sub"]
resource = Accounts.get_user!(id)
{:ok, resource}
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
end