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
|
2021-04-15 21:50:29 +08:00
|
|
|
redirect_home(conn)
|
|
|
|
else
|
|
|
|
conn
|
|
|
|
end
|
2021-04-15 20:15:56 +08:00
|
|
|
end
|
|
|
|
|
2021-04-15 21:50:29 +08:00
|
|
|
def index(conn, _params) do
|
2022-04-14 00:51:28 +08:00
|
|
|
render(conn, "index.html", auth_mode: Livebook.Config.auth_mode())
|
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
|
|
|
|
redirect_home(conn)
|
|
|
|
else
|
|
|
|
index(conn, %{})
|
|
|
|
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
|
|
|
|
redirect_home(conn)
|
|
|
|
else
|
|
|
|
index(conn, %{})
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2021-04-15 21:50:29 +08:00
|
|
|
defp redirect_home(conn) do
|
2021-04-15 20:15:56 +08:00
|
|
|
conn
|
|
|
|
|> redirect(to: "/")
|
2021-04-15 21:50:29 +08:00
|
|
|
|> halt()
|
2021-04-15 20:15:56 +08:00
|
|
|
end
|
|
|
|
end
|