diff --git a/lib/livebook_web/controllers/auth_controller.ex b/lib/livebook_web/controllers/auth_controller.ex index 38c9bc9b42e..c213cb9c2e9 100644 --- a/lib/livebook_web/controllers/auth_controller.ex +++ b/lib/livebook_web/controllers/auth_controller.ex @@ -1,12 +1,14 @@ defmodule LivebookWeb.AuthController do use LivebookWeb, :controller - plug :require_unauthenticated_password + plug :require_unauthenticated alias LivebookWeb.AuthPlug - defp require_unauthenticated_password(conn, _opts) do - if Livebook.Config.auth_mode() != :password or AuthPlug.authenticated?(conn, :password) do + defp require_unauthenticated(conn, _opts) do + auth_mode = Livebook.Config.auth_mode() + + if auth_mode not in [:password, :token] or AuthPlug.authenticated?(conn, auth_mode) do redirect_home(conn) else conn @@ -14,7 +16,7 @@ defmodule LivebookWeb.AuthController do end def index(conn, _params) do - render(conn, "index.html") + render(conn, "index.html", auth_mode: Livebook.Config.auth_mode()) end def authenticate(conn, %{"password" => password}) do @@ -27,6 +29,16 @@ defmodule LivebookWeb.AuthController do end end + def authenticate(conn, %{"token" => token}) do + conn = AuthPlug.store(conn, :token, token) + + if AuthPlug.authenticated?(conn, :token) do + redirect_home(conn) + else + index(conn, %{}) + end + end + defp redirect_home(conn) do conn |> redirect(to: "/") diff --git a/lib/livebook_web/plugs/auth_plug.ex b/lib/livebook_web/plugs/auth_plug.ex index 55a662724f2..6536cf7ab2a 100644 --- a/lib/livebook_web/plugs/auth_plug.ex +++ b/lib/livebook_web/plugs/auth_plug.ex @@ -1,7 +1,3 @@ -defmodule LivebookWeb.InvalidTokenError do - defexception plug_status: 401, message: "invalid token" -end - defmodule LivebookWeb.AuthPlug do @moduledoc false @@ -55,9 +51,7 @@ defmodule LivebookWeb.AuthPlug do end defp authenticate(conn, :password) do - conn - |> redirect(to: "/authenticate") - |> halt() + redirect_to_authenticate(conn) end defp authenticate(conn, :token) do @@ -70,10 +64,16 @@ defmodule LivebookWeb.AuthPlug do |> redirect(to: path_with_query(conn.request_path, query_params)) |> halt() else - raise LivebookWeb.InvalidTokenError + redirect_to_authenticate(conn) end end + defp redirect_to_authenticate(conn) do + conn + |> redirect(to: "/authenticate") + |> halt() + end + defp path_with_query(path, params) when params == %{}, do: path defp path_with_query(path, params), do: path <> "?" <> URI.encode_query(params) diff --git a/lib/livebook_web/templates/auth/index.html.eex b/lib/livebook_web/templates/auth/index.html.eex index 739790615cc..f9e003ade1e 100644 --- a/lib/livebook_web/templates/auth/index.html.eex +++ b/lib/livebook_web/templates/auth/index.html.eex @@ -8,12 +8,21 @@