games_app/backend/dist-test-faq/services/adminService.js

462 lines
18 KiB
JavaScript

"use strict";
/**
* Admin user management service.
* Orchestrates user repository access, email decryption, and wallet balances for admin APIs.
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.listUsers = listUsers;
exports.updateUserAccountFlags = updateUserAccountFlags;
exports.batchUpdateUserAccountFlags = batchUpdateUserAccountFlags;
exports.batchUpdateUserSecurity = batchUpdateUserSecurity;
exports.batchGrantLedgerCredit = batchGrantLedgerCredit;
exports.markUserEmailVerified = markUserEmailVerified;
exports.deleteUser = deleteUser;
exports.getUserDetails = getUserDetails;
exports.updateUserRole = updateUserRole;
exports.updateUserRoles = updateUserRoles;
const userRepository = __importStar(require("../repositories/userRepository"));
const auditLogRepository = __importStar(require("../repositories/auditLogRepository"));
const roleRepository = __importStar(require("../repositories/roleRepository"));
const fundApprovalService = __importStar(require("./fundApprovalService"));
const walletService = __importStar(require("./walletService"));
const refreshTokenRepository = __importStar(require("../repositories/refreshTokenRepository"));
const totpRecoveryRepository = __importStar(require("../repositories/totpRecoveryRepository"));
const crypto_1 = require("../utils/crypto");
const auditDiff_1 = require("../utils/auditDiff");
function parseOptionalBigInt(value) {
if (!value?.trim())
return undefined;
try {
return BigInt(value.trim());
}
catch {
return undefined;
}
}
function decryptEmail(encrypted) {
if (!encrypted)
return null;
try {
return (0, crypto_1.decrypt)(encrypted);
}
catch {
return null;
}
}
function deriveAccountStatus(row) {
if (!row.is_enabled)
return 'disabled';
if (!row.is_account_non_locked ||
!row.is_account_non_expired ||
!row.is_credentials_non_expired ||
row.withdrawals_suspended ||
row.under_surveillance) {
return 'suspended';
}
return 'active';
}
/**
* Lists users for the admin panel with decrypted emails and aggregated stats.
*/
async function listUsers(options) {
const result = await userRepository.listForAdmin({
search: options.search,
roleName: options.roleName,
emailVerified: options.emailVerified,
country: options.country,
inactiveSinceDays: options.inactiveSinceDays,
activityFilter: options.activityFilter,
activityPeriodFrom: options.activityPeriodFrom,
activityPeriodTo: options.activityPeriodTo,
minMainBalance: parseOptionalBigInt(options.minMainBalance),
maxMainBalance: parseOptionalBigInt(options.maxMainBalance),
minBonusReceived: parseOptionalBigInt(options.minBonusReceived),
maxBonusReceived: parseOptionalBigInt(options.maxBonusReceived),
accountStatus: options.accountStatus,
hasReceivedBonus: options.hasReceivedBonus,
createdFrom: options.createdFrom,
createdTo: options.createdTo,
minAge: options.minAge,
maxAge: options.maxAge,
totpEnabled: options.totpEnabled,
underSurveillance: options.underSurveillance,
userIds: options.userIds,
sortBy: options.sortBy,
sortDir: options.sortDir,
limit: options.limit,
offset: options.offset,
cursor: options.cursor,
includeTotal: options.includeTotal,
});
return {
total: result.total,
totalIsExact: result.totalIsExact,
nextCursor: result.nextCursor,
hasMore: result.hasMore,
users: result.users.map((u) => ({
id: u.id,
email: decryptEmail(u.email_encrypted),
first_name: u.first_name,
middle_name: u.middle_name,
last_name: u.last_name,
date_of_birth: u.date_of_birth,
role_id: u.role_id,
role_name: u.role_name,
email_verified: u.email_verified,
totp_enabled: u.totp_enabled,
is_enabled: u.is_enabled,
is_account_non_expired: u.is_account_non_expired,
is_account_non_locked: u.is_account_non_locked,
is_credentials_non_expired: u.is_credentials_non_expired,
country_of_residence: u.country_of_residence,
nationality: u.nationality,
referral_code: u.referral_code,
first_deposit_at: u.first_deposit_at,
first_deposit_transaction_id: u.first_deposit_transaction_id,
withdrawals_suspended: u.withdrawals_suspended,
under_surveillance: u.under_surveillance,
security_suspended_at: u.security_suspended_at,
created_at: u.created_at,
updated_at: u.updated_at,
main_balance_raw: u.main_balance_raw,
bonus_balance_raw: u.bonus_balance_raw,
total_bonus_received_raw: u.total_bonus_received_raw,
prediction_count: u.prediction_count,
total_stake_raw: u.total_stake_raw,
total_payout_raw: u.total_payout_raw,
net_pnl_raw: u.net_pnl_raw,
last_login_at: u.last_login_at,
last_activity_at: u.last_activity_at,
account_status: deriveAccountStatus(u),
})),
};
}
async function updateUserAccountFlags(userId, flags, actor) {
const repoFlags = {};
if (typeof flags.isEnabled === 'boolean')
repoFlags.is_enabled = flags.isEnabled;
if (typeof flags.isAccountNonExpired === 'boolean') {
repoFlags.is_account_non_expired = flags.isAccountNonExpired;
}
if (typeof flags.isAccountNonLocked === 'boolean') {
repoFlags.is_account_non_locked = flags.isAccountNonLocked;
}
if (typeof flags.isCredentialsNonExpired === 'boolean') {
repoFlags.is_credentials_non_expired = flags.isCredentialsNonExpired;
}
if (Object.keys(repoFlags).length === 0) {
throw new Error('At least one flag required');
}
const existing = await userRepository.findById(userId);
if (!existing) {
throw new Error('User not found');
}
const beforeFlags = (0, auditDiff_1.userAccountFlagsSnapshot)(existing);
await userRepository.updateAccountFlags(userId, repoFlags);
if (actor) {
const afterFlags = {
...beforeFlags,
...(typeof flags.isEnabled === 'boolean' ? { is_enabled: flags.isEnabled } : {}),
...(typeof flags.isAccountNonExpired === 'boolean'
? { is_account_non_expired: flags.isAccountNonExpired }
: {}),
...(typeof flags.isAccountNonLocked === 'boolean'
? { is_account_non_locked: flags.isAccountNonLocked }
: {}),
...(typeof flags.isCredentialsNonExpired === 'boolean'
? { is_credentials_non_expired: flags.isCredentialsNonExpired }
: {}),
};
const diff = (0, auditDiff_1.diffFields)(beforeFlags, afterFlags, [
'is_enabled',
'is_account_non_expired',
'is_account_non_locked',
'is_credentials_non_expired',
]);
await auditLogRepository.create({
userId: actor.adminUserId,
action: 'admin_user_flags_updated',
resourceType: 'user',
resourceId: userId,
ipAddress: actor.ipAddress ?? null,
userAgent: actor.userAgent ?? null,
metadata: diff ?? { changed: Object.keys(repoFlags), before: beforeFlags, after: afterFlags },
});
}
}
async function batchUpdateUserAccountFlags(userIds, flags, actor) {
const unique = [...new Set(userIds.filter(Boolean))];
const result = { succeeded: [], failed: [] };
for (const userId of unique) {
try {
await updateUserAccountFlags(userId, flags, actor);
result.succeeded.push(userId);
}
catch (e) {
result.failed.push({
userId,
error: e instanceof Error ? e.message : 'Update failed',
});
}
}
return result;
}
async function batchUpdateUserSecurity(userIds, body, actor) {
const unique = [...new Set(userIds.filter(Boolean))];
const result = { succeeded: [], failed: [] };
for (const userId of unique) {
try {
const existing = await userRepository.findById(userId);
if (!existing) {
throw new Error('User not found');
}
const beforeSecurity = (0, auditDiff_1.userSecurityFlagsSnapshot)(existing);
if (body.reactivateWithdrawals) {
await userRepository.updateSecurityFlags(userId, {
withdrawals_suspended: false,
under_surveillance: false,
clear_security_reason: true,
});
}
else {
const flags = {};
if (typeof body.withdrawalsSuspended === 'boolean') {
flags.withdrawals_suspended = body.withdrawalsSuspended;
}
if (typeof body.underSurveillance === 'boolean') {
flags.under_surveillance = body.underSurveillance;
}
if (body.reason)
flags.security_reason_encrypted = body.reason;
if (body.withdrawalsSuspended || body.underSurveillance) {
flags.set_suspended_at = true;
}
if (Object.keys(flags).length === 0) {
throw new Error('No security flags provided');
}
await userRepository.updateSecurityFlags(userId, flags);
}
if (actor) {
const updated = await userRepository.findById(userId);
const afterSecurity = updated
? (0, auditDiff_1.userSecurityFlagsSnapshot)(updated)
: {
withdrawals_suspended: false,
under_surveillance: false,
security_suspended_at: null,
};
const diff = (0, auditDiff_1.diffFields)(beforeSecurity, afterSecurity, [
'withdrawals_suspended',
'under_surveillance',
'security_suspended_at',
]);
await auditLogRepository.create({
userId: actor.adminUserId,
action: 'admin_user_security_updated',
resourceType: 'user',
resourceId: userId,
ipAddress: actor.ipAddress ?? null,
userAgent: actor.userAgent ?? null,
metadata: {
...(diff ?? { changed: [], before: beforeSecurity, after: afterSecurity }),
reasonProvided: Boolean(body.reason?.trim()),
reactivateWithdrawals: Boolean(body.reactivateWithdrawals),
},
});
}
result.succeeded.push(userId);
}
catch (e) {
result.failed.push({
userId,
error: e instanceof Error ? e.message : 'Security update failed',
});
}
}
return result;
}
async function batchGrantLedgerCredit(userIds, input, requestedBy) {
const unique = [...new Set(userIds.filter(Boolean))];
const result = { succeeded: [], failed: [] };
for (const userId of unique) {
try {
await fundApprovalService.createFundRequest({
operationType: 'ledger_credit',
payload: {
userId,
walletTypeId: input.walletTypeId,
adjustmentType: input.adjustmentType,
amountRaw: input.amountRaw,
reason: input.reason,
},
requestedBy,
});
result.succeeded.push(userId);
}
catch (e) {
result.failed.push({
userId,
error: e instanceof Error ? e.message : 'Credit request failed',
});
}
}
return result;
}
/**
* Marks a user's email as verified (admin support action).
*/
async function markUserEmailVerified(userId, adminUserId) {
const user = await userRepository.findById(userId);
if (!user) {
throw new Error('User not found');
}
if (!user.email_verified) {
await userRepository.setEmailVerified(userId, true);
await auditLogRepository.create({
userId: adminUserId,
action: 'admin_email_verified',
resourceType: 'user',
resourceId: userId,
metadata: {
changed: ['email_verified'],
before: { email_verified: false },
after: { email_verified: true },
},
});
}
return { message: 'Email marked as verified', emailVerified: true };
}
async function deleteUser(targetUserId, adminUserId, opts) {
if (targetUserId === adminUserId) {
throw new Error('You cannot delete your own account');
}
const user = await userRepository.findById(targetUserId);
if (!user || user.deleted_at) {
throw new Error('User not found');
}
const roles = await roleRepository.getUserRoleNames(targetUserId);
if (roles.includes('super_admin')) {
const count = await roleRepository.countUsersWithRoleName('super_admin');
if (count <= 1) {
throw new Error('At least one super administrator must remain on the platform');
}
}
if (roles.includes('admin')) {
const count = await roleRepository.countUsersWithRoleName('admin');
if (count <= 1) {
throw new Error('At least one administrator must remain on the platform');
}
}
const mainBalance = await userRepository.getUserMainBalanceRaw(targetUserId);
if (mainBalance > 0n) {
throw new Error('User has a non-zero main balance — settle or transfer funds before deletion');
}
const beforeSnapshot = {
roles,
flags: (0, auditDiff_1.userAccountFlagsSnapshot)(user),
security: (0, auditDiff_1.userSecurityFlagsSnapshot)(user),
email_verified: user.email_verified,
totp_enabled: user.totp_enabled,
};
await refreshTokenRepository.deleteByUserId(targetUserId);
await totpRecoveryRepository.deleteCodesForUser(targetUserId);
const tombstoneHash = (0, crypto_1.hashForIndex)(`deleted:${targetUserId}:${Date.now()}`);
const ok = await userRepository.softDeleteUser(targetUserId, tombstoneHash);
if (!ok) {
throw new Error('User could not be deleted');
}
await auditLogRepository.create({
userId: adminUserId,
action: 'admin_user_deleted',
resourceType: 'user',
resourceId: targetUserId,
ipAddress: opts?.ipAddress ?? null,
userAgent: opts?.userAgent ?? null,
metadata: {
changed: ['deleted'],
before: beforeSnapshot,
after: { deleted: true },
reason: opts?.reason?.trim() || null,
},
});
return { message: 'User account deleted' };
}
/**
* Loads full admin user details including wallet balances.
*/
async function getUserDetails(userId) {
const row = await userRepository.getForAdmin(userId);
if (!row) {
throw new Error('User not found');
}
const balances = await walletService.getUserBalances(userId);
return {
user: {
id: row.id,
email: decryptEmail(row.email_encrypted),
role_id: row.role_id,
role_name: row.role_name,
roles: await roleRepository.getUserRoleNames(userId),
email_verified: row.email_verified,
totp_enabled: row.totp_enabled,
is_enabled: row.is_enabled,
is_account_non_expired: row.is_account_non_expired,
is_account_non_locked: row.is_account_non_locked,
is_credentials_non_expired: row.is_credentials_non_expired,
withdrawals_suspended: row.withdrawals_suspended,
under_surveillance: row.under_surveillance,
security_suspended_at: row.security_suspended_at,
created_at: row.created_at,
},
balances: balances.balances.map((b) => ({
wallet_type: b.walletType.code,
wallet_name: b.walletType.name,
available: b.available,
locked: b.locked,
})),
inventory: balances.inventory,
networks: balances.networks,
};
}
async function updateUserRole(targetUserId, role, adminUserId, notifyCtx = {}) {
const result = await fundApprovalService.updateUserRoles(targetUserId, [role], adminUserId, notifyCtx);
const primary = roleRepository.resolvePrimaryRole(result.roles);
return { userId: targetUserId, role: primary };
}
async function updateUserRoles(targetUserId, roles, adminUserId, notifyCtx = {}) {
return fundApprovalService.updateUserRoles(targetUserId, roles, adminUserId, notifyCtx);
}
//# sourceMappingURL=adminService.js.map