349 lines
13 KiB
JavaScript
349 lines
13 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.getUserDetails = getUserDetails;
|
|
exports.updateUserRole = updateUserRole;
|
|
const userRepository = __importStar(require("../repositories/userRepository"));
|
|
const auditLogRepository = __importStar(require("../repositories/auditLogRepository"));
|
|
const walletService = __importStar(require("./walletService"));
|
|
const adminCreditService = __importStar(require("./adminCreditService"));
|
|
const crypto_1 = require("../utils/crypto");
|
|
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) {
|
|
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');
|
|
}
|
|
await userRepository.updateAccountFlags(userId, repoFlags);
|
|
}
|
|
async function batchUpdateUserAccountFlags(userIds, flags) {
|
|
const unique = [...new Set(userIds.filter(Boolean))];
|
|
const result = { succeeded: [], failed: [] };
|
|
for (const userId of unique) {
|
|
try {
|
|
await updateUserAccountFlags(userId, flags);
|
|
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) {
|
|
const unique = [...new Set(userIds.filter(Boolean))];
|
|
const result = { succeeded: [], failed: [] };
|
|
for (const userId of unique) {
|
|
try {
|
|
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);
|
|
}
|
|
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, approvedBy) {
|
|
const unique = [...new Set(userIds.filter(Boolean))];
|
|
const result = { succeeded: [], failed: [] };
|
|
for (const userId of unique) {
|
|
try {
|
|
await adminCreditService.grantLedgerCredit({
|
|
userId,
|
|
walletTypeId: input.walletTypeId,
|
|
adjustmentType: input.adjustmentType,
|
|
amountRaw: input.amountRaw,
|
|
reason: input.reason,
|
|
approvedBy,
|
|
});
|
|
result.succeeded.push(userId);
|
|
}
|
|
catch (e) {
|
|
result.failed.push({
|
|
userId,
|
|
error: e instanceof Error ? e.message : 'Credit 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,
|
|
});
|
|
}
|
|
return { message: 'Email marked as verified', emailVerified: true };
|
|
}
|
|
/**
|
|
* 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,
|
|
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.map((b) => ({
|
|
wallet_type: b.walletType.code,
|
|
wallet_name: b.walletType.name,
|
|
available: b.available,
|
|
locked: b.locked,
|
|
})),
|
|
};
|
|
}
|
|
async function updateUserRole(targetUserId, role, adminUserId) {
|
|
if (!['user', 'moderator', 'admin'].includes(role)) {
|
|
throw new Error('Invalid role');
|
|
}
|
|
const target = await userRepository.findById(targetUserId);
|
|
if (!target)
|
|
throw new Error('User not found');
|
|
const currentRole = (await userRepository.getRoleName(target.role_id));
|
|
const roleId = await userRepository.getRoleIdByName(role);
|
|
if (currentRole === role) {
|
|
return { userId: targetUserId, role };
|
|
}
|
|
if (currentRole === 'admin' && role !== 'admin') {
|
|
const adminCount = await userRepository.countUsersWithRole('admin');
|
|
if (adminCount <= 1) {
|
|
throw new Error('Cannot change role: at least one administrator must remain on the platform');
|
|
}
|
|
}
|
|
if (targetUserId === adminUserId && currentRole === 'admin' && role !== 'admin') {
|
|
throw new Error('You cannot remove your own administrator role');
|
|
}
|
|
await userRepository.updateUserRole(targetUserId, roleId);
|
|
await auditLogRepository.create({
|
|
userId: adminUserId,
|
|
action: 'admin_user_role_changed',
|
|
resourceType: 'user',
|
|
resourceId: targetUserId,
|
|
metadata: { from: currentRole, to: role },
|
|
});
|
|
return { userId: targetUserId, role };
|
|
}
|
|
//# sourceMappingURL=adminService.js.map
|