update user refactor

This commit is contained in:
Alex Holliday committed 2026-01-16 20:29:54 +00:00
1 parent 88bb8ef2d3
commit cb5b8e0673
16 files changed
+293 -80

No files matched your search

+35 -21
View File
@@ -1,5 +1,7 @@
import { IMonitorsRepository } from "@/repositories/index.js";
import { IInvitesRepository, IMonitorsRepository, IUsersRepository } from "@/repositories/index.js";
import Team from "@/db/models/Team.js";
import type { User } from "@/types/index.js";
import bcrypt from "bcryptjs";
const SERVICE_NAME = "userService";
@@ -16,6 +18,8 @@ class UserService {
private jobQueue: any;
private crypto: any;
private monitorsRepository: IMonitorsRepository;
private usersRepository: IUsersRepository;
private invitesRepository: IInvitesRepository;
constructor({
crypto,
@@ -28,6 +32,8 @@ class UserService {
errorService,
jobQueue,
monitorsRepository,
usersRepository,
invitesRepository,
}: {
crypto: any;
db: any;
@@ -39,6 +45,8 @@ class UserService {
errorService: any;
jobQueue: any;
monitorsRepository: IMonitorsRepository;
usersRepository: IUsersRepository;
invitesRepository: IInvitesRepository;
}) {
this.db = db;
this.emailService = emailService;
@@ -50,6 +58,8 @@ class UserService {
this.jobQueue = jobQueue;
this.crypto = crypto;
this.monitorsRepository = monitorsRepository;
this.usersRepository = usersRepository;
this.invitesRepository = invitesRepository;
}
get serviceName() {
@@ -66,33 +76,37 @@ class UserService {
registerUser = async (user: Partial<User>, inviteToken: string, file: any) => {
// Create a new user
// If superAdmin exists, a token should be attached to all further register requests
const superAdminExists = await this.db.userModule.checkSuperadmin();
const superAdminExists = await this.usersRepository.findSuperAdmin();
if (superAdminExists) {
const invitedUser = await this.db.inviteModule.getInviteTokenAndDelete(inviteToken);
user.role = invitedUser.role;
user.teamId = invitedUser.teamId;
const invite = await this.invitesRepository.findByTokenAndDelete(inviteToken);
user.role = invite.role;
user.teamId = invite.teamId;
} else {
// This is the first account, create JWT secret to use if one is not supplied by env
const jwtSecret = this.crypto.randomBytes(64).toString("hex");
await this.db.settingsModule.updateAppSettings({ jwtSecret });
// Create a new team
const team = new Team({
email: user.email,
});
user.teamId = team._id;
}
const newUser = await this.db.userModule.insertUser({ ...user }, file);
const newUser = await this.usersRepository.create({ ...user }, file);
this.logger.debug({
message: "New user created",
service: SERVICE_NAME,
method: "registerUser",
details: newUser._id,
details: newUser.id,
});
const userForToken = { ...newUser._doc };
delete userForToken.profileImage;
delete userForToken.avatarImage;
delete newUser.profileImage;
delete newUser.avatarImage;
const appSettings = await this.settingsService.getSettings();
const token = this.issueToken(userForToken, appSettings);
const token = this.issueToken(newUser, appSettings);
try {
const html = await this.emailService.buildEmail("welcomeEmailTemplate", {
@@ -120,17 +134,18 @@ class UserService {
loginUser = async (email: string, password: string) => {
// Check if user exists
const user = await this.db.userModule.getUserByEmail(email);
const user = await this.usersRepository.findByEmail(email);
// Compare password
const match = await user.comparePassword(password);
const match = await bcrypt.compare(password, user.password);
if (match !== true) {
throw this.errorService.createAuthenticationError(this.stringService.authIncorrectPassword);
}
// Remove password from user object. Should this be abstracted to DB layer?
const userWithoutPassword = { ...user._doc };
delete userWithoutPassword.password;
delete userWithoutPassword.avatarImage;
const userWithoutPassword = { ...user };
userWithoutPassword.password = "";
userWithoutPassword.avatarImage = "";
// Happy path, return token
const appSettings = await this.settingsService.getSettings();
@@ -140,16 +155,16 @@ class UserService {
return { user: userWithoutPassword, token };
};
editUser = async (updates: any, file: any, currentUser: any) => {
editUser = async (updates: Partial<User & { newPassword?: string }>, file: any, currentUser: any) => {
// 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
const user = await this.db.userModule.getUserByEmail(currentUser.email);
const user = await this.usersRepository.findByEmail(currentUser.email);
// Compare passwords
const match = await user.comparePassword(updates?.password);
const match = await bcrypt.compare(updates?.password, user.password);
// If not a match, throw a 403
// 403 instead of 401 to avoid triggering axios interceptor
if (!match) {
@@ -159,8 +174,7 @@ class UserService {
updates.password = updates.newPassword;
}
const updatedUser = await this.db.userModule.updateUser({ userId: currentUser?._id, user: updates, file: file });
return updatedUser;
return await this.usersRepository.updateById(currentUser.id, updates, file);
};
checkSuperadminExists = async () => {