Hello, I’m using Guardian for authentication on Phoenix app, the login persist when I log in as a normal user but I’m setting a flag to know if someone is an admin and if they are then I put the key: admin
on their session but for some reason Guardian.Plug.resource
returns nil
I can access an endpoint which is meant only to be accessed by admins but the resource, the current user and Guardian.authenticated?
returns nil or false and thus I can’t see links and stuff meant to for logged users.
Serializer:
defmodule Euridime.GuardianSerializer do
@moduledoc false
@behaviour Guardian.Serializer
alias Euridime.{Repo, User.Admin}
def for_token(%Admin{} = user), do: {:ok, "User:#{user.id}"}
def for_token(_), do: {:error, "Unknown resource type"}
def from_token("User:" <> id), do: {:ok, Repo.get(Admin, String.to_integer(id))}
def from_token(_), do: {:error, "Unknown resource type"}
end
This is what I’m using to login the admin:
conn
|> put_flash(:info, "Welcome, #{username}")
|> Guardian.Plug.sign_in(user, :token, key: :admin) # Tried changing :token to :access
|> redirect(to: admin_path(conn, :index))
And the helper on the views:
defmodule Euridime.ViewHelper do
@moduledoc false
alias Euridime.User
def current_user(conn) do
Guardian.Plug.current_resource(conn) ||
Guardian.Plug.current_resource(conn, :admin)
# Also tried Guardian.Plug.current_resource(conn || conn, :admin)
end
end