philomena/lib/pow_multi_factor/plug.ex

38 lines
739 B
Elixir
Raw Normal View History

2019-10-31 18:57:39 +01:00
defmodule PowMultiFactor.Plug do
@moduledoc """
Plug helper methods.
"""
2019-11-02 14:14:03 +01:00
alias Plug.Crypto
2019-10-31 18:57:39 +01:00
alias Pow.Plug
2019-11-02 14:14:03 +01:00
alias Pow.Config
2019-10-31 18:57:39 +01:00
2019-11-02 14:14:03 +01:00
def mfa_authorized?(conn, config) do
2019-10-31 18:57:39 +01:00
user = Plug.current_user(conn)
if user.otp_required_for_login do
2019-11-02 14:14:03 +01:00
secret = user.__struct__.otp_secret(user)
totp = Elixir2fa.generate_totp(secret)
Crypto.secure_compare(totp, conn.params)
2019-10-31 18:57:39 +01:00
else
2019-11-02 14:14:03 +01:00
true
2019-10-31 18:57:39 +01:00
end
end
2019-11-02 14:14:03 +01:00
def assign_mfa(conn, config) do
user = Plug.current_user(conn)
repo = Config.repo!(config)
2019-10-31 18:57:39 +01:00
2019-11-02 14:14:03 +01:00
if user.encrypted_otp_secret in [nil, ""] do
{:ok, user} =
user.__struct__.put_otp_secret(Elixir2fa.random_secret())
|> repo.update()
2019-10-31 18:57:39 +01:00
2019-11-02 14:14:03 +01:00
user
else
user
end
end
2019-10-31 18:57:39 +01:00
end