2019-11-17 19:18:21 +01:00
|
|
|
defmodule PhilomenaWeb.TotpPlug do
|
2019-11-13 04:12:46 +01:00
|
|
|
@moduledoc """
|
|
|
|
This plug ensures that a user session has a valid TOTP.
|
|
|
|
|
|
|
|
## Example
|
|
|
|
|
|
|
|
plug PhilomenaWeb.TotpPlug
|
|
|
|
"""
|
|
|
|
|
|
|
|
alias PhilomenaWeb.Router.Helpers, as: Routes
|
2024-04-28 04:58:43 +02:00
|
|
|
use PhilomenaWeb, :verified_routes
|
2019-11-13 04:12:46 +01:00
|
|
|
|
|
|
|
@doc false
|
|
|
|
@spec init(any()) :: any()
|
|
|
|
def init(opts), do: opts
|
|
|
|
|
|
|
|
@doc false
|
|
|
|
@spec call(Plug.Conn.t(), any()) :: Plug.Conn.t()
|
|
|
|
def call(conn, _opts) do
|
2020-07-28 22:56:26 +02:00
|
|
|
case conn.assigns.current_user do
|
2020-01-11 05:20:19 +01:00
|
|
|
nil -> conn
|
2019-11-13 04:12:46 +01:00
|
|
|
user -> maybe_require_totp_phase(user, conn)
|
|
|
|
end
|
|
|
|
end
|
2020-01-11 05:20:19 +01:00
|
|
|
|
2019-11-13 04:12:46 +01:00
|
|
|
defp maybe_require_totp_phase(%{otp_required_for_login: nil}, conn), do: conn
|
|
|
|
defp maybe_require_totp_phase(%{otp_required_for_login: false}, conn), do: conn
|
2020-01-11 05:20:19 +01:00
|
|
|
|
2019-11-13 04:12:46 +01:00
|
|
|
defp maybe_require_totp_phase(_user, conn) do
|
2020-07-28 22:56:26 +02:00
|
|
|
case conn.assigns.totp_valid? do
|
|
|
|
true ->
|
2019-11-13 04:12:46 +01:00
|
|
|
conn
|
|
|
|
|
2020-07-28 22:56:26 +02:00
|
|
|
_falsy ->
|
2019-11-13 04:12:46 +01:00
|
|
|
conn
|
2024-04-29 02:55:27 +02:00
|
|
|
|> Phoenix.Controller.redirect(to: ~p"/sessions/totp/new")
|
2020-07-28 22:56:26 +02:00
|
|
|
|> Plug.Conn.halt()
|
2019-11-13 04:12:46 +01:00
|
|
|
end
|
|
|
|
end
|
2020-01-11 05:20:19 +01:00
|
|
|
end
|