Merge pull request #3149 from bluewave-labs/feat/user-service-ts
feat/user service ts
This commit is contained in:
42 files changed
+851
-366
No files matched your search
@@ -1,11 +1,14 @@
|
||||
import { IMonitorsRepository } from "@/repositories/index.js";
|
||||
import { IInvitesRepository, IMonitorsRepository, IRecoveryTokensRepository, IUsersRepository, ISettingsRepository } from "@/repositories/index.js";
|
||||
import Team from "@/db/models/Team.js";
|
||||
import type { User } from "@/types/index.js";
|
||||
import bcrypt from "bcryptjs";
|
||||
import { AppError } from "@/utils/AppError.js";
|
||||
|
||||
const SERVICE_NAME = "userService";
|
||||
|
||||
class UserService {
|
||||
static SERVICE_NAME = SERVICE_NAME;
|
||||
|
||||
private db: any;
|
||||
private emailService: any;
|
||||
private settingsService: any;
|
||||
private logger: any;
|
||||
@@ -15,10 +18,13 @@ class UserService {
|
||||
private jobQueue: any;
|
||||
private crypto: any;
|
||||
private monitorsRepository: IMonitorsRepository;
|
||||
private usersRepository: IUsersRepository;
|
||||
private invitesRepository: IInvitesRepository;
|
||||
private recoveryTokensRepository: IRecoveryTokensRepository;
|
||||
private settingsRepository: ISettingsRepository;
|
||||
|
||||
constructor({
|
||||
crypto,
|
||||
db,
|
||||
emailService,
|
||||
settingsService,
|
||||
logger,
|
||||
@@ -27,9 +33,12 @@ class UserService {
|
||||
errorService,
|
||||
jobQueue,
|
||||
monitorsRepository,
|
||||
usersRepository,
|
||||
invitesRepository,
|
||||
recoveryTokensRepository,
|
||||
settingsRepository,
|
||||
}: {
|
||||
crypto: any;
|
||||
db: any;
|
||||
emailService: any;
|
||||
settingsService: any;
|
||||
logger: any;
|
||||
@@ -38,8 +47,11 @@ class UserService {
|
||||
errorService: any;
|
||||
jobQueue: any;
|
||||
monitorsRepository: IMonitorsRepository;
|
||||
usersRepository: IUsersRepository;
|
||||
invitesRepository: IInvitesRepository;
|
||||
recoveryTokensRepository: IRecoveryTokensRepository;
|
||||
settingsRepository: ISettingsRepository;
|
||||
}) {
|
||||
this.db = db;
|
||||
this.emailService = emailService;
|
||||
this.settingsService = settingsService;
|
||||
this.logger = logger;
|
||||
@@ -49,6 +61,10 @@ class UserService {
|
||||
this.jobQueue = jobQueue;
|
||||
this.crypto = crypto;
|
||||
this.monitorsRepository = monitorsRepository;
|
||||
this.usersRepository = usersRepository;
|
||||
this.invitesRepository = invitesRepository;
|
||||
this.recoveryTokensRepository = recoveryTokensRepository;
|
||||
this.settingsRepository = settingsRepository;
|
||||
}
|
||||
|
||||
get serviceName() {
|
||||
@@ -62,36 +78,40 @@ class UserService {
|
||||
return this.jwt.sign(payloadData, tokenSecret, { expiresIn: tokenTTL });
|
||||
};
|
||||
|
||||
registerUser = async (user: any, file: any) => {
|
||||
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(user.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 });
|
||||
await this.settingsRepository.update({ 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", {
|
||||
@@ -119,17 +139,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();
|
||||
@@ -139,16 +160,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) {
|
||||
@@ -158,18 +179,19 @@ 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 () => {
|
||||
const superAdminExists = await this.db.userModule.checkSuperadmin();
|
||||
return superAdminExists;
|
||||
return await this.usersRepository.findSuperAdmin();
|
||||
};
|
||||
|
||||
requestRecovery = async (email: string) => {
|
||||
const user = await this.db.userModule.getUserByEmail(email);
|
||||
const recoveryToken = await this.db.recoveryModule.requestRecoveryToken(email);
|
||||
const user = await this.usersRepository.findByEmail(email);
|
||||
|
||||
// Delete existing tokens
|
||||
await this.recoveryTokensRepository.deleteManyByEmail(email);
|
||||
const recoveryToken = await this.recoveryTokensRepository.create(email);
|
||||
const name = user.firstName;
|
||||
const { clientHost } = this.settingsService.getSettings();
|
||||
const url = `${clientHost}/set-new-password/${recoveryToken.token}`;
|
||||
@@ -184,24 +206,39 @@ class UserService {
|
||||
};
|
||||
|
||||
validateRecovery = async (recoveryToken: string) => {
|
||||
await this.db.recoveryModule.validateRecoveryToken(recoveryToken);
|
||||
// Throws if token not found, validating
|
||||
await this.recoveryTokensRepository.findByToken(recoveryToken);
|
||||
};
|
||||
|
||||
resetPassword = async (password: string, recoveryToken: string) => {
|
||||
const user = await this.db.recoveryModule.resetPassword(password, recoveryToken);
|
||||
const appSettings = await this.settingsService.getSettings();
|
||||
const token = this.issueToken(user._doc, appSettings);
|
||||
return { user, token };
|
||||
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 });
|
||||
}
|
||||
|
||||
existingUser.password = password;
|
||||
await this.usersRepository.updateById(existingUser.id, existingUser, null);
|
||||
await this.recoveryTokensRepository.deleteManyByEmail(existingUser.email);
|
||||
|
||||
existingUser.password = "";
|
||||
existingUser.profileImage = undefined;
|
||||
|
||||
const token = this.issueToken(existingUser, await this.settingsService.getSettings());
|
||||
|
||||
return { user: existingUser, token };
|
||||
};
|
||||
|
||||
deleteUser = async (user: any) => {
|
||||
deleteUser = async (user: User) => {
|
||||
const email = user?.email;
|
||||
if (!email) {
|
||||
throw this.errorService.createBadRequestError("No email in request");
|
||||
}
|
||||
|
||||
const teamId = user?.teamId;
|
||||
const userId = user?._id;
|
||||
const userId = user?.id;
|
||||
|
||||
if (!teamId) {
|
||||
throw this.errorService.createBadRequestError("No team ID in request");
|
||||
@@ -230,24 +267,28 @@ class UserService {
|
||||
));
|
||||
}
|
||||
// 6. Delete the user by id
|
||||
await this.db.userModule.deleteUser(userId);
|
||||
await this.usersRepository.deleteById(userId);
|
||||
};
|
||||
|
||||
getAllUsers = async () => {
|
||||
const users = await this.db.userModule.getAllUsers();
|
||||
return users;
|
||||
return await this.usersRepository.findAll();
|
||||
};
|
||||
|
||||
getUserById = async (roles: any, userId: any) => {
|
||||
const user = await this.db.userModule.getUserById(roles, userId);
|
||||
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);
|
||||
|
||||
return user;
|
||||
};
|
||||
|
||||
editUserById = async (userId: any, user: any) => {
|
||||
await this.db.userModule.editUserById(userId, user);
|
||||
editUserById = async (userId: any, patch: Partial<User>) => {
|
||||
await this.usersRepository.updateById(userId, patch, null);
|
||||
};
|
||||
|
||||
setPasswordByUserId = async (userId: any, password: string) => {
|
||||
const updatedUser = await this.db.userModule.updateUser({ userId: userId, user: { password: password }, file: null });
|
||||
const updatedUser = await this.usersRepository.updateById(userId, { password }, null);
|
||||
return updatedUser;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -46,7 +46,7 @@ class EmailService {
|
||||
*/
|
||||
this.loadTemplate = (templateName) => {
|
||||
try {
|
||||
const templatePath = this.path.join(__dirname, `../../../templates/${templateName}.mjml`);
|
||||
const templatePath = this.path.join(__dirname, `../../templates/${templateName}.mjml`);
|
||||
const templateContent = this.fs.readFileSync(templatePath, "utf8");
|
||||
return this.compile(templateContent);
|
||||
} catch (error) {
|
||||
|
||||
Reference in new issue
Block a user