2019-11-13 04:12:46 +01:00
|
|
|
defmodule PhilomenaWeb.Registration.TotpController do
|
|
|
|
use PhilomenaWeb, :controller
|
|
|
|
|
2020-07-28 22:56:26 +02:00
|
|
|
alias PhilomenaWeb.UserAuth
|
2019-11-13 04:12:46 +01:00
|
|
|
alias Philomena.Users.User
|
2020-07-28 22:56:26 +02:00
|
|
|
alias Philomena.Users
|
2019-11-13 04:12:46 +01:00
|
|
|
alias Philomena.Repo
|
|
|
|
|
|
|
|
def edit(conn, _params) do
|
|
|
|
user = conn.assigns.current_user
|
|
|
|
|
|
|
|
case user.encrypted_otp_secret do
|
|
|
|
nil ->
|
|
|
|
user
|
|
|
|
|> User.create_totp_secret_changeset()
|
|
|
|
|> Repo.update()
|
|
|
|
|
2020-07-28 22:56:26 +02:00
|
|
|
# Redirect to have the conn pick up the changes
|
2024-06-06 22:28:35 +02:00
|
|
|
redirect(conn, to: ~p"/registrations/totp/edit")
|
2019-11-13 04:12:46 +01:00
|
|
|
|
|
|
|
_ ->
|
2020-07-28 22:56:26 +02:00
|
|
|
changeset = Users.change_user(user)
|
2019-11-13 05:49:37 +01:00
|
|
|
secret = User.totp_secret(user)
|
|
|
|
qrcode = User.totp_qrcode(user)
|
2020-01-11 05:20:19 +01:00
|
|
|
|
|
|
|
render(conn, "edit.html",
|
2020-08-18 00:05:22 +02:00
|
|
|
title: "Two Factor Authentication",
|
2020-01-11 05:20:19 +01:00
|
|
|
changeset: changeset,
|
|
|
|
totp_secret: secret,
|
|
|
|
totp_qrcode: qrcode
|
|
|
|
)
|
2019-11-13 04:12:46 +01:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def update(conn, params) do
|
|
|
|
backup_codes = User.random_backup_codes()
|
2020-07-28 22:56:26 +02:00
|
|
|
user = conn.assigns.current_user
|
2019-11-13 04:12:46 +01:00
|
|
|
|
2019-11-13 05:49:37 +01:00
|
|
|
user
|
2019-11-13 04:12:46 +01:00
|
|
|
|> User.totp_changeset(params, backup_codes)
|
|
|
|
|> Repo.update()
|
|
|
|
|> case do
|
|
|
|
{:error, changeset} ->
|
2019-11-13 05:49:37 +01:00
|
|
|
secret = User.totp_secret(user)
|
|
|
|
qrcode = User.totp_qrcode(user)
|
|
|
|
render(conn, "edit.html", changeset: changeset, totp_secret: secret, totp_qrcode: qrcode)
|
2020-01-11 05:20:19 +01:00
|
|
|
|
2019-11-13 04:12:46 +01:00
|
|
|
{:ok, user} ->
|
|
|
|
conn
|
|
|
|
|> put_flash(:totp_backup_codes, backup_codes)
|
2024-06-06 22:28:35 +02:00
|
|
|
|> put_session(:user_return_to, ~p"/registrations/totp/edit")
|
2020-11-16 03:07:55 +01:00
|
|
|
|> UserAuth.totp_auth_user(user, %{})
|
2019-11-13 04:12:46 +01:00
|
|
|
end
|
|
|
|
end
|
2019-12-16 20:24:38 +01:00
|
|
|
end
|