Ensure we can update contentMap on update
[akkoma] / lib / pleroma / mfa / changeset.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.MFA.Changeset do
6 alias Pleroma.MFA
7 alias Pleroma.MFA.Settings
8 alias Pleroma.User
9
10 def disable(%Ecto.Changeset{} = changeset, force \\ false) do
11 settings =
12 changeset
13 |> Ecto.Changeset.apply_changes()
14 |> MFA.fetch_settings()
15
16 if force || not MFA.enabled?(settings) do
17 put_change(changeset, %Settings{settings | enabled: false})
18 else
19 changeset
20 end
21 end
22
23 def disable_totp(%User{multi_factor_authentication_settings: settings} = user) do
24 user
25 |> put_change(%Settings{settings | totp: %Settings.TOTP{}})
26 end
27
28 def confirm_totp(%User{multi_factor_authentication_settings: settings} = user) do
29 totp_settings = %Settings.TOTP{settings.totp | confirmed: true}
30
31 user
32 |> put_change(%Settings{settings | totp: totp_settings, enabled: true})
33 end
34
35 def setup_totp(%User{} = user, attrs) do
36 mfa_settings = MFA.fetch_settings(user)
37
38 totp_settings =
39 %Settings.TOTP{}
40 |> Ecto.Changeset.cast(attrs, [:secret, :delivery_type])
41
42 user
43 |> put_change(%Settings{mfa_settings | totp: Ecto.Changeset.apply_changes(totp_settings)})
44 end
45
46 def cast_backup_codes(%User{} = user, codes) do
47 user
48 |> put_change(%Settings{
49 user.multi_factor_authentication_settings
50 | backup_codes: codes
51 })
52 end
53
54 defp put_change(%User{} = user, settings) do
55 user
56 |> Ecto.Changeset.change()
57 |> put_change(settings)
58 end
59
60 defp put_change(%Ecto.Changeset{} = changeset, settings) do
61 changeset
62 |> Ecto.Changeset.put_change(:multi_factor_authentication_settings, settings)
63 end
64 end