2021-04-15 20:15:56 +08:00
|
|
|
defmodule LivebookWeb.AuthController do
|
|
|
|
use LivebookWeb, :controller
|
|
|
|
|
2022-04-14 00:51:28 +08:00
|
|
|
plug :require_unauthenticated
|
2021-04-15 20:15:56 +08:00
|
|
|
|
2021-04-15 21:50:29 +08:00
|
|
|
alias LivebookWeb.AuthPlug
|
2021-04-15 20:15:56 +08:00
|
|
|
|
2022-04-14 00:51:28 +08:00
|
|
|
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
|
2022-04-15 20:24:35 +08:00
|
|
|
redirect_to(conn)
|
2021-04-15 21:50:29 +08:00
|
|
|
else
|
|
|
|
conn
|
|
|
|
end
|
2021-04-15 20:15:56 +08:00
|
|
|
end
|
|
|
|
|
2022-11-23 01:56:42 +08:00
|
|
|
def index(conn, params) do
|
|
|
|
render(conn, "index.html", auth_mode: Livebook.Config.auth_mode(), errors: params["errors"])
|
2021-04-15 20:15:56 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
def authenticate(conn, %{"password" => password}) do
|
2021-04-15 21:50:29 +08:00
|
|
|
conn = AuthPlug.store(conn, :password, password)
|
|
|
|
|
|
|
|
if AuthPlug.authenticated?(conn, :password) do
|
2022-04-15 20:24:35 +08:00
|
|
|
redirect_to(conn)
|
2021-04-15 21:50:29 +08:00
|
|
|
else
|
2022-12-12 18:52:45 +08:00
|
|
|
render_form_error(conn, :password)
|
2021-04-15 21:50:29 +08:00
|
|
|
end
|
|
|
|
end
|
2021-04-15 20:15:56 +08:00
|
|
|
|
2022-04-14 00:51:28 +08:00
|
|
|
def authenticate(conn, %{"token" => token}) do
|
|
|
|
conn = AuthPlug.store(conn, :token, token)
|
|
|
|
|
|
|
|
if AuthPlug.authenticated?(conn, :token) do
|
2022-04-15 20:24:35 +08:00
|
|
|
redirect_to(conn)
|
2022-04-14 00:51:28 +08:00
|
|
|
else
|
2022-12-12 18:52:45 +08:00
|
|
|
render_form_error(conn, :token)
|
2022-04-14 00:51:28 +08:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2022-12-12 18:52:45 +08:00
|
|
|
defp render_form_error(conn, auth_mode) do
|
|
|
|
index(conn, %{"errors" => [{"%{auth_mode} is invalid", [auth_mode: auth_mode]}]})
|
2022-11-23 01:56:42 +08:00
|
|
|
end
|
|
|
|
|
2022-04-15 20:24:35 +08:00
|
|
|
defp redirect_to(conn) do
|
2021-04-15 20:15:56 +08:00
|
|
|
conn
|
2022-04-15 20:24:35 +08:00
|
|
|
|> then(fn conn ->
|
|
|
|
if redirect_to = get_session(conn, :redirect_to) do
|
|
|
|
conn
|
|
|
|
|> delete_session(:redirect_to)
|
|
|
|
|> redirect(to: redirect_to)
|
|
|
|
else
|
|
|
|
redirect(conn, to: "/")
|
|
|
|
end
|
|
|
|
end)
|
2021-04-15 21:50:29 +08:00
|
|
|
|> halt()
|
2021-04-15 20:15:56 +08:00
|
|
|
end
|
|
|
|
end
|