philomena/lib/philomena_web/plugs/totp_plug.ex

40 lines
905 B
Elixir
Raw Normal View History

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
"""
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
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
case conn.assigns.totp_valid? do
true ->
2019-11-13 04:12:46 +01:00
conn
_falsy ->
2019-11-13 04:12:46 +01:00
conn
2024-06-06 22:28:35 +02:00
|> Phoenix.Controller.redirect(to: ~p"/sessions/totp/new")
|> Plug.Conn.halt()
2019-11-13 04:12:46 +01:00
end
end
2020-01-11 05:20:19 +01:00
end