Hi, I’m working on a NextJS project with Phoenix API for my backend. On my nextjs, I have a function to ping if user is currently authenticated through a protected endpoint /api/users/me
On my logout function, it calls a controller action which deletes the session but when another call for the function to ping a authenticated user, the session key is still present.
Here’s my controller functions with regards to logging in and logging out user.
def create(conn, %{"email" => email, "password" => password}) do
with {:ok, %User{} = user} <- Accounts.authenticate_user(email, password),
token <- Token.generate_token(user) do
conn
|> put_session(:token, token)
|> render("auth.json", user: user)
else
{:error, message} ->
conn
|> delete_session(:token)
|> put_status(401)
|> json(%{message: message})
end
end
def delete(conn, _params) do
conn
|> clear_session()
|> configure_session(drop: true)
|> send_resp(:no_content, "")
end
To illustrate my problem, I screenshots some of the network requests.
Initial request for /api/users/me
After logging in:
Then another request sent to /api/users/me
Log out user
Sent request to /api/users/me
, this time it should return 401 error, but was not the case
I also use two plugs, one if for store current_user to assigns, and one is for ensuring if user is authenticated
#Verify Token
def call(conn, _opts) do
token = get_session(conn, :token)
case Token.verify_token(token) do
{:ok, payload} ->
conn
|> assign(:current_user, payload)
{:error, _} ->
conn
end
end
# Ensure authenticated
def call(conn, opts) do
handler = Keyword.get(opts, :handler)
case conn.assigns[:current_user] do
nil ->
conn
|> handler.call(:unauthenticated)
|> halt()
_ ->
conn
end
end
Hope someone can figure out what causes this issue.
Thank you very much.