Files
vitfit-r2/V2/app/modules/users/service.js
T
2026-06-13 08:03:45 -04:00

132 lines
5.2 KiB
JavaScript

'use strict';
const bcrypt = require('bcryptjs');
const { Op } = require('sequelize');
const { AppError } = require('../../core/errors');
const { log: auditLog } = require('../../core/audit');
const BCRYPT_ROUNDS = 12;
async function getUsers(models, orgId, { role, isActive, page = 1, limit = 50 } = {}) {
const where = { organizationId: orgId };
if (role) where.role = role;
if (isActive != null) where.isActive = isActive === 'true' || isActive === true;
const offset = (page - 1) * limit;
const { rows, count } = await models.User.findAndCountAll({ where, limit, offset, order: [['createdAt', 'ASC']] });
return { rows, count };
}
async function getUserById(models, id, orgId) {
const user = await models.User.findOne({ where: { id, organizationId: orgId } });
if (!user) throw new AppError('NOT_FOUND', 'User not found.', 404);
return user;
}
async function createUser(models, req, orgId, { username, email, firstName, lastName, password, role }) {
if (role === 'SystemAdmin') {
throw new AppError('AUTH_FORBIDDEN', 'Cannot create SystemAdmin accounts via this endpoint.', 403);
}
const hash = await bcrypt.hash(password, BCRYPT_ROUNDS);
let user;
try {
user = await models.User.create({ organizationId: orgId, username, email, firstName, lastName, password: hash, role });
} catch (err) {
if (err.name === 'SequelizeUniqueConstraintError') {
throw new AppError('CONFLICT', 'Username already exists.', 409, 'username');
}
throw err;
}
await auditLog(req, 'user.create', 'user', user.id, { username, role });
return user.toPublic();
}
async function deactivateUser(models, req, targetId, orgId) {
const user = await getUserById(models, targetId, orgId);
if (user.role === 'Owner') {
const ownerCount = await models.User.count({ where: { organizationId: orgId, role: 'Owner', isActive: true } });
if (ownerCount <= 1) throw new AppError('LAST_OWNER_PROTECTED', 'Cannot deactivate the last Owner.', 400);
}
await user.update({ isActive: false });
await models.DeviceToken.update({ isRevoked: true }, { where: { userId: targetId } });
await auditLog(req, 'user.deactivate', 'user', targetId, {});
}
async function changeRole(models, req, targetId, newRole, orgId, actorId) {
const user = await getUserById(models, targetId, orgId);
if (actorId === targetId) {
throw new AppError('AUTH_FORBIDDEN', 'You cannot change your own role.', 403);
}
if (user.role === 'Owner' && newRole !== 'Owner') {
const ownerCount = await models.User.count({ where: { organizationId: orgId, role: 'Owner', isActive: true } });
if (ownerCount <= 1) throw new AppError('LAST_OWNER_PROTECTED', 'Cannot change the role of the last Owner.', 400);
}
await user.update({ role: newRole });
await auditLog(req, 'user.role.change', 'user', targetId, { from: user.role, to: newRole });
return user.toPublic();
}
async function resetPassword(models, req, targetId, newPassword, orgId) {
await getUserById(models, targetId, orgId); // 404 guard
const hash = await bcrypt.hash(newPassword, BCRYPT_ROUNDS);
await models.User.update(
{ password: hash, passwordChangedAt: new Date() },
{ where: { id: targetId } }
);
await models.DeviceToken.update({ isRevoked: true }, { where: { userId: targetId } });
await auditLog(req, 'user.password.reset', 'user', targetId, {});
}
async function updateProfile(models, req, userId, data) {
const user = await models.User.findByPk(userId);
if (!user) throw new AppError('NOT_FOUND', 'User not found.', 404);
const before = { firstName: user.firstName, lastName: user.lastName, email: user.email };
await user.update(data);
await auditLog(req, 'user.profile.update', 'user', userId, { before, after: data });
return user.toPublic();
}
async function changeOwnPassword(models, req, userId, currentPassword, newPassword) {
const user = await models.User.unscoped().findByPk(userId, {
attributes: ['id', 'password', 'organizationId'],
});
const valid = await bcrypt.compare(currentPassword, user.password);
if (!valid) throw new AppError('AUTH_FORBIDDEN', 'Current password is incorrect.', 401);
const hash = await bcrypt.hash(newPassword, BCRYPT_ROUNDS);
await models.User.update(
{ password: hash, passwordChangedAt: new Date() },
{ where: { id: userId } }
);
await models.DeviceToken.update({ isRevoked: true }, { where: { userId } });
await auditLog(req, 'user.password.change', 'user', userId, {});
}
async function getDeviceTokens(models, userId, orgId) {
return models.DeviceToken.findAll({
where: { userId, organizationId: orgId, isRevoked: false },
attributes: ['id', 'deviceName', 'deviceType', 'lastUsedAt', 'expiresAt'],
order: [['createdAt', 'DESC']],
});
}
async function revokeDeviceToken(models, req, tokenId, userId, orgId) {
const token = await models.DeviceToken.findOne({ where: { id: tokenId, userId, organizationId: orgId } });
if (!token) throw new AppError('NOT_FOUND', 'Device token not found.', 404);
await token.update({ isRevoked: true });
await auditLog(req, 'auth.device.revoked', 'device_token', tokenId, {});
}
module.exports = { getUsers, getUserById, createUser, deactivateUser, changeRole, resetPassword, updateProfile, changeOwnPassword, getDeviceTokens, revokeDeviceToken };