This commit is contained in:
Ccjcarkbla
2026-06-13 08:03:45 -04:00
parent cfcd6ae11e
commit a2c300678b
121 changed files with 8639 additions and 0 deletions
@@ -0,0 +1,47 @@
'use strict';
module.exports = {
async up(queryInterface, Sequelize) {
// Create Users table if it doesn't exist (new installs)
const tableDesc = await queryInterface.describeTable('Users').catch(() => null);
if (!tableDesc) {
await queryInterface.createTable('Users', {
id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true },
organizationId: { type: Sequelize.INTEGER },
username: { type: Sequelize.STRING, allowNull: false, unique: true },
email: { type: Sequelize.STRING, unique: true },
password: { type: Sequelize.STRING, allowNull: false },
role: { type: Sequelize.ENUM('SystemAdmin', 'Owner', 'Coach', 'Client'), allowNull: false, defaultValue: 'Coach' },
firstName: { type: Sequelize.STRING },
lastName: { type: Sequelize.STRING },
isActive: { type: Sequelize.BOOLEAN, defaultValue: true },
lastLoginAt: { type: Sequelize.DATE },
passwordChangedAt: { type: Sequelize.DATE },
createdAt: { type: Sequelize.DATE, allowNull: false },
updatedAt: { type: Sequelize.DATE, allowNull: false },
});
return;
}
// V1 upgrade path: add missing columns
const addIfMissing = async (col, def) => {
if (!tableDesc[col]) {
await queryInterface.addColumn('Users', col, def);
}
};
await addIfMissing('organizationId', { type: Sequelize.INTEGER });
await addIfMissing('email', { type: Sequelize.STRING });
await addIfMissing('firstName', { type: Sequelize.STRING });
await addIfMissing('lastName', { type: Sequelize.STRING });
await addIfMissing('isActive', { type: Sequelize.BOOLEAN, defaultValue: true });
await addIfMissing('lastLoginAt', { type: Sequelize.DATE });
await addIfMissing('passwordChangedAt', { type: Sequelize.DATE });
},
async down(queryInterface) {
// No-op for V1 upgrade path; would need to be more specific for rollback
await queryInterface.dropTable('Users').catch(() => {});
},
};
@@ -0,0 +1,20 @@
'use strict';
// passwordChangedAt was added in 003 for new installs; this migration ensures
// it exists on V1 upgrades where 003 ran the addIfMissing path but may have
// been using an older column list.
module.exports = {
async up(queryInterface, Sequelize) {
const tableDesc = await queryInterface.describeTable('Users').catch(() => null);
if (tableDesc && !tableDesc['passwordChangedAt']) {
await queryInterface.addColumn('Users', 'passwordChangedAt', {
type: Sequelize.DATE,
allowNull: true,
});
}
},
async down(queryInterface) {
await queryInterface.removeColumn('Users', 'passwordChangedAt').catch(() => {});
},
};
+32
View File
@@ -0,0 +1,32 @@
'use strict';
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
organizationId: { type: DataTypes.INTEGER },
username: { type: DataTypes.STRING, allowNull: false, unique: true },
email: { type: DataTypes.STRING, unique: true },
password: { type: DataTypes.STRING, allowNull: false },
role: { type: DataTypes.ENUM('SystemAdmin', 'Owner', 'Coach', 'Client'), allowNull: false, defaultValue: 'Coach' },
firstName: { type: DataTypes.STRING },
lastName: { type: DataTypes.STRING },
isActive: { type: DataTypes.BOOLEAN, defaultValue: true },
lastLoginAt: { type: DataTypes.DATE },
passwordChangedAt: { type: DataTypes.DATE },
}, {
defaultScope: {
attributes: { exclude: ['password', 'passwordChangedAt'] },
},
});
User.prototype.toPublic = function () {
const { password, passwordChangedAt, ...rest } = this.toJSON();
return rest;
};
User.associate = (models) => {
User.hasMany(models.DeviceToken, { foreignKey: 'userId' });
};
return { User };
};
+41
View File
@@ -0,0 +1,41 @@
'use strict';
const express = require('express');
const { models } = require('../../core/db');
const { authenticateToken } = require('../../core/auth');
const { ok, noContent } = require('../../core/respond');
const { AppError } = require('../../core/errors');
const { changeOwnPassword: changeOwnPasswordSchema } = require('../../core/schemas/auth');
const svc = require('./service');
const router = express.Router();
router.prefix = 'my';
function validate(schema) {
return (req, res, next) => {
const result = schema.safeParse(req.body);
if (!result.success) {
const e = result.error.errors[0];
return next(new AppError('VALIDATION_FAILED', e.message, 400, e.path[0]));
}
req.body = result.data;
next();
};
}
router.get('/profile', authenticateToken, async (req, res, next) => {
try {
const user = await models.User.findByPk(req.user.id);
if (!user) return next(new AppError('NOT_FOUND', 'User not found.', 404));
ok(res, user.toPublic());
} catch (err) { next(err); }
});
router.put('/password', authenticateToken, validate(changeOwnPasswordSchema), async (req, res, next) => {
try {
await svc.changeOwnPassword(models, req, req.user.id, req.body.currentPassword, req.body.newPassword);
noContent(res);
} catch (err) { next(err); }
});
module.exports = router;
+122
View File
@@ -0,0 +1,122 @@
'use strict';
const express = require('express');
const { models } = require('../../core/db');
const { authenticateToken, authenticateRole } = require('../../core/auth');
const { ok, created, collection, noContent } = require('../../core/respond');
const { AppError } = require('../../core/errors');
const { createUser: createUserSchema, updateProfile, resetPassword: resetPasswordSchema, changeRole: changeRoleSchema } = require('../../core/schemas/users');
const { changeOwnPassword: changeOwnPasswordSchema } = require('../../core/schemas/auth');
const svc = require('./service');
const router = express.Router();
router.prefix = 'users';
const OWNERS = ['Owner', 'SystemAdmin'];
function validate(schema) {
return (req, res, next) => {
const result = schema.safeParse(req.body);
if (!result.success) {
const e = result.error.errors[0];
return next(new AppError('VALIDATION_FAILED', e.message, 400, e.path[0]));
}
req.body = result.data;
next();
};
}
// GET /users
router.get('/', authenticateToken, authenticateRole(OWNERS), async (req, res, next) => {
try {
const { role, isActive, page = 1, limit = 50 } = req.query;
const { rows, count } = await svc.getUsers(models, req.user.organizationId, { role, isActive, page: +page, limit: +limit });
collection(res, rows.map(u => u.toPublic()), count, +page, +limit);
} catch (err) { next(err); }
});
// POST /users
router.post('/', authenticateToken, authenticateRole(OWNERS), validate(createUserSchema), async (req, res, next) => {
try {
const user = await svc.createUser(models, req, req.user.organizationId, req.body);
created(res, user);
} catch (err) { next(err); }
});
// GET /users/:id
router.get('/:id', authenticateToken, async (req, res, next) => {
try {
const targetId = parseInt(req.params.id, 10);
// Own profile: any role. Other profiles: Owner+
if (req.user.id !== targetId && !OWNERS.includes(req.user.role)) {
return next(new AppError('AUTH_FORBIDDEN', 'Forbidden.', 403));
}
const user = await svc.getUserById(models, targetId, req.user.organizationId);
const tokens = await svc.getDeviceTokens(models, targetId, req.user.organizationId);
ok(res, { ...user.toPublic(), deviceTokens: tokens });
} catch (err) { next(err); }
});
// PATCH /users/:id
router.patch('/:id', authenticateToken, validate(updateProfile), async (req, res, next) => {
try {
const targetId = parseInt(req.params.id, 10);
if (req.user.id !== targetId && !OWNERS.includes(req.user.role)) {
return next(new AppError('AUTH_FORBIDDEN', 'Forbidden.', 403));
}
const user = await svc.updateProfile(models, req, targetId, req.body);
ok(res, user);
} catch (err) { next(err); }
});
// DELETE /users/:id (soft deactivate)
router.delete('/:id', authenticateToken, authenticateRole(OWNERS), async (req, res, next) => {
try {
await svc.deactivateUser(models, req, parseInt(req.params.id, 10), req.user.organizationId);
noContent(res);
} catch (err) { next(err); }
});
// PUT /users/:id/role
router.put('/:id/role', authenticateToken, authenticateRole(OWNERS), validate(changeRoleSchema), async (req, res, next) => {
try {
const user = await svc.changeRole(models, req, parseInt(req.params.id, 10), req.body.role, req.user.organizationId, req.user.id);
ok(res, user);
} catch (err) { next(err); }
});
// PUT /users/:id/password (admin reset — no current password required)
router.put('/:id/password', authenticateToken, authenticateRole(OWNERS), validate(resetPasswordSchema), async (req, res, next) => {
try {
await svc.resetPassword(models, req, parseInt(req.params.id, 10), req.body.newPassword, req.user.organizationId);
noContent(res);
} catch (err) { next(err); }
});
// GET /users/:id/devices
router.get('/:id/devices', authenticateToken, async (req, res, next) => {
try {
const targetId = parseInt(req.params.id, 10);
if (req.user.id !== targetId && !OWNERS.includes(req.user.role)) {
return next(new AppError('AUTH_FORBIDDEN', 'Forbidden.', 403));
}
const tokens = await svc.getDeviceTokens(models, targetId, req.user.organizationId);
ok(res, tokens);
} catch (err) { next(err); }
});
// DELETE /users/:id/devices/:tokenId
router.delete('/:id/devices/:tokenId', authenticateToken, async (req, res, next) => {
try {
const targetId = parseInt(req.params.id, 10);
if (req.user.id !== targetId && !OWNERS.includes(req.user.role)) {
return next(new AppError('AUTH_FORBIDDEN', 'Forbidden.', 403));
}
await svc.revokeDeviceToken(models, req, parseInt(req.params.tokenId, 10), targetId, req.user.organizationId);
noContent(res);
} catch (err) { next(err); }
});
// PUT /my/password (own password change with current password verification)
// Note: registered here but mounted under /users; the /my prefix is handled by a separate router
module.exports = router;
+131
View File
@@ -0,0 +1,131 @@
'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 };