Files
Checkmate/server/src/service/business/userService.ts
T

254 lines
7.4 KiB
TypeScript
Raw Normal View History

2026-01-15 20:55:01 +00:00
import { IMonitorsRepository } from "@/repositories/index.js";
2025-07-23 13:03:57 -07:00
const SERVICE_NAME = "userService";
class UserService {
static SERVICE_NAME = SERVICE_NAME;
2025-07-25 15:15:14 -07:00
2026-01-15 20:55:01 +00:00
private db: any;
private emailService: any;
private settingsService: any;
private logger: any;
private stringService: any;
private jwt: any;
private errorService: any;
private jobQueue: any;
private crypto: any;
private monitorsRepository: IMonitorsRepository;
constructor({
crypto,
db,
emailService,
settingsService,
logger,
stringService,
jwt,
errorService,
jobQueue,
monitorsRepository,
}: {
crypto: any;
db: any;
emailService: any;
settingsService: any;
logger: any;
stringService: any;
jwt: any;
errorService: any;
jobQueue: any;
monitorsRepository: IMonitorsRepository;
}) {
2025-07-23 13:03:57 -07:00
this.db = db;
this.emailService = emailService;
this.settingsService = settingsService;
this.logger = logger;
this.stringService = stringService;
this.jwt = jwt;
2025-07-24 15:06:46 -07:00
this.errorService = errorService;
2025-07-27 19:51:39 -07:00
this.jobQueue = jobQueue;
this.crypto = crypto;
2026-01-15 20:55:01 +00:00
this.monitorsRepository = monitorsRepository;
2025-07-23 13:03:57 -07:00
}
2025-07-25 15:15:14 -07:00
get serviceName() {
return UserService.SERVICE_NAME;
}
2026-01-15 20:55:01 +00:00
issueToken = (payload: any, appSettings: any) => {
2025-07-23 13:03:57 -07:00
const tokenTTL = appSettings?.jwtTTL ?? "2h";
const tokenSecret = appSettings?.jwtSecret;
const payloadData = payload;
return this.jwt.sign(payloadData, tokenSecret, { expiresIn: tokenTTL });
};
2026-01-15 20:55:01 +00:00
registerUser = async (user: any, file: any) => {
2025-07-23 13:03:57 -07:00
// Create a new user
// If superAdmin exists, a token should be attached to all further register requests
2025-07-30 10:41:53 -07:00
const superAdminExists = await this.db.userModule.checkSuperadmin();
2025-07-23 13:03:57 -07:00
if (superAdminExists) {
2025-07-29 19:53:11 -07:00
const invitedUser = await this.db.inviteModule.getInviteTokenAndDelete(user.inviteToken);
2025-07-23 13:03:57 -07:00
user.role = invitedUser.role;
user.teamId = invitedUser.teamId;
} else {
// This is the first account, create JWT secret to use if one is not supplied by env
2025-07-30 09:18:16 -07:00
const jwtSecret = this.crypto.randomBytes(64).toString("hex");
2025-07-31 11:57:55 -07:00
await this.db.settingsModule.updateAppSettings({ jwtSecret });
2025-07-23 13:03:57 -07:00
}
2025-07-30 10:41:53 -07:00
const newUser = await this.db.userModule.insertUser({ ...user }, file);
2025-07-23 13:03:57 -07:00
this.logger.debug({
message: "New user created",
service: SERVICE_NAME,
method: "registerUser",
details: newUser._id,
});
const userForToken = { ...newUser._doc };
delete userForToken.profileImage;
delete userForToken.avatarImage;
const appSettings = await this.settingsService.getSettings();
const token = this.issueToken(userForToken, appSettings);
try {
const html = await this.emailService.buildEmail("welcomeEmailTemplate", {
name: newUser.firstName,
});
2026-01-15 20:55:01 +00:00
this.emailService.sendEmail(newUser.email, "Welcome to Uptime Monitor", html).catch((error: any) => {
2025-07-23 13:03:57 -07:00
this.logger.warn({
message: error.message,
service: SERVICE_NAME,
method: "registerUser",
stack: error.stack,
});
});
2026-01-15 20:55:01 +00:00
} catch (error: any) {
2025-07-23 13:03:57 -07:00
this.logger.warn({
message: error.message,
service: SERVICE_NAME,
method: "registerUser",
stack: error.stack,
});
}
return { user: newUser, token };
};
2026-01-15 20:55:01 +00:00
loginUser = async (email: string, password: string) => {
2025-07-23 13:03:57 -07:00
// Check if user exists
2025-07-30 10:41:53 -07:00
const user = await this.db.userModule.getUserByEmail(email);
2025-07-23 13:03:57 -07:00
// Compare password
const match = await user.comparePassword(password);
if (match !== true) {
2025-07-24 15:06:46 -07:00
throw this.errorService.createAuthenticationError(this.stringService.authIncorrectPassword);
2025-07-23 13:03:57 -07:00
}
// Remove password from user object. Should this be abstracted to DB layer?
const userWithoutPassword = { ...user._doc };
delete userWithoutPassword.password;
delete userWithoutPassword.avatarImage;
// Happy path, return token
const appSettings = await this.settingsService.getSettings();
const token = this.issueToken(userWithoutPassword, appSettings);
// reset avatar image
userWithoutPassword.avatarImage = user.avatarImage;
return { user: userWithoutPassword, token };
};
2026-01-15 20:55:01 +00:00
editUser = async (updates: any, file: any, currentUser: any) => {
2025-07-23 13:03:57 -07:00
// Change Password check
if (updates?.password && updates?.newPassword) {
// Get user's email
// Add user email to body for DB operation
updates.email = currentUser.email;
// Get user
2025-07-30 10:41:53 -07:00
const user = await this.db.userModule.getUserByEmail(currentUser.email);
2025-07-23 13:03:57 -07:00
// Compare passwords
const match = await user.comparePassword(updates?.password);
// If not a match, throw a 403
// 403 instead of 401 to avoid triggering axios interceptor
if (!match) {
2025-07-24 15:06:46 -07:00
throw this.errorService.createAuthorizationError(this.stringService.authIncorrectPassword);
2025-07-23 13:03:57 -07:00
}
// If a match, update the password
updates.password = updates.newPassword;
}
2025-07-30 10:41:53 -07:00
const updatedUser = await this.db.userModule.updateUser({ userId: currentUser?._id, user: updates, file: file });
2025-07-23 13:03:57 -07:00
return updatedUser;
};
checkSuperadminExists = async () => {
2025-07-30 10:41:53 -07:00
const superAdminExists = await this.db.userModule.checkSuperadmin();
2025-07-23 13:03:57 -07:00
return superAdminExists;
};
2026-01-15 20:55:01 +00:00
requestRecovery = async (email: string) => {
2025-07-30 10:41:53 -07:00
const user = await this.db.userModule.getUserByEmail(email);
2025-07-30 15:34:03 -07:00
const recoveryToken = await this.db.recoveryModule.requestRecoveryToken(email);
2025-07-23 13:03:57 -07:00
const name = user.firstName;
const { clientHost } = this.settingsService.getSettings();
const url = `${clientHost}/set-new-password/${recoveryToken.token}`;
const html = await this.emailService.buildEmail("passwordResetTemplate", {
name,
email,
url,
});
const msgId = await this.emailService.sendEmail(email, "Checkmate Password Reset", html);
return msgId;
};
2026-01-15 20:55:01 +00:00
validateRecovery = async (recoveryToken: string) => {
2025-07-30 15:34:03 -07:00
await this.db.recoveryModule.validateRecoveryToken(recoveryToken);
2025-07-23 13:03:57 -07:00
};
2026-01-15 20:55:01 +00:00
resetPassword = async (password: string, recoveryToken: string) => {
2025-07-30 15:34:03 -07:00
const user = await this.db.recoveryModule.resetPassword(password, recoveryToken);
2025-07-23 13:03:57 -07:00
const appSettings = await this.settingsService.getSettings();
const token = this.issueToken(user._doc, appSettings);
return { user, token };
};
2026-01-15 20:55:01 +00:00
deleteUser = async (user: any) => {
2025-07-23 13:03:57 -07:00
const email = user?.email;
if (!email) {
2025-07-25 10:16:29 -07:00
throw this.errorService.createBadRequestError("No email in request");
2025-07-23 13:03:57 -07:00
}
const teamId = user?.teamId;
const userId = user?._id;
if (!teamId) {
2025-07-25 10:16:29 -07:00
throw this.errorService.createBadRequestError("No team ID in request");
2025-07-23 13:03:57 -07:00
}
if (!userId) {
2025-07-25 10:16:29 -07:00
throw this.errorService.createBadRequestError("No user ID in request");
2025-07-23 13:03:57 -07:00
}
const roles = user?.role;
if (roles.includes("demo")) {
2025-07-25 10:16:29 -07:00
throw this.errorService.createBadRequestError("Demo user cannot be deleted");
2025-07-23 13:03:57 -07:00
}
// 1. Find all the monitors associated with the team ID if superadmin
2026-01-15 20:55:01 +00:00
const res = await this.monitorsRepository.findByTeamId(teamId, {});
2025-07-23 13:03:57 -07:00
if (roles.includes("superadmin")) {
// 2. Remove all jobs, delete checks and alerts
2026-01-15 20:55:01 +00:00
res &&
res?.length > 0 &&
2025-07-23 13:03:57 -07:00
(await Promise.all(
2026-01-15 20:55:01 +00:00
res.map(async (monitor) => {
2025-07-23 13:03:57 -07:00
await this.jobQueue.deleteJob(monitor);
})
));
}
// 6. Delete the user by id
2025-07-30 10:41:53 -07:00
await this.db.userModule.deleteUser(userId);
2025-07-23 13:03:57 -07:00
};
getAllUsers = async () => {
2025-07-30 10:41:53 -07:00
const users = await this.db.userModule.getAllUsers();
2025-07-23 13:03:57 -07:00
return users;
};
2026-01-15 20:55:01 +00:00
getUserById = async (roles: any, userId: any) => {
2025-07-30 10:41:53 -07:00
const user = await this.db.userModule.getUserById(roles, userId);
2025-07-23 13:03:57 -07:00
return user;
};
2026-01-15 20:55:01 +00:00
editUserById = async (userId: any, user: any) => {
2025-07-30 10:41:53 -07:00
await this.db.userModule.editUserById(userId, user);
2025-07-23 13:03:57 -07:00
};
2026-01-15 20:55:01 +00:00
setPasswordByUserId = async (userId: any, password: string) => {
2025-10-06 15:43:17 -04:00
const updatedUser = await this.db.userModule.updateUser({ userId: userId, user: { password: password }, file: null });
2025-10-01 11:34:51 -04:00
return updatedUser;
2025-10-02 15:19:42 -04:00
};
2025-07-23 13:03:57 -07:00
}
export default UserService;