discourse/app/assets/javascripts/admin/addon/controllers/admin-user-index.js

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

621 lines
17 KiB
JavaScript
Raw Normal View History

import DiscourseURL, { userPath } from "discourse/lib/url";
import { and, notEmpty } from "@ember/object/computed";
2019-10-29 13:31:44 -04:00
import { fmt, propertyNotEqual, setting } from "discourse/lib/computed";
import AdminUser from "admin/models/admin-user";
2019-10-29 13:31:44 -04:00
import CanCheckEmails from "discourse/mixins/can-check-emails";
import Controller from "@ember/controller";
import I18n from "I18n";
2016-06-30 13:55:44 -04:00
import { ajax } from "discourse/lib/ajax";
2015-08-07 15:08:27 -04:00
import bootbox from "bootbox";
import discourseComputed from "discourse-common/utils/decorators";
import getURL from "discourse-common/lib/get-url";
import { htmlSafe } from "@ember/template";
import { iconHTML } from "discourse-common/lib/icon-library";
import { extractError, popupAjaxError } from "discourse/lib/ajax-error";
import { inject as service } from "@ember/service";
import showModal from "discourse/lib/show-modal";
2014-08-12 19:04:36 -04:00
export default Controller.extend(CanCheckEmails, {
FEATURE: Centralized 2FA page (#15377) 2FA support in Discourse was added and grown gradually over the years: we first added support for TOTP for logins, then we implemented backup codes, and last but not least, security keys. 2FA usage was initially limited to logging in, but it has been expanded and we now require 2FA for risky actions such as adding a new admin to the site. As a result of this gradual growth of the 2FA system, technical debt has accumulated to the point where it has become difficult to require 2FA for more actions. We now have 5 different 2FA UI implementations and each one has to support all 3 2FA methods (TOTP, backup codes, and security keys) which makes it difficult to maintain a consistent UX for these different implementations. Moreover, there is a lot of repeated logic in the server-side code behind these 5 UI implementations which hinders maintainability even more. This commit is the first step towards repaying the technical debt: it builds a system that centralizes as much as possible of the 2FA server-side logic and UI. The 2 main components of this system are: 1. A dedicated page for 2FA with support for all 3 methods. 2. A reusable server-side class that centralizes the 2FA logic (the `SecondFactor::AuthManager` class). From a top-level view, the 2FA flow in this new system looks like this: 1. User initiates an action that requires 2FA; 2. Server is aware that 2FA is required for this action, so it redirects the user to the 2FA page if the user has a 2FA method, otherwise the action is performed. 3. User submits the 2FA form on the page; 4. Server validates the 2FA and if it's successful, the action is performed and the user is redirected to the previous page. A more technically-detailed explanation/documentation of the new system is available as a comment at the top of the `lib/second_factor/auth_manager.rb` file. Please note that the details are not set in stone and will likely change in the future, so please don't use the system in your plugins yet. Since this is a new system that needs to be tested, we've decided to migrate only the 2FA for adding a new admin to the new system at this time (in this commit). Our plan is to gradually migrate the remaining 2FA implementations to the new system. For screenshots of the 2FA page, see PR #15377 on GitHub.
2022-02-17 04:12:59 -05:00
router: service(),
adminTools: service(),
originalPrimaryGroupId: null,
customGroupIdsBuffer: null,
availableGroups: null,
userTitleValue: null,
ssoExternalEmail: null,
ssoLastPayload: null,
2015-08-07 15:08:27 -04:00
showBadges: setting("enable_badges"),
hasLockedTrustLevel: notEmpty("model.manual_locked_trust_level"),
2014-03-05 07:52:20 -05:00
2015-08-07 15:08:27 -04:00
primaryGroupDirty: propertyNotEqual(
"originalPrimaryGroupId",
"model.primary_group_id"
),
canDisableSecondFactor: and(
"model.second_factor_enabled",
"model.can_disable_second_factor"
),
@discourseComputed("model.customGroups")
customGroupIds(customGroups) {
return customGroups.mapBy("id");
},
@discourseComputed("customGroupIdsBuffer", "customGroupIds")
customGroupsDirty(buffer, original) {
if (buffer === null) {
return false;
}
return buffer.length === original.length
? buffer.any((id) => !original.includes(id))
: true;
},
@discourseComputed("model.automaticGroups")
automaticGroups(automaticGroups) {
return automaticGroups
.map((group) => {
const name = htmlSafe(group.name);
return `<a href="/g/${name}">${name}</a>`;
})
.join(", ");
},
@discourseComputed("model.associated_accounts")
associatedAccountsLoaded(associatedAccounts) {
return typeof associatedAccounts !== "undefined";
},
@discourseComputed("model.associated_accounts")
associatedAccounts(associatedAccounts) {
return associatedAccounts
.map((provider) => `${provider.name} (${provider.description})`)
.join(", ");
},
@discourseComputed("model.user_fields.[]")
userFields(userFields) {
return this.site.collectUserFields(userFields);
},
preferencesPath: fmt("model.username_lower", userPath("%@/preferences")),
@discourseComputed(
"model.can_delete_all_posts",
"model.staff",
"model.post_count"
)
deleteAllPostsExplanation(canDeleteAllPosts, staff, postCount) {
if (canDeleteAllPosts) {
return null;
}
if (staff) {
return I18n.t("admin.user.delete_posts_forbidden_because_staff");
}
if (postCount > this.siteSettings.delete_all_posts_max) {
return I18n.t("admin.user.cant_delete_all_too_many_posts", {
count: this.siteSettings.delete_all_posts_max,
});
} else {
return I18n.t("admin.user.cant_delete_all_posts", {
count: this.siteSettings.delete_user_max_post_age,
});
}
},
@discourseComputed("model.canBeDeleted", "model.staff")
deleteExplanation(canBeDeleted, staff) {
if (canBeDeleted) {
return null;
}
if (staff) {
return I18n.t("admin.user.delete_forbidden_because_staff");
} else {
return I18n.t("admin.user.delete_forbidden", {
count: this.siteSettings.delete_user_max_post_age,
});
}
},
@discourseComputed("model.username")
postEditsByEditorFilter(username) {
return { editor: username };
},
groupAdded(added) {
this.model
.groupAdded(added)
.catch(() => bootbox.alert(I18n.t("generic_error")));
},
groupRemoved(groupId) {
this.model
.groupRemoved(groupId)
.then(() => {
if (groupId === this.originalPrimaryGroupId) {
this.set("originalPrimaryGroupId", null);
}
})
.catch(() => bootbox.alert(I18n.t("generic_error")));
},
@discourseComputed("ssoLastPayload")
ssoPayload(lastPayload) {
return lastPayload.split("&");
},
2013-09-16 14:08:55 -04:00
actions: {
impersonate() {
return this.model
.impersonate()
.then(() => DiscourseURL.redirectTo("/"))
.catch((e) => {
if (e.status === 404) {
bootbox.alert(I18n.t("admin.impersonate.not_found"));
} else {
bootbox.alert(I18n.t("admin.impersonate.invalid"));
}
});
},
logOut() {
return this.model
.logOut()
.then(() => bootbox.alert(I18n.t("admin.user.logged_out")));
},
resetBounceScore() {
return this.model.resetBounceScore();
},
approve() {
return this.model.approve(this.currentUser);
},
_formatError(event) {
return `http: ${event.status} - ${event.body}`;
},
deactivate() {
return this.model
.deactivate()
.then(() =>
this.model.setProperties({ active: false, can_activate: true })
)
.catch((e) => {
const error = I18n.t("admin.user.deactivate_failed", {
error: this._formatError(e),
});
bootbox.alert(error);
});
},
sendActivationEmail() {
return this.model
.sendActivationEmail()
.then(() => bootbox.alert(I18n.t("admin.user.activation_email_sent")))
.catch(popupAjaxError);
},
activate() {
return this.model
.activate()
.then(() =>
this.model.setProperties({
active: true,
can_deactivate: !this.model.staff,
})
)
.catch((e) => {
const error = I18n.t("admin.user.activate_failed", {
error: this._formatError(e),
});
bootbox.alert(error);
});
},
revokeAdmin() {
return this.model.revokeAdmin();
},
grantAdmin() {
return this.model
.grantAdmin()
.then((result) => {
if (result.email_confirmation_required) {
bootbox.alert(I18n.t("admin.user.grant_admin_confirm"));
}
})
FEATURE: Centralized 2FA page (#15377) 2FA support in Discourse was added and grown gradually over the years: we first added support for TOTP for logins, then we implemented backup codes, and last but not least, security keys. 2FA usage was initially limited to logging in, but it has been expanded and we now require 2FA for risky actions such as adding a new admin to the site. As a result of this gradual growth of the 2FA system, technical debt has accumulated to the point where it has become difficult to require 2FA for more actions. We now have 5 different 2FA UI implementations and each one has to support all 3 2FA methods (TOTP, backup codes, and security keys) which makes it difficult to maintain a consistent UX for these different implementations. Moreover, there is a lot of repeated logic in the server-side code behind these 5 UI implementations which hinders maintainability even more. This commit is the first step towards repaying the technical debt: it builds a system that centralizes as much as possible of the 2FA server-side logic and UI. The 2 main components of this system are: 1. A dedicated page for 2FA with support for all 3 methods. 2. A reusable server-side class that centralizes the 2FA logic (the `SecondFactor::AuthManager` class). From a top-level view, the 2FA flow in this new system looks like this: 1. User initiates an action that requires 2FA; 2. Server is aware that 2FA is required for this action, so it redirects the user to the 2FA page if the user has a 2FA method, otherwise the action is performed. 3. User submits the 2FA form on the page; 4. Server validates the 2FA and if it's successful, the action is performed and the user is redirected to the previous page. A more technically-detailed explanation/documentation of the new system is available as a comment at the top of the `lib/second_factor/auth_manager.rb` file. Please note that the details are not set in stone and will likely change in the future, so please don't use the system in your plugins yet. Since this is a new system that needs to be tested, we've decided to migrate only the 2FA for adding a new admin to the new system at this time (in this commit). Our plan is to gradually migrate the remaining 2FA implementations to the new system. For screenshots of the 2FA page, see PR #15377 on GitHub.
2022-02-17 04:12:59 -05:00
.catch((error) => {
const nonce = error.jqXHR?.responseJSON.second_factor_challenge_nonce;
if (nonce) {
this.router.transitionTo("second-factor-auth", {
queryParams: { nonce },
});
} else {
popupAjaxError(error);
}
});
},
revokeModeration() {
return this.model.revokeModeration();
},
grantModeration() {
return this.model.grantModeration();
},
saveTrustLevel() {
return this.model
.saveTrustLevel()
.then(() => window.location.reload())
.catch((e) => {
let error;
if (e.jqXHR.responseJSON && e.jqXHR.responseJSON.errors) {
error = e.jqXHR.responseJSON.errors[0];
}
error =
error ||
I18n.t("admin.user.trust_level_change_failed", {
error: this._formatError(e),
});
bootbox.alert(error);
});
},
restoreTrustLevel() {
return this.model.restoreTrustLevel();
},
lockTrustLevel(locked) {
return this.model
.lockTrustLevel(locked)
.then(() => window.location.reload())
.catch((e) => {
let error;
if (e.jqXHR.responseJSON && e.jqXHR.responseJSON.errors) {
error = e.jqXHR.responseJSON.errors[0];
}
error =
error ||
I18n.t("admin.user.trust_level_change_failed", {
error: this._formatError(e),
});
bootbox.alert(error);
});
2017-11-10 12:18:08 -05:00
},
unsilence() {
return this.model.unsilence();
2017-11-10 12:18:08 -05:00
},
silence() {
return this.model.silence();
},
anonymize() {
const user = this.model;
const message = I18n.t("admin.user.anonymize_confirm");
const performAnonymize = () => {
this.model
.anonymize()
.then((data) => {
if (data.success) {
if (data.username) {
document.location = getURL(
`/admin/users/${user.get("id")}/${data.username}`
);
} else {
document.location = getURL("/admin/users/list/active");
}
} else {
bootbox.alert(I18n.t("admin.user.anonymize_failed"));
if (data.user) {
user.setProperties(data.user);
}
}
})
.catch(() => bootbox.alert(I18n.t("admin.user.anonymize_failed")));
};
const buttons = [
{
label: I18n.t("composer.cancel"),
class: "cancel",
link: true,
},
{
label: I18n.t("admin.user.anonymize_yes"),
class: "btn btn-danger",
icon: iconHTML("exclamation-triangle"),
callback: () => {
performAnonymize();
},
},
];
bootbox.dialog(message, buttons, { classes: "delete-user-modal" });
},
disableSecondFactor() {
return this.model.disableSecondFactor();
2018-06-15 11:03:24 -04:00
},
clearPenaltyHistory() {
const user = this.model;
const path = `/admin/users/${user.get("id")}/penalty_history`;
return ajax(path, { type: "DELETE" })
.then(() => user.set("tl3_requirements.penalty_counts.total", 0))
.catch(popupAjaxError);
},
destroy() {
const postCount = this.get("model.post_count");
const maxPostCount = this.siteSettings.delete_all_posts_max;
const message = I18n.t("admin.user.delete_confirm");
const location = document.location.pathname;
const performDestroy = (block) => {
bootbox.dialog(I18n.t("admin.user.deleting_user"));
let formData = { context: location };
if (block) {
formData["block_email"] = true;
formData["block_urls"] = true;
formData["block_ip"] = true;
}
if (postCount <= maxPostCount) {
formData["delete_posts"] = true;
}
this.model
.destroy(formData)
.then((data) => {
if (data.deleted) {
if (/^\/admin\/users\/list\//.test(location)) {
document.location = location;
} else {
document.location = getURL("/admin/users/list/active");
}
} else {
bootbox.alert(I18n.t("admin.user.delete_failed"));
}
})
.catch(() => {
bootbox.alert(I18n.t("admin.user.delete_failed"));
});
};
const buttons = [
{
label: I18n.t("composer.cancel"),
class: "btn",
link: true,
},
{
icon: iconHTML("exclamation-triangle"),
label: I18n.t("admin.user.delete_and_block"),
class: "btn btn-danger",
callback: () => {
performDestroy(true);
},
},
{
label: I18n.t("admin.user.delete_dont_block"),
class: "btn btn-primary",
callback: () => {
performDestroy(false);
},
},
];
bootbox.dialog(message, buttons, { classes: "delete-user-modal" });
},
promptTargetUser() {
showModal("admin-merge-users-prompt", {
admin: true,
model: this.model,
});
},
showMergeConfirmation(targetUsername) {
showModal("admin-merge-users-confirmation", {
admin: true,
model: {
username: this.model.username,
targetUsername,
},
});
},
merge(targetUsername) {
const user = this.model;
const location = document.location.pathname;
let formData = { context: location };
if (targetUsername) {
formData["target_username"] = targetUsername;
}
this.model
.merge(formData)
.then((response) => {
if (response.success) {
showModal("admin-merge-users-progress", {
admin: true,
model: this.model,
});
} else {
bootbox.alert(I18n.t("admin.user.merge_failed"));
}
})
.catch(() => {
AdminUser.find(user.id).then((u) => user.setProperties(u));
bootbox.alert(I18n.t("admin.user.merge_failed"));
});
},
viewActionLogs() {
this.adminTools.showActionLogs(this, {
target_user: this.get("model.username"),
});
},
2017-09-12 17:07:42 -04:00
showSuspendModal() {
this.adminTools.showSuspendModal(this.model);
2017-09-12 17:07:42 -04:00
},
unsuspend() {
this.model.unsuspend().catch(popupAjaxError);
},
showSilenceModal() {
this.adminTools.showSilenceModal(this.model);
},
2017-09-12 17:07:42 -04:00
saveUsername(newUsername) {
const oldUsername = this.get("model.username");
this.set("model.username", newUsername);
const path = `/users/${oldUsername.toLowerCase()}/preferences/username`;
return ajax(path, { data: { new_username: newUsername }, type: "PUT" })
.catch((e) => {
this.set("model.username", oldUsername);
popupAjaxError(e);
})
.finally(() => this.toggleProperty("editingUsername"));
},
saveName(newName) {
const oldName = this.get("model.name");
this.set("model.name", newName);
2018-06-15 11:03:24 -04:00
const path = userPath(`${this.get("model.username").toLowerCase()}.json`);
return ajax(path, { data: { name: newName }, type: "PUT" })
.catch((e) => {
this.set("model.name", oldName);
popupAjaxError(e);
})
.finally(() => this.toggleProperty("editingName"));
},
saveTitle(newTitle) {
const oldTitle = this.get("model.title");
this.set("model.title", newTitle);
const path = userPath(`${this.get("model.username").toLowerCase()}.json`);
return ajax(path, { data: { title: newTitle }, type: "PUT" })
.catch((e) => {
this.set("model.title", oldTitle);
popupAjaxError(e);
})
.finally(() => this.toggleProperty("editingTitle"));
2013-10-22 15:53:08 -04:00
},
saveCustomGroups() {
const currentIds = this.customGroupIds;
const bufferedIds = this.customGroupIdsBuffer;
const availableGroups = this.availableGroups;
bufferedIds
.filter((id) => !currentIds.includes(id))
.forEach((id) => this.groupAdded(availableGroups.findBy("id", id)));
currentIds
.filter((id) => !bufferedIds.includes(id))
.forEach((id) => this.groupRemoved(id));
},
2014-07-15 10:11:39 -04:00
resetCustomGroups() {
this.set("customGroupIdsBuffer", this.model.customGroups.mapBy("id"));
},
savePrimaryGroup() {
const primaryGroupId = this.get("model.primary_group_id");
const path = `/admin/users/${this.get("model.id")}/primary_group`;
return ajax(path, {
type: "PUT",
data: { primary_group_id: primaryGroupId },
})
.then(() => this.set("originalPrimaryGroupId", primaryGroupId))
.catch(() => bootbox.alert(I18n.t("generic_error")));
},
resetPrimaryGroup() {
this.set("model.primary_group_id", this.originalPrimaryGroupId);
2013-09-16 14:08:55 -04:00
},
deleteSSORecord() {
return bootbox.confirm(
FEATURE: Rename 'Discourse SSO' to DiscourseConnect (#11978) The 'Discourse SSO' protocol is being rebranded to DiscourseConnect. This should help to reduce confusion when 'SSO' is used in the generic sense. This commit aims to: - Rename `sso_` site settings. DiscourseConnect specific ones are prefixed `discourse_connect_`. Generic settings are prefixed `auth_` - Add (server-side-only) backwards compatibility for the old setting names, with deprecation notices - Copy `site_settings` database records to the new names - Rename relevant translation keys - Update relevant translations This commit does **not** aim to: - Rename any Ruby classes or methods. This might be done in a future commit - Change any URLs. This would break existing integrations - Make any changes to the protocol. This would break existing integrations - Change any functionality. Further normalization across DiscourseConnect and other auth methods will be done separately The risks are: - There is no backwards compatibility for site settings on the client-side. Accessing auth-related site settings in Javascript is fairly rare, and an error on the client side would not be security-critical. - If a plugin is monkey-patching parts of the auth process, changes to locale keys could cause broken error messages. This should also be unlikely. The old site setting names remain functional, so security-related overrides will remain working. A follow-up commit will be made with a post-deploy migration to delete the old `site_settings` rows.
2021-02-08 05:04:33 -05:00
I18n.t("admin.user.discourse_connect.confirm_delete"),
I18n.t("no_value"),
I18n.t("yes_value"),
(confirmed) => {
if (confirmed) {
return this.model.deleteSSORecord();
}
}
);
},
checkSsoEmail() {
return ajax(userPath(`${this.model.username_lower}/sso-email.json`), {
data: { context: window.location.pathname },
}).then((result) => {
if (result) {
this.set("ssoExternalEmail", result.email);
}
});
},
checkSsoPayload() {
return ajax(userPath(`${this.model.username_lower}/sso-payload.json`), {
data: { context: window.location.pathname },
}).then((result) => {
if (result) {
this.set("ssoLastPayload", result.payload);
}
});
},
showDeletePostsConfirmation() {
showModal("admin-delete-posts-confirmation", {
admin: true,
model: this.model,
});
},
deleteAllPosts() {
let deletedPosts = 0;
let deletedPercentage = 0;
const user = this.model;
const performDelete = (progressModal) => {
this.model
.deleteAllPosts()
.then(({ posts_deleted }) => {
if (posts_deleted === 0) {
user.set("post_count", 0);
progressModal.send("closeModal");
} else {
deletedPosts += posts_deleted;
deletedPercentage = Math.floor(
(deletedPosts * 100) / user.get("post_count")
);
progressModal.setProperties({
deletedPercentage,
});
performDelete(progressModal);
}
})
.catch((e) => {
progressModal.send("closeModal");
let error;
AdminUser.find(user.get("id")).then((u) => user.setProperties(u));
error = extractError(e) || I18n.t("admin.user.delete_posts_failed");
bootbox.alert(error);
});
};
const progressModal = showModal("admin-delete-user-posts-progress", {
admin: true,
});
performDelete(progressModal);
},
2013-09-16 14:08:55 -04:00
},
});