Files
Checkmate/server/src/domain/users/user.service.ts
T

409 lines
14 KiB
TypeScript
Raw Normal View History

2026-06-09 12:34:15 -07:00
import { ISettingsRepository } from "@/domain/app-settings/app-settings-repository.interface.js";
import { IInvitesRepository } from "@/domain/invites/invite.repository.interface.js";
import { IRecoveryTokensRepository } from "@/domain/recovery-tokens/recovery-token.repository.interface.js";
import { ITeamsRepository } from "@/domain/teams/team.repository.interface.js";
import { IUsersRepository } from "@/domain/users/user.repository.interface.js";
import { IMonitorsRepository } from "@/domain/monitors/monitor.repository.interface.js";
import type { User } from "@/domain/users/user.type.js";
import { canManageRole, type UserRole } from "@/domain/users/user.type.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-06-09 12:34:15 -07:00
import { IEmailService } from "@/service/emailService.js";
import { EnvConfig, ISettingsService } from "@/domain/app-settings/app-settings.service.js";
2026-03-05 14:46:28 -08:00
import { ILogger } from "@/utils/logger.js";
import jwt from "jsonwebtoken";
import crypto from "crypto";
2026-06-10 09:30:14 -07:00
import { IWorker } from "@/worker/worker.interface.js";
type CryptoType = typeof crypto;
2026-03-05 14:46:28 -08:00
type JwtType = typeof jwt;
2025-07-23 13:03:57 -07:00
const SERVICE_NAME = "userService";
2026-03-05 14:46:28 -08:00
export interface IUserService {
issueToken(payload: Partial<User>, appSettings: EnvConfig): string;
registerUser(user: Partial<User>, inviteToken: string, file: Express.Multer.File | null): Promise<{ user: User; token: string }>;
createUser(userData: Partial<User>, teamId: string, actorRoles: UserRole[], file: Express.Multer.File | null): Promise<User>;
2026-03-05 14:46:28 -08:00
loginUser(email: string, password: string): Promise<{ user: User; token: string }>;
editUser(
updates: Partial<User & { newPassword?: string }>,
file: Express.Multer.File | null,
currentUserId: string,
currentUserEmail: string
): Promise<User>;
2026-03-05 14:46:28 -08:00
checkSuperadminExists(): Promise<boolean>;
requestRecovery(email: string): Promise<string | false | undefined>;
validateRecovery(recoveryToken: string): Promise<void>;
resetPassword(password: string, recoveryToken: string): Promise<{ user: User; token: string }>;
deleteUser(params: { userId: string; teamId: string; roles: UserRole[] }): Promise<void>;
deleteUserById(params: { actorId: string; actorTeamId: string; actorRoles: UserRole[]; targetUserId: string }): Promise<void>;
2026-03-05 14:46:28 -08:00
getAllUsers(): Promise<User[]>;
getUserById(roles: UserRole[], userId: string): Promise<User>;
editUserById(userId: string, patch: Partial<User>): Promise<void>;
setPasswordByUserId(userId: string, password: string): Promise<User>;
}
export class UserService implements IUserService {
2025-07-23 13:03:57 -07:00
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-03-05 14:46:28 -08:00
private emailService: IEmailService;
private settingsService: ISettingsService;
private logger: ILogger;
private jwt: JwtType;
2026-06-10 09:30:14 -07:00
private worker: IWorker;
private crypto: CryptoType;
2026-01-15 20:55:01 +00:00
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,
2026-06-10 09:30:14 -07:00
worker,
2026-01-15 20:55:01 +00:00
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: CryptoType;
2026-03-05 14:46:28 -08:00
emailService: IEmailService;
settingsService: ISettingsService;
logger: ILogger;
jwt: JwtType;
2026-06-10 09:30:14 -07:00
worker: IWorker;
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;
2026-06-10 09:30:14 -07:00
this.worker = worker;
2025-07-27 19:51:39 -07:00
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;
}
issueToken = (payload: Partial<User>, appSettings: EnvConfig) => {
2026-04-10 10:59:48 -07:00
return this.jwt.sign(payload, appSettings.jwtSecret, { expiresIn: appSettings.jwtTTL });
2025-07-23 13:03:57 -07:00
};
registerUser = async (user: Partial<User>, inviteToken: string, file: Express.Multer.File | null) => {
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 as User, file);
2025-07-23 13:03:57 -07:00
this.logger.debug({
message: "New user created",
service: SERVICE_NAME,
method: "registerUser",
2026-03-06 19:48:19 +11:00
details: { userId: 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-03-05 14:46:28 -08:00
if (!html) {
throw new Error("Failed to build welcome email HTML");
}
this.emailService.sendEmail(newUser.email, "Welcome to Uptime Monitor", html).catch((error: unknown) => {
2025-07-23 13:03:57 -07:00
this.logger.warn({
2026-03-05 14:46:28 -08:00
message: error instanceof Error ? error.message : "Unknown error",
2025-07-23 13:03:57 -07:00
service: SERVICE_NAME,
method: "registerUser",
2026-03-05 14:46:28 -08:00
stack: error instanceof Error ? error.stack : undefined,
2025-07-23 13:03:57 -07:00
});
});
2026-03-05 14:46:28 -08:00
} catch (error: unknown) {
2025-07-23 13:03:57 -07:00
this.logger.warn({
2026-03-05 14:46:28 -08:00
message: error instanceof Error ? error.message : "Unknown error",
2025-07-23 13:03:57 -07:00
service: SERVICE_NAME,
method: "registerUser",
2026-03-05 14:46:28 -08:00
stack: error instanceof Error ? error.stack : undefined,
2025-07-23 13:03:57 -07:00
});
}
return { user: newUser, token };
};
createUser = async (userData: Partial<User>, teamId: string, actorRoles: UserRole[], file: Express.Multer.File | null) => {
2026-02-09 18:49:31 +00:00
// 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 as User, file);
2026-02-09 18:49:31 +00:00
this.logger.debug({
message: "New user created by superadmin",
service: SERVICE_NAME,
method: "createUser",
2026-03-06 19:48:19 +11:00
details: { userId: newUser.id },
2026-02-09 18:49:31 +00:00
});
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 };
};
editUser = async (
updates: Partial<User & { newPassword?: string }>,
file: Express.Multer.File | null,
currentUserId: string,
currentUserEmail: string
) => {
2025-07-23 13:03:57 -07:00
// Change Password check
2026-04-10 10:59:48 -07:00
if (updates.password && updates.newPassword) {
updates.email = currentUserEmail;
const user = await this.usersRepository.findByEmail(currentUserEmail);
2026-04-10 10:59:48 -07: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
}
return await this.usersRepository.updateById(currentUserId, 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;
2026-03-06 19:48:19 +11:00
const settings = this.settingsService.getSettings();
2026-04-10 10:59:48 -07:00
const url = `${settings.clientHost}/set-new-password/${recoveryToken.token}`;
2025-07-23 13:03:57 -07:00
const html = await this.emailService.buildEmail("passwordResetTemplate", {
name,
email,
url,
});
if (!html) {
2026-03-06 09:14:12 -08:00
throw new AppError({
message: "Failed to build password reset email HTML",
service: SERVICE_NAME,
method: "requestRecovery",
status: 500,
});
}
2025-07-23 13:03:57 -07:00
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
};
deleteUser = async ({ userId, teamId, roles }: { userId: string; teamId: string; roles: UserRole[] }) => {
2025-07-23 13:03:57 -07:00
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
}
if (roles.includes("superadmin")) {
2026-04-10 10:59:48 -07:00
const monitors = await this.monitorsRepository.findByTeamId(teamId, {});
if (monitors) {
2026-06-10 09:30:14 -07:00
await Promise.all(monitors.map((monitor) => this.worker.deleteJob(monitor)));
2026-03-05 14:46:28 -08:00
}
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
};
deleteUserById = async ({
actorId,
actorRoles,
actorTeamId,
targetUserId,
}: {
actorId: string;
actorTeamId: string;
actorRoles: UserRole[];
targetUserId: string;
}) => {
if (actorId === targetUserId) {
2026-03-06 14:18:27 -05:00
throw new AppError({ message: "Cannot delete your own account from here", service: SERVICE_NAME, method: "deleteUserById", status: 400 });
}
const targetUser = await this.usersRepository.findById(targetUserId);
if (targetUser.teamId !== actorTeamId) {
2026-03-06 14:18:27 -05:00
throw new AppError({ message: "User is not on your team", service: SERVICE_NAME, method: "deleteUserById", status: 403 });
}
if (targetUser.role.includes("demo")) {
throw new AppError({ message: "Demo user cannot be deleted", service: SERVICE_NAME, method: "deleteUserById", status: 400 });
}
const targetRoles = targetUser.role;
// Check actor can manage all of target's roles
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 remove this user",
service: SERVICE_NAME,
method: "deleteUserById",
status: 403,
});
}
}
await this.usersRepository.deleteById(targetUserId);
this.logger.info({
message: `User ${targetUserId} deleted by ${actorId}`,
2026-03-06 14:18:27 -05:00
service: SERVICE_NAME,
method: "deleteUserById",
});
};
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
};
getUserById = async (roles: UserRole[], userId: string) => {
2026-03-06 14:18:27 -05:00
if (!roles.includes("superadmin") && !roles.includes("admin")) {
throw new AppError({ message: "Insufficient permissions", service: SERVICE_NAME, status: 403 });
2026-01-16 22:41:12 +00:00
}
2026-04-10 10:59:48 -07:00
return await this.usersRepository.findById(userId);
2025-07-23 13:03:57 -07:00
};
editUserById = async (userId: string, patch: Partial<User>) => {
2026-01-16 22:41:12 +00:00
await this.usersRepository.updateById(userId, patch, null);
2025-07-23 13:03:57 -07:00
};
2026-01-16 22:41:12 +00:00
setPasswordByUserId = async (userId: string, 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
}