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

351 lines
11 KiB
TypeScript
Raw Normal View History

2026-01-21 11:46:49 -08:00
import {
IInvitesRepository,
IMonitorsRepository,
IRecoveryTokensRepository,
IUsersRepository,
ISettingsRepository,
2026-01-21 11:56:05 -08:00
ITeamsRepository,
2026-01-21 11:46:49 -08:00
} from "@/repositories/index.js";
2026-01-16 19:14:03 +00:00
import type { User } from "@/types/index.js";
2026-02-09 18:49:31 +00:00
import { canManageRole, type UserRole } from "@/types/user.js";
2026-01-16 20:29:54 +00:00
import bcrypt from "bcryptjs";
2026-01-16 22:03:35 +00:00
import { AppError } from "@/utils/AppError.js";
2026-01-21 11:46:49 -08:00
import { ISuperSimpleQueue } from "@/service/infrastructure/SuperSimpleQueue/SuperSimpleQueue.js";
2026-01-15 20:55:01 +00:00
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-02-07 21:15:58 +00:00
private hashPassword = (password: string): string => {
const salt = bcrypt.genSaltSync(10);
return bcrypt.hashSync(password, salt);
};
2026-01-15 20:55:01 +00:00
private emailService: any;
private settingsService: any;
private logger: any;
private jwt: any;
2026-01-20 23:06:23 +00:00
private jobQueue: ISuperSimpleQueue;
2026-01-15 20:55:01 +00:00
private crypto: any;
private monitorsRepository: IMonitorsRepository;
2026-01-16 20:29:54 +00:00
private usersRepository: IUsersRepository;
private invitesRepository: IInvitesRepository;
2026-01-16 22:03:35 +00:00
private recoveryTokensRepository: IRecoveryTokensRepository;
2026-01-17 19:08:12 +00:00
private settingsRepository: ISettingsRepository;
2026-01-21 11:56:05 -08:00
private teamsRepository: ITeamsRepository;
2026-01-15 20:55:01 +00:00
constructor({
crypto,
emailService,
settingsService,
logger,
jwt,
jobQueue,
monitorsRepository,
2026-01-16 20:29:54 +00:00
usersRepository,
invitesRepository,
2026-01-16 22:03:35 +00:00
recoveryTokensRepository,
2026-01-17 19:08:12 +00:00
settingsRepository,
2026-01-21 11:46:49 -08:00
teamsRepository,
2026-01-15 20:55:01 +00:00
}: {
crypto: any;
emailService: any;
settingsService: any;
logger: any;
jwt: any;
2026-01-20 23:06:23 +00:00
jobQueue: ISuperSimpleQueue;
2026-01-15 20:55:01 +00:00
monitorsRepository: IMonitorsRepository;
2026-01-16 20:29:54 +00:00
usersRepository: IUsersRepository;
invitesRepository: IInvitesRepository;
2026-01-16 22:03:35 +00:00
recoveryTokensRepository: IRecoveryTokensRepository;
2026-01-17 19:08:12 +00:00
settingsRepository: ISettingsRepository;
2026-01-21 11:56:05 -08:00
teamsRepository: ITeamsRepository;
2026-01-15 20:55:01 +00:00
}) {
2025-07-23 13:03:57 -07:00
this.emailService = emailService;
this.settingsService = settingsService;
this.logger = logger;
this.jwt = jwt;
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;
2026-01-16 20:29:54 +00:00
this.usersRepository = usersRepository;
this.invitesRepository = invitesRepository;
2026-01-16 22:03:35 +00:00
this.recoveryTokensRepository = recoveryTokensRepository;
2026-01-17 19:08:12 +00:00
this.settingsRepository = settingsRepository;
2026-01-21 11:46:49 -08:00
this.teamsRepository = teamsRepository;
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-16 19:14:03 +00:00
registerUser = async (user: Partial<User>, inviteToken: string, 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
2026-01-16 20:29:54 +00:00
const superAdminExists = await this.usersRepository.findSuperAdmin();
2025-07-23 13:03:57 -07:00
if (superAdminExists) {
2026-01-16 20:29:54 +00:00
const invite = await this.invitesRepository.findByTokenAndDelete(inviteToken);
user.role = invite.role ?? ["user"];
2026-01-16 20:29:54 +00:00
user.teamId = invite.teamId;
user.email = invite.email;
2025-07-23 13:03:57 -07:00
} 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");
2026-01-17 19:08:12 +00:00
await this.settingsRepository.update({ jwtSecret });
2026-01-16 20:29:54 +00:00
// Create a new team
2026-01-21 11:46:49 -08:00
if (!user.email) {
throw new AppError({ message: "Email is required for first user", service: SERVICE_NAME, method: "registerUser", status: 400 });
}
const team = await this.teamsRepository.create(user.email);
user.teamId = team.id;
user.role = ["superadmin"];
2025-07-23 13:03:57 -07:00
}
2026-02-07 21:15:58 +00:00
// Hash password before storing
if (user.password) {
user.password = this.hashPassword(user.password);
}
const newUser = await this.usersRepository.create(user, file);
2025-07-23 13:03:57 -07:00
this.logger.debug({
message: "New user created",
service: SERVICE_NAME,
method: "registerUser",
2026-01-16 20:29:54 +00:00
details: newUser.id,
2025-07-23 13:03:57 -07:00
});
2026-01-16 20:29:54 +00:00
delete newUser.profileImage;
delete newUser.avatarImage;
2025-07-23 13:03:57 -07:00
const appSettings = await this.settingsService.getSettings();
2026-01-16 20:29:54 +00:00
const token = this.issueToken(newUser, appSettings);
2025-07-23 13:03:57 -07:00
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-02-09 18:49:31 +00:00
createUser = async (userData: Partial<User>, teamId: string, actorRoles: UserRole[], file: any) => {
// Validate that the creator can assign the requested roles
const targetRoles = userData.role ?? [];
for (const targetRole of targetRoles) {
const canManage = actorRoles.some((actorRole) => canManageRole(actorRole, targetRole));
if (!canManage) {
throw new AppError({
message: "You do not have permission to assign this role",
service: SERVICE_NAME,
method: "createUser",
status: 403,
});
}
}
userData.teamId = teamId;
if (userData.password) {
userData.password = this.hashPassword(userData.password);
}
const newUser = await this.usersRepository.create(userData, file);
this.logger.debug({
message: "New user created by superadmin",
service: SERVICE_NAME,
method: "createUser",
details: newUser.id,
});
newUser.profileImage = undefined;
newUser.avatarImage = undefined;
newUser.password = "";
return newUser;
};
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
2026-01-16 20:29:54 +00:00
const user = await this.usersRepository.findByEmail(email);
2025-07-23 13:03:57 -07:00
// Compare password
2026-01-16 20:29:54 +00:00
const match = await bcrypt.compare(password, user.password);
2025-07-23 13:03:57 -07:00
if (match !== true) {
2026-01-20 23:06:23 +00:00
throw new AppError({ message: "Incorrect password", service: SERVICE_NAME, status: 401 });
2025-07-23 13:03:57 -07:00
}
// Remove password from user object. Should this be abstracted to DB layer?
2026-01-16 20:29:54 +00:00
const userWithoutPassword = { ...user };
userWithoutPassword.password = "";
userWithoutPassword.avatarImage = "";
2025-07-23 13:03:57 -07:00
// 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-16 20:29:54 +00:00
editUser = async (updates: Partial<User & { newPassword?: string }>, 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
2026-01-16 20:29:54 +00:00
const user = await this.usersRepository.findByEmail(currentUser.email);
2025-07-23 13:03:57 -07:00
// Compare passwords
2026-01-16 20:29:54 +00:00
const match = await bcrypt.compare(updates?.password, user.password);
2025-07-23 13:03:57 -07:00
// If not a match, throw a 403
// 403 instead of 401 to avoid triggering axios interceptor
if (!match) {
2026-01-20 23:06:23 +00:00
throw new AppError({ message: "Incorrect current password", service: SERVICE_NAME, status: 403 });
2025-07-23 13:03:57 -07:00
}
// If a match, update the password
2026-02-07 21:15:58 +00:00
updates.password = this.hashPassword(updates.newPassword);
delete updates.newPassword;
2025-07-23 13:03:57 -07:00
}
2026-01-16 20:29:54 +00:00
return await this.usersRepository.updateById(currentUser.id, updates, file);
2025-07-23 13:03:57 -07:00
};
checkSuperadminExists = async () => {
2026-01-16 22:03:35 +00:00
return await this.usersRepository.findSuperAdmin();
2025-07-23 13:03:57 -07:00
};
2026-01-15 20:55:01 +00:00
requestRecovery = async (email: string) => {
2026-01-16 22:41:12 +00:00
const user = await this.usersRepository.findByEmail(email);
2026-01-16 22:03:35 +00:00
// Delete existing tokens
await this.recoveryTokensRepository.deleteManyByEmail(email);
const recoveryToken = await this.recoveryTokensRepository.create(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) => {
2026-01-16 22:03:35 +00:00
// Throws if token not found, validating
await this.recoveryTokensRepository.findByToken(recoveryToken);
2025-07-23 13:03:57 -07:00
};
2026-01-15 20:55:01 +00:00
resetPassword = async (password: string, recoveryToken: string) => {
2026-01-16 22:03:35 +00:00
const existingToken = await this.recoveryTokensRepository.findByToken(recoveryToken);
const existingUser = await this.usersRepository.findByEmail(existingToken.email);
const match = await bcrypt.compare(password, existingUser.password);
if (match === true) {
throw new AppError({ message: "New password cannot be same as old password", service: SERVICE_NAME, status: 400 });
}
2026-02-07 21:15:58 +00:00
const hashedPassword = this.hashPassword(password);
await this.usersRepository.updateById(existingUser.id, { password: hashedPassword }, null);
2026-01-16 22:03:35 +00:00
await this.recoveryTokensRepository.deleteManyByEmail(existingUser.email);
existingUser.password = "";
existingUser.profileImage = undefined;
const token = this.issueToken(existingUser, await this.settingsService.getSettings());
return { user: existingUser, token };
2025-07-23 13:03:57 -07:00
};
2026-01-16 22:41:12 +00:00
deleteUser = async (user: User) => {
2025-07-23 13:03:57 -07:00
const email = user?.email;
if (!email) {
2026-01-20 23:06:23 +00:00
throw new AppError({ message: "No email in request", service: SERVICE_NAME, method: "deleteUser", status: 400 });
2025-07-23 13:03:57 -07:00
}
const teamId = user?.teamId;
2026-01-16 22:41:12 +00:00
const userId = user?.id;
2025-07-23 13:03:57 -07:00
if (!teamId) {
2026-01-20 23:06:23 +00:00
throw new AppError({ message: "No team ID in request", service: SERVICE_NAME, method: "deleteUser", status: 400 });
2025-07-23 13:03:57 -07:00
}
if (!userId) {
2026-01-20 23:06:23 +00:00
throw new AppError({ message: "No user ID in request", service: SERVICE_NAME, method: "deleteUser", status: 400 });
2025-07-23 13:03:57 -07:00
}
const roles = user?.role;
if (roles.includes("demo")) {
2026-01-20 23:06:23 +00:00
throw new AppError({ message: "Demo user cannot be deleted", service: SERVICE_NAME, method: "deleteUser", status: 400 });
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) => {
2026-01-20 23:06:23 +00:00
await this.jobQueue.deleteJob(monitor.id);
2025-07-23 13:03:57 -07:00
})
));
}
// 6. Delete the user by id
2026-01-16 22:41:12 +00:00
await this.usersRepository.deleteById(userId);
2025-07-23 13:03:57 -07:00
};
getAllUsers = async () => {
2026-01-16 22:41:12 +00:00
return await this.usersRepository.findAll();
2025-07-23 13:03:57 -07:00
};
2026-01-15 20:55:01 +00:00
getUserById = async (roles: any, userId: any) => {
2026-01-16 22:41:12 +00:00
if (!roles.includes("superadmin")) {
throw new AppError({ message: "User is not a superadmin", service: SERVICE_NAME, status: 403 });
}
const user = await this.usersRepository.findById(userId);
2025-07-23 13:03:57 -07:00
return user;
};
2026-01-16 22:41:12 +00:00
editUserById = async (userId: any, patch: Partial<User>) => {
await this.usersRepository.updateById(userId, patch, null);
2025-07-23 13:03:57 -07:00
};
2026-01-16 22:41:12 +00:00
2026-01-15 20:55:01 +00:00
setPasswordByUserId = async (userId: any, password: string) => {
2026-02-07 21:15:58 +00:00
const hashedPassword = this.hashPassword(password);
const updatedUser = await this.usersRepository.updateById(userId, { password: hashedPassword }, 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;