Commit a1400904 by tdgiang

Add createdByUsername field and boot-time admin seed/backfill

Adds AdminTransaction.createdByUsername (default null) so future
permission-scoped views can attribute data to a user, plus a new
app/libs/adminBootstrap.js that seeds the first admin account from
ADMIN_USER/ADMIN_PASSWORD on boot and backfills any pre-existing
transaction lacking createdByUsername to that admin. Wired into
server.js's mongoose 'open' handler. Idempotent across repeated boots.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
parent 79ccec0a
"use strict";
var AdminUser = require("../models/AdminUser");
var AdminTransaction = require("../models/AdminTransaction");
var passwordHash = require("./passwordHash");
module.exports = function run(config, callback) {
AdminUser.findOne({ role: "admin" }, function (err, existingAdmin) {
if (err) {
return callback(err);
}
if (existingAdmin) {
return backfillTransactions(existingAdmin.username, callback);
}
if (!config.admin || !config.admin.user || !config.admin.password) {
console.error("adminBootstrap: no admin exists and ADMIN_USER/ADMIN_PASSWORD not set - cannot seed");
return callback(null);
}
AdminUser.create(
{
username: String(config.admin.user).trim().toLowerCase(),
passwordHash: passwordHash.hash(config.admin.password),
role: "admin",
active: true,
},
function (createErr, admin) {
if (createErr) {
return callback(createErr);
}
console.log("adminBootstrap: seeded first admin account:", admin.username);
return backfillTransactions(admin.username, callback);
}
);
});
};
function backfillTransactions(adminUsername, callback) {
AdminTransaction.updateMany(
{ createdByUsername: null },
{ createdByUsername: adminUsername },
function (err, result) {
if (err) {
return callback(err);
}
if (result && result.nModified) {
console.log("adminBootstrap: backfilled", result.nModified, "old transactions to", adminUsername);
}
return callback(null);
}
);
}
......@@ -19,6 +19,7 @@ var AdminTransactionSchema = new Schema(
merchantToken: { type: String, required: true },
timeStamp: { type: String, required: true },
resultMsg: { type: String, default: "" },
createdByUsername: { type: String, default: null },
paidAt: { type: Date, default: null },
},
{ timestamps: true }
......
......@@ -25,6 +25,11 @@ mongoose.connection.on('error', function (err) {
});
mongoose.connection.once('open', function () {
console.log('MongoDB connected');
require('./app/libs/adminBootstrap')(config, function (err) {
if (err) {
console.error('adminBootstrap failed:', err.message);
}
});
});
/**
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment