Initial commit: teaching institution management API.
Express/MongoDB backend with JWT auth, RBAC, S3 uploads, notifications, and scheduled jobs.
This commit is contained in:
@@ -0,0 +1,232 @@
|
||||
// /components/users/userService.js
|
||||
'use strict';
|
||||
|
||||
const User = require('./userModel');
|
||||
const Role = require('../roles/roleModel');
|
||||
const bcrypt = require('bcryptjs');
|
||||
const AppError = require('../../utils/AppError');
|
||||
const { calculateMeta } = require('../../utils/pagination');
|
||||
const { generateUsername, generateSimplePassword } = require('../../utils/credentials');
|
||||
const { sendAccountCreatedSms } = require('../../utils/senders/smsMessages');
|
||||
const logger = require('../../utils/logger');
|
||||
|
||||
const POPULATE_ROLE = { path: 'role', select: 'name permissions' };
|
||||
const SAFE_FIELDS = '-passwordHash -refreshTokens';
|
||||
const ALLOWED_MESSENGERS = ['Bale', 'WhatsApp', 'Telegram', 'SMS', 'Email'];
|
||||
|
||||
const normalizePreferredMessengers = (value) => {
|
||||
if (value == null || value === '') return undefined;
|
||||
const list = Array.isArray(value) ? value : [value];
|
||||
const cleaned = [...new Set(list.map(String).filter((v) => ALLOWED_MESSENGERS.includes(v)))];
|
||||
return cleaned;
|
||||
};
|
||||
|
||||
const allocateUniqueUsername = async (preferred) => {
|
||||
let username = preferred && String(preferred).trim();
|
||||
if (username) {
|
||||
const exists = await User.exists({ username });
|
||||
if (exists) throw new AppError('USER_ALREADY_EXISTS', null, 'Username already exists');
|
||||
return username;
|
||||
}
|
||||
|
||||
for (let attempt = 0; attempt < 12; attempt += 1) {
|
||||
username = generateUsername();
|
||||
const exists = await User.exists({ username });
|
||||
if (!exists) return username;
|
||||
}
|
||||
throw new AppError('INTERNAL_SERVER_ERROR', null, 'Could not generate a unique username');
|
||||
};
|
||||
|
||||
const signUp = async (body) => {
|
||||
const { name, surname, nationalId, nationalIdCode, phoneNumber, phone, username, password, email, address, preferredMessenger } = body;
|
||||
|
||||
const userRole = await Role.findOne({ name: 'User' });
|
||||
if (!userRole) throw new AppError('DEFAULT_ROLE_NOT_FOUND');
|
||||
|
||||
const passwordHash = await bcrypt.hash(password, 10);
|
||||
const user = await User.create({
|
||||
name,
|
||||
surname,
|
||||
nationalIdCode: nationalIdCode || nationalId,
|
||||
phoneNumber: phoneNumber || phone,
|
||||
username,
|
||||
passwordHash,
|
||||
email,
|
||||
address,
|
||||
preferredMessenger: normalizePreferredMessengers(preferredMessenger),
|
||||
role: userRole._id
|
||||
});
|
||||
|
||||
return user.populate(POPULATE_ROLE);
|
||||
};
|
||||
|
||||
const getUserById = async (id) => {
|
||||
const user = await User.findById(id).select(SAFE_FIELDS).populate(POPULATE_ROLE).lean();
|
||||
if (!user) throw new AppError('USER_NOT_FOUND');
|
||||
return user;
|
||||
};
|
||||
|
||||
const getAllUsers = async (query) => {
|
||||
const page = parseInt(query.page) || 1;
|
||||
const limit = Math.min(parseInt(query.limit) || 20, 200);
|
||||
const skip = (page - 1) * limit;
|
||||
|
||||
const filter = {};
|
||||
if (query.search) {
|
||||
filter.$or = [
|
||||
{ name: new RegExp(query.search, 'i') },
|
||||
{ surname: new RegExp(query.search, 'i') },
|
||||
{ username: new RegExp(query.search, 'i') }
|
||||
];
|
||||
}
|
||||
if (query.isActive !== undefined) filter.isActive = query.isActive === 'true';
|
||||
|
||||
const [items, total] = await Promise.all([
|
||||
User.find(filter).select(SAFE_FIELDS).populate(POPULATE_ROLE).skip(skip).limit(limit).sort({ createdAt: -1 }).lean(),
|
||||
User.countDocuments(filter)
|
||||
]);
|
||||
|
||||
return { data: items, meta: calculateMeta(total, page, limit) };
|
||||
};
|
||||
|
||||
const searchUsers = async (query) => getAllUsers(query);
|
||||
|
||||
const createUserAdmin = async (body) => {
|
||||
const {
|
||||
name,
|
||||
surname,
|
||||
nationalIdCode,
|
||||
nationalId,
|
||||
phoneNumber,
|
||||
phone,
|
||||
username: requestedUsername,
|
||||
password: requestedPassword,
|
||||
email,
|
||||
roleId,
|
||||
role,
|
||||
address,
|
||||
preferredMessenger,
|
||||
} = body;
|
||||
|
||||
let roleObj = null;
|
||||
if (roleId || role) {
|
||||
roleObj = await Role.findById(roleId || role);
|
||||
}
|
||||
if (!roleObj) {
|
||||
roleObj = await Role.findOne({ name: 'User' });
|
||||
}
|
||||
if (!roleObj) throw new AppError('DEFAULT_ROLE_NOT_FOUND');
|
||||
|
||||
const plainPassword = (requestedPassword && String(requestedPassword).trim()) || generateSimplePassword();
|
||||
const username = await allocateUniqueUsername(requestedUsername);
|
||||
const passwordHash = await bcrypt.hash(plainPassword, 10);
|
||||
const resolvedPhone = phoneNumber || phone;
|
||||
|
||||
const user = await User.create({
|
||||
name,
|
||||
surname,
|
||||
nationalIdCode: nationalIdCode || nationalId,
|
||||
phoneNumber: resolvedPhone,
|
||||
username,
|
||||
passwordHash,
|
||||
email,
|
||||
address,
|
||||
preferredMessenger: normalizePreferredMessengers(preferredMessenger),
|
||||
role: roleObj._id,
|
||||
});
|
||||
|
||||
try {
|
||||
await sendAccountCreatedSms(resolvedPhone, username, plainPassword);
|
||||
} catch (err) {
|
||||
logger.error(`[createUserAdmin] Account SMS failed for ${resolvedPhone}: ${err.message}`);
|
||||
}
|
||||
|
||||
const created = await User.findById(user._id).select(SAFE_FIELDS).populate(POPULATE_ROLE).lean();
|
||||
return {
|
||||
...created,
|
||||
generatedCredentials: {
|
||||
username,
|
||||
password: plainPassword,
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const updateUser = async (id, body) => {
|
||||
const {
|
||||
password,
|
||||
nationalId,
|
||||
nationalIdCode,
|
||||
phone,
|
||||
phoneNumber,
|
||||
roleId,
|
||||
role,
|
||||
username,
|
||||
passwordHash,
|
||||
refreshTokens,
|
||||
preferredMessenger,
|
||||
_id,
|
||||
id: bodyId,
|
||||
createdAt,
|
||||
updatedAt,
|
||||
__v,
|
||||
...rest
|
||||
} = body;
|
||||
|
||||
const update = { ...rest };
|
||||
|
||||
// Map frontend field aliases to schema fields
|
||||
if (nationalIdCode || nationalId) {
|
||||
update.nationalIdCode = nationalIdCode || nationalId;
|
||||
}
|
||||
if (phoneNumber || phone) {
|
||||
update.phoneNumber = phoneNumber || phone;
|
||||
}
|
||||
if (roleId || role) {
|
||||
update.role = roleId || role;
|
||||
}
|
||||
if (preferredMessenger !== undefined) {
|
||||
update.preferredMessenger = normalizePreferredMessengers(preferredMessenger) || [];
|
||||
}
|
||||
|
||||
// Never overwrite username with an empty value on update
|
||||
if (typeof username === 'string' && username.trim()) {
|
||||
update.username = username.trim();
|
||||
}
|
||||
|
||||
// Strip empty strings so required validators are not tripped
|
||||
Object.keys(update).forEach((key) => {
|
||||
if (key === 'preferredMessenger') return;
|
||||
if (update[key] === '' || update[key] === null || update[key] === undefined) {
|
||||
delete update[key];
|
||||
}
|
||||
});
|
||||
|
||||
if (password) {
|
||||
update.passwordHash = await bcrypt.hash(password, 10);
|
||||
}
|
||||
|
||||
const user = await User.findByIdAndUpdate(id, update, { new: true, runValidators: true })
|
||||
.select(SAFE_FIELDS)
|
||||
.populate(POPULATE_ROLE)
|
||||
.lean();
|
||||
if (!user) throw new AppError('USER_NOT_FOUND');
|
||||
return user;
|
||||
};
|
||||
|
||||
const deleteUser = async (id) => {
|
||||
const user = await User.findByIdAndDelete(id);
|
||||
if (!user) throw new AppError('USER_NOT_FOUND');
|
||||
};
|
||||
|
||||
const enrollUserInCourse = async (userId, courseId, actorId) => {
|
||||
const user = await User.findById(userId);
|
||||
if (!user) throw new AppError('USER_NOT_FOUND');
|
||||
|
||||
if (!user.courses.includes(courseId)) {
|
||||
user.courses.push(courseId);
|
||||
await user.save();
|
||||
}
|
||||
return User.findById(userId).select(SAFE_FIELDS).populate('courses').lean();
|
||||
};
|
||||
|
||||
module.exports = { signUp, getUserById, getAllUsers, searchUsers, createUserAdmin, updateUser, deleteUser, enrollUserInCourse };
|
||||
Reference in New Issue
Block a user