+# Set TFA to enabled if $tfa_cfg is passed, or to disabled if $tfa_cfg is undef,
+# When enabling we also merge the old user.cfg keys into the $tfa_cfg.
+my sub set_user_tfa_enabled : prototype($$$) {
+ my ($userid, $realm, $tfa_cfg) = @_;
+
+ PVE::AccessControl::lock_user_config(sub {
+ my $user_cfg = cfs_read_file('user.cfg');
+ my $user = $user_cfg->{users}->{$userid};
+ my $keys = $user->{keys};
+ # When enabling, we convert old-old keys,
+ # When disabling, we shouldn't actually have old keys anymore, so if they are there,
+ # they'll be removed.
+ if ($tfa_cfg && $keys && $keys !~ /^x(?:!.*)?$/) {
+ my $domain_cfg = cfs_read_file('domains.cfg');
+ my $realm_cfg = $domain_cfg->{ids}->{$realm};
+ die "auth domain '$realm' does not exist\n" if !$realm_cfg;
+
+ my $realm_tfa = $realm_cfg->{tfa};
+ $realm_tfa = PVE::Auth::Plugin::parse_tfa_config($realm_tfa) if $realm_tfa;
+
+ PVE::AccessControl::add_old_keys_to_realm_tfa($userid, $tfa_cfg, $realm_tfa, $keys);
+ }
+ $user->{keys} = $tfa_cfg ? 'x' : undef;
+ cfs_write_file("user.cfg", $user_cfg);
+ }, "enabling TFA for the user failed");
+}
+