2021-04-08 17:41:52 +08:00
|
|
|
defmodule LivebookWeb.InvalidTokenError do
|
|
|
|
defexception plug_status: 401, message: "invalid token"
|
|
|
|
end
|
|
|
|
|
|
|
|
defmodule LivebookWeb.AuthPlug do
|
|
|
|
@moduledoc false
|
|
|
|
|
|
|
|
@behaviour Plug
|
|
|
|
|
|
|
|
import Plug.Conn
|
|
|
|
import Phoenix.Controller
|
|
|
|
|
|
|
|
@impl true
|
|
|
|
def init(opts), do: opts
|
|
|
|
|
|
|
|
@impl true
|
2021-04-15 20:15:56 +08:00
|
|
|
def call(conn, _opts) do
|
2021-04-15 21:50:29 +08:00
|
|
|
mode = Livebook.Config.auth_mode()
|
2021-04-15 20:15:56 +08:00
|
|
|
|
2021-04-15 21:50:29 +08:00
|
|
|
if authenticated?(conn, mode) do
|
|
|
|
conn
|
|
|
|
else
|
|
|
|
authenticate(conn, mode)
|
2021-04-08 17:41:52 +08:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2021-04-15 21:50:29 +08:00
|
|
|
@doc """
|
|
|
|
Stores in the session the secret for the given mode.
|
|
|
|
"""
|
|
|
|
def store(conn, mode, value) do
|
|
|
|
put_session(conn, key(conn, mode), hash(value))
|
|
|
|
end
|
|
|
|
|
2021-04-15 20:15:56 +08:00
|
|
|
@doc """
|
|
|
|
Checks if given connection is already authenticated.
|
|
|
|
"""
|
2021-04-15 21:50:29 +08:00
|
|
|
@spec authenticated?(Plug.Conn.t(), Livebook.Config.auth_mode()) :: boolean()
|
|
|
|
def authenticated?(conn, mode)
|
2021-04-08 17:41:52 +08:00
|
|
|
|
2021-04-15 20:15:56 +08:00
|
|
|
def authenticated?(conn, mode) when mode in [:token, :password] do
|
2021-04-15 21:50:29 +08:00
|
|
|
secret = get_session(conn, key(conn, mode))
|
|
|
|
is_binary(secret) and Plug.Crypto.secure_compare(secret, expected(mode))
|
2021-04-15 20:15:56 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
def authenticated?(_conn, _mode) do
|
|
|
|
true
|
|
|
|
end
|
|
|
|
|
2021-04-15 21:50:29 +08:00
|
|
|
defp authenticate(conn, :password) do
|
|
|
|
conn
|
|
|
|
|> redirect(to: "/authenticate")
|
|
|
|
|> halt()
|
2021-04-15 20:15:56 +08:00
|
|
|
end
|
|
|
|
|
2021-04-15 21:50:29 +08:00
|
|
|
defp authenticate(conn, :token) do
|
|
|
|
token = Map.get(conn.query_params, "token")
|
2021-04-08 17:41:52 +08:00
|
|
|
|
2021-04-15 21:50:29 +08:00
|
|
|
if is_binary(token) and Plug.Crypto.secure_compare(hash(token), expected(:token)) do
|
|
|
|
# Redirect to the same path without query params
|
|
|
|
conn
|
|
|
|
|> store(:token, token)
|
|
|
|
|> redirect(to: conn.request_path)
|
|
|
|
|> halt()
|
|
|
|
else
|
|
|
|
raise LivebookWeb.InvalidTokenError
|
2021-04-08 17:41:52 +08:00
|
|
|
end
|
|
|
|
end
|
2021-04-15 20:15:56 +08:00
|
|
|
|
2021-04-15 21:50:29 +08:00
|
|
|
defp key(conn, mode), do: "#{conn.port}:#{mode}"
|
|
|
|
defp expected(mode), do: hash(Application.fetch_env!(:livebook, mode))
|
|
|
|
defp hash(value), do: :crypto.hash(:sha256, value)
|
2021-04-08 17:41:52 +08:00
|
|
|
end
|