Guardian を使用して最初の Elixir アプリを構築しています。ユーザーがログインして認証できるという問題がありますが、次のページにリダイレクトするとconn
、ユーザー情報が保存されなくなり、Guardian.Plug.is_authenticated?
false が返されます。
session_controller.ex
....
def create(conn, %{"session" => %{"email" => email, "password" => password}}) do
case PhoenixApp.Auth.authenticate_user(email, password) do
{:ok, user} ->
conn
|> PhoenixApp.Auth.login(user)
|> put_flash(:info, "Welcome back!")
|> redirect(to: "/users")
{:error, _reason} ->
conn
|> put_flash(:error, "Invalid username or password.")
|> render("new.html")
end
end
...
router.ex
...
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_flash
plug :protect_from_forgery
plug :put_secure_browser_headers
end
scope "/", PhoenixAppWeb do
pipe_through [:browser]
get "/signup", UserController, :new
get "/login", SessionController, :new
post "/login", SessionController, :create
delete "/logout/:id", SessionController, :delete
end
scope "/", PhoenixAppWeb do
# Protected routes
pipe_through [:browser, :auth]
resources "/users", UserController, except: [:new]
get "/", PageController, :index
end
# Auth pipeline
pipeline :auth do
plug(PhoenixApp.Auth.AuthAccessPipeline)
end
...
auth.ex
...
def login(conn, user) do
conn
|> Guardian.Plug.sign_in(user)
|> assign(:current_user, user)
|> IO.inspect
|> put_user_token(user)
end
...
auth_access_pipeline.ex
defmodule PhoenixApp.Auth.AuthAccessPipeline do
@moduledoc false
use Guardian.Plug.Pipeline,
otp_app: :phoenix_app,
error_handler: PhoenixApp.Auth.AuthErrorHandler
plug(Guardian.Plug.Pipeline,
module: PhoenixApp.Guardian,
error_handler: PhoenixApp.Auth.AuthErrorHandler
)
plug(Guardian.Plug.VerifySession, claims: %{"typ" => "access"})
# plug(Guardian.Plug.EnsureAuthenticated)
# plug(Guardian.Plug.LoadResource)
end
IO.inspect(conn)
from myメソッドは、の下のキーにlogin
サインインしたばかりのユーザーの JSON 化された User 構造体を返し、トークンと共に を格納します。へのリダイレクト後を調べると、in の割り当てはあり、ありません。assigns
current_user
user_token
conn
/users
current_user
nil
user_token