philomena/lib/philomena_web/plugs/totp_plug.ex

40 lines
930 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
"""
alias PhilomenaWeb.Router.Helpers, as: Routes
@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
|> Phoenix.Controller.redirect(to: Routes.session_totp_path(conn, :new))
|> Plug.Conn.halt()
2019-11-13 04:12:46 +01:00
end
end
2020-01-11 05:20:19 +01:00
end