livebook/lib/livebook_web/controllers/auth_controller.ex

48 lines
1 KiB
Elixir
Raw Normal View History

2021-04-15 20:15:56 +08:00
defmodule LivebookWeb.AuthController do
use LivebookWeb, :controller
plug :require_unauthenticated
2021-04-15 20:15:56 +08:00
alias LivebookWeb.AuthPlug
2021-04-15 20:15:56 +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
redirect_home(conn)
else
conn
end
2021-04-15 20:15:56 +08:00
end
def index(conn, _params) do
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
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
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
2021-04-15 20:15:56 +08:00
conn
|> redirect(to: "/")
|> halt()
2021-04-15 20:15:56 +08:00
end
end