@nocobase/plugin-auth
Version:
User authentication management, including password, SMS, and support for Single Sign-On (SSO) protocols, with extensibility.
325 lines (323 loc) • 12.2 kB
JavaScript
/**
* This file is part of the NocoBase (R) project.
* Copyright (c) 2020-2024 NocoBase Co., Ltd.
* Authors: NocoBase Team.
*
* This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var basic_auth_exports = {};
__export(basic_auth_exports, {
BasicAuth: () => BasicAuth
});
module.exports = __toCommonJS(basic_auth_exports);
var import_auth = require("@nocobase/auth");
var import_lodash = __toESM(require("lodash"));
var import_preset = require("../preset");
var import_utils = require("@nocobase/utils");
class BasicAuth extends import_auth.BaseAuth {
static optionsKeysNotAllowedInEnv = ["emailContentText", "emailContentHTML", "emailSubject"];
constructor(config) {
const userCollection = config.ctx.db.getCollection("users");
super({ ...config, userCollection });
}
isEmail(value) {
return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(value);
}
async validate() {
const ctx = this.ctx;
const {
account,
// Username or email
email,
// Old parameter, compatible with old api
password
} = ctx.action.params.values || {};
if (!account && !email) {
ctx.throw(400, ctx.t("Please enter your username or email", { ns: import_preset.namespace }));
}
const filter = email ? { email } : {
$or: [{ username: account }, { email: account }]
};
const user = await this.userRepository.findOne({
filter
});
if (!user) {
ctx.throw(401, ctx.t("The username/email or password is incorrect, please re-enter", { ns: import_preset.namespace }));
}
const field = this.userCollection.getField("password");
const valid = await field.verify(password, user.password);
if (!valid) {
ctx.throw(401, ctx.t("The username/email or password is incorrect, please re-enter", { ns: import_preset.namespace }), {
internalCode: "INCORRECT_PASSWORD",
user
});
}
return user;
}
getSignupFormSettings() {
var _a;
const options = ((_a = this.authenticator.options) == null ? void 0 : _a.public) || {};
let { signupForm = [] } = options;
signupForm = signupForm.filter((item) => item.show);
if (!(signupForm.length && signupForm.some(
(item) => ["username", "email"].includes(item.field) && item.show && item.required
))) {
signupForm.push({ field: "username", show: true, required: true });
}
return signupForm;
}
verfiySignupParams(signupFormSettings, values) {
const { username, email } = values;
const usernameSetting = signupFormSettings.find((item) => item.field === "username");
if (usernameSetting && usernameSetting.show) {
if (username && !this.validateUsername(username) || usernameSetting.required && !username) {
throw new Error("Please enter a valid username");
}
}
const emailSetting = signupFormSettings.find((item) => item.field === "email");
if (emailSetting && emailSetting.show) {
if (email && !this.isEmail(email)) {
throw new Error("Please enter a valid email address");
}
if (emailSetting.required && !email) {
throw new Error("Please enter a valid email address");
}
}
const requiredFields = signupFormSettings.filter((item) => item.show && item.required);
requiredFields.forEach((item) => {
if (!values[item.field]) {
throw new Error(`Please enter ${item.field}`);
}
});
}
async signUp() {
var _a;
const ctx = this.ctx;
const options = ((_a = this.authenticator.options) == null ? void 0 : _a.public) || {};
if (!options.allowSignUp) {
ctx.throw(403, ctx.t("Not allowed to sign up", { ns: import_preset.namespace }));
}
const User = ctx.db.getRepository("users");
const { values } = ctx.action.params;
const { password, confirm_password } = values;
const signupFormSettings = this.getSignupFormSettings();
try {
this.verfiySignupParams(signupFormSettings, values);
} catch (error) {
ctx.throw(400, this.ctx.t(error.message, { ns: import_preset.namespace }));
}
if (!password) {
ctx.throw(400, ctx.t("Please enter a password", { ns: import_preset.namespace }));
}
if (password !== confirm_password) {
ctx.throw(400, ctx.t("The password is inconsistent, please re-enter", { ns: import_preset.namespace }));
}
const fields = signupFormSettings.map((item) => item.field);
const userValues = import_lodash.default.pick(values, fields);
const user = await User.create({ values: { ...userValues, password } });
return user;
}
getEmailConfig() {
var _a, _b;
const options = import_lodash.default.omit(this.authenticator.options, "public") || {};
return { ...options, enableResetPassword: (_b = (_a = this.authenticator.options) == null ? void 0 : _a.public) == null ? void 0 : _b.enableResetPassword };
}
async lostPassword() {
var _a;
const ctx = this.ctx;
const {
values: { email, baseURL }
} = ctx.action.params;
const authenticatorName = ctx.headers["x-authenticator"];
if (!authenticatorName) {
ctx.throw(400, ctx.t("Missing X-Authenticator in request header", { ns: import_preset.namespace }));
}
if (!email) {
ctx.throw(400, ctx.t("Please fill in your email address", { ns: import_preset.namespace }));
}
if (!this.isEmail(email)) {
ctx.throw(400, ctx.t("Incorrect email format", { ns: import_preset.namespace }));
}
const user = await this.userRepository.findOne({
where: {
email
}
});
if (!user) {
ctx.throw(401, ctx.t("The email is incorrect, please re-enter", { ns: import_preset.namespace }));
}
const {
notificationChannel,
emailContentType,
emailContentHTML,
emailContentText,
emailSubject,
enableResetPassword,
resetTokenExpiresIn
} = this.getEmailConfig();
if (!enableResetPassword) {
ctx.throw(403, ctx.t("Not allowed to reset password", { ns: import_preset.namespace }));
}
const resetToken = await ctx.app.authManager.jwt.sign(
{
resetPasswordUserId: user.id
},
{
expiresIn: resetTokenExpiresIn * 60
// 配置的过期时间,单位分钟,需要转成秒
}
);
const resetLink = `${baseURL}/reset-password?resetToken=${resetToken}&name=${authenticatorName}`;
const systemSettings = await ((_a = ctx.db.getRepository("systemSettings")) == null ? void 0 : _a.findOne()) || {};
const notificationManager = ctx.app.getPlugin("notification-manager");
if (notificationManager) {
const emailer = await notificationManager.manager.findChannel(notificationChannel);
if (emailer) {
try {
const parsedSubject = (0, import_utils.parsedValue)(emailSubject, {
$user: user,
$resetLink: resetLink,
$env: ctx.app.environment.getVariables(),
$resetLinkExpiration: resetTokenExpiresIn,
$systemSettings: systemSettings
});
const parsedContent = (0, import_utils.parsedValue)(emailContentType === "html" ? emailContentHTML : emailContentText, {
$user: user,
$resetLink: resetLink,
$env: ctx.app.environment.getVariables(),
$resetLinkExpiration: resetTokenExpiresIn,
$systemSettings: systemSettings
});
const content = emailContentType === "html" ? { html: parsedContent } : { text: parsedContent };
try {
await notificationManager.send({
channelName: notificationChannel,
message: {
to: [email],
subject: parsedSubject,
contentType: emailContentType,
...content
}
});
ctx.logger.info(`Password reset email sent to ${email}`);
} catch (error) {
ctx.logger.error(`Failed to send reset password email: ${error.message}`, {
error,
email,
notificationChannel
});
ctx.throw(
500,
ctx.t("Failed to send email. Error: {{error}}", {
ns: import_preset.namespace,
error: error.message
})
);
}
} catch (error) {
ctx.logger.error(`Error parsing email template variables: ${error.message}`, {
error,
emailSubject,
emailContentType
});
ctx.throw(
500,
ctx.t("Error parsing email template. Error: {{error}}", {
ns: import_preset.namespace,
error: error.message
})
);
}
} else {
ctx.throw(400, ctx.t("Email channel not found", { ns: import_preset.namespace }));
}
} else {
ctx.throw(500, ctx.t("Notification manager plugin not found", { ns: import_preset.namespace }));
}
ctx.logger.info(`Password reset email sent to ${email}`);
return null;
}
async resetPassword() {
const ctx = this.ctx;
const {
values: { password, resetToken }
} = ctx.action.params;
if (!resetToken) {
ctx.throw(401, ctx.t("Token expired", { ns: import_preset.namespace }));
}
try {
await this.checkResetToken(resetToken);
} catch (error) {
throw error;
}
let decodedToken;
try {
decodedToken = await ctx.app.authManager.jwt.decode(resetToken);
} catch (error) {
ctx.throw(401, ctx.t("Token expired", { ns: import_preset.namespace }));
}
const user = await this.userRepository.findOne({
where: {
id: decodedToken.resetPasswordUserId
}
});
if (!user) {
ctx.throw(404, ctx.t("User not found", { ns: import_preset.namespace }));
}
user.password = password;
await user.save();
await ctx.app.authManager.jwt.block(resetToken);
ctx.logger.info(`Password for user ${user.id} has been reset`);
return null;
}
/**
* 检查重置密码的 Token 是否有效
*/
async checkResetToken(resetToken) {
if (!resetToken) {
this.ctx.throw(401, this.ctx.t("Token expired", { ns: import_preset.namespace }));
}
const blocked = await this.jwt.blacklist.has(resetToken);
if (blocked) {
this.ctx.throw(401, this.ctx.t("Token expired", { ns: import_preset.namespace }));
}
try {
await this.ctx.app.authManager.jwt.decode(resetToken);
return true;
} catch (err) {
this.ctx.throw(401, this.ctx.t("Token expired", { ns: import_preset.namespace }));
}
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
BasicAuth
});