709 lines
30 KiB
JavaScript
709 lines
30 KiB
JavaScript
"use strict";
|
|
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.findByEmailHash = findByEmailHash;
|
|
exports.findByPhoneHash = findByPhoneHash;
|
|
exports.findById = findById;
|
|
exports.create = create;
|
|
exports.updateTotp = updateTotp;
|
|
exports.getLoginLockedUntil = getLoginLockedUntil;
|
|
exports.incrementFailedLoginCount = incrementFailedLoginCount;
|
|
exports.setLoginLockedUntil = setLoginLockedUntil;
|
|
exports.resetFailedLoginState = resetFailedLoginState;
|
|
exports.getFailedLoginCount = getFailedLoginCount;
|
|
exports.getRoleName = getRoleName;
|
|
exports.adminListHasActiveFilters = adminListHasActiveFilters;
|
|
exports.listForAdmin = listForAdmin;
|
|
exports.getForAdmin = getForAdmin;
|
|
exports.updateAccountFlags = updateAccountFlags;
|
|
exports.updateSecurityFlags = updateSecurityFlags;
|
|
exports.getProfileForUser = getProfileForUser;
|
|
exports.getSelfProfileForUser = getSelfProfileForUser;
|
|
exports.updateProfile = updateProfile;
|
|
exports.updatePassword = updatePassword;
|
|
exports.getTokenVersion = getTokenVersion;
|
|
exports.incrementTokenVersion = incrementTokenVersion;
|
|
exports.softDeleteUser = softDeleteUser;
|
|
exports.getUserMainBalanceRaw = getUserMainBalanceRaw;
|
|
exports.setEmailVerified = setEmailVerified;
|
|
exports.countUsersWithRole = countUsersWithRole;
|
|
exports.getRoleIdByName = getRoleIdByName;
|
|
exports.updateUserRole = updateUserRole;
|
|
const connection_1 = require("../db/connection");
|
|
const onlineUsersRepository_1 = require("./onlineUsersRepository");
|
|
const crypto_1 = require("../utils/crypto");
|
|
const adminListCursor_1 = require("./adminListCursor");
|
|
const roleRepository = __importStar(require("./roleRepository"));
|
|
/**
|
|
* Repository for user account persistence and administration.
|
|
* Handles authentication lookups, profile management, and admin user listing.
|
|
*/
|
|
const USER_COLUMNS = 'id, email_hash, password_hash, role_id, email_verified, phone_verified, totp_secret_encrypted, totp_enabled, is_enabled, is_account_non_expired, is_account_non_locked, is_credentials_non_expired, token_version, withdrawals_suspended, under_surveillance, security_suspended_at, security_reason_encrypted, deleted_at, created_at, updated_at';
|
|
/**
|
|
* Finds a user by their indexed email hash.
|
|
* @param emailHash - HMAC hash of the normalized email address.
|
|
* @returns The user record, or null if not found.
|
|
*/
|
|
async function findByEmailHash(emailHash) {
|
|
const rows = await (0, connection_1.query)(`SELECT ${USER_COLUMNS} FROM users WHERE email_hash = $1 AND deleted_at IS NULL`, [emailHash]);
|
|
return rows[0] || null;
|
|
}
|
|
/**
|
|
* Finds a user by their indexed phone hash.
|
|
* @param phoneHash - HMAC hash of the normalized phone number.
|
|
* @returns The user record, or null if not found.
|
|
*/
|
|
async function findByPhoneHash(phoneHash) {
|
|
const rows = await (0, connection_1.query)(`SELECT ${USER_COLUMNS} FROM users WHERE phone_hash = $1 AND deleted_at IS NULL`, [phoneHash]);
|
|
return rows[0] || null;
|
|
}
|
|
/**
|
|
* Finds a user by primary key.
|
|
* @param id - User UUID.
|
|
* @returns The user record, or null if not found.
|
|
*/
|
|
async function findById(id) {
|
|
const rows = await (0, connection_1.query)(`SELECT ${USER_COLUMNS} FROM users WHERE id = $1`, [id]);
|
|
return rows[0] || null;
|
|
}
|
|
/**
|
|
* Creates a new user account.
|
|
* @param data - User registration fields.
|
|
* @param data.emailHash - HMAC hash of the normalized email address.
|
|
* @param data.emailEncrypted - Optional encrypted email for display/recovery.
|
|
* @param data.passwordHash - Bcrypt hash of the user's password.
|
|
* @param data.roleId - Optional role ID (defaults to 1).
|
|
* @returns The newly created user record.
|
|
*/
|
|
async function create(data) {
|
|
const rows = await (0, connection_1.query)(`INSERT INTO users (
|
|
email_hash, email_encrypted, password_hash, role_id,
|
|
first_name, last_name, phone_hash, phone_encrypted,
|
|
country_of_residence, nationality, gender, referral_code, referred_by_user_id,
|
|
registration_ip
|
|
)
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
|
|
RETURNING ${USER_COLUMNS}`, [
|
|
data.emailHash,
|
|
data.emailEncrypted || null,
|
|
data.passwordHash,
|
|
data.roleId ?? 1,
|
|
data.firstName ?? null,
|
|
data.lastName ?? null,
|
|
data.phoneHash ?? null,
|
|
data.phoneEncrypted ?? null,
|
|
data.countryOfResidence ?? null,
|
|
data.nationality ?? null,
|
|
data.gender ?? null,
|
|
data.referralCode ?? null,
|
|
data.referredByUserId ?? null,
|
|
data.registrationIp ?? null,
|
|
]);
|
|
const user = rows[0];
|
|
await roleRepository.ensureUserHasDefaultRole(user.id, data.roleId ?? 1);
|
|
return user;
|
|
}
|
|
/**
|
|
* Updates a user's TOTP (two-factor) configuration.
|
|
* @param userId - ID of the user to update.
|
|
* @param totpSecretEncrypted - Encrypted TOTP secret, or null to clear it.
|
|
* @param enabled - Whether TOTP is enabled for the user.
|
|
* @returns Resolves when the row has been updated.
|
|
*/
|
|
async function updateTotp(userId, totpSecretEncrypted, enabled) {
|
|
await (0, connection_1.query)('UPDATE users SET totp_secret_encrypted = $1, totp_enabled = $2, updated_at = NOW() WHERE id = $3', [totpSecretEncrypted, enabled, userId]);
|
|
}
|
|
async function getLoginLockedUntil(userId) {
|
|
const rows = await (0, connection_1.query)('SELECT login_locked_until FROM users WHERE id = $1', [userId]);
|
|
const v = rows[0]?.login_locked_until;
|
|
return v ? new Date(v) : null;
|
|
}
|
|
async function incrementFailedLoginCount(userId) {
|
|
const rows = await (0, connection_1.query)(`UPDATE users SET failed_login_count = failed_login_count + 1, updated_at = NOW()
|
|
WHERE id = $1
|
|
RETURNING failed_login_count`, [userId]);
|
|
return rows[0]?.failed_login_count ?? 0;
|
|
}
|
|
async function setLoginLockedUntil(userId, until) {
|
|
await (0, connection_1.query)('UPDATE users SET login_locked_until = $1, updated_at = NOW() WHERE id = $2', [
|
|
until,
|
|
userId,
|
|
]);
|
|
}
|
|
async function resetFailedLoginState(userId) {
|
|
await (0, connection_1.query)(`UPDATE users SET failed_login_count = 0, login_locked_until = NULL, updated_at = NOW() WHERE id = $1`, [userId]);
|
|
}
|
|
async function getFailedLoginCount(userId) {
|
|
const rows = await (0, connection_1.query)(`SELECT failed_login_count FROM users WHERE id = $1`, [userId]);
|
|
return rows[0]?.failed_login_count ?? 0;
|
|
}
|
|
/**
|
|
* Resolves a role ID to its display name.
|
|
* @param roleId - Numeric role identifier.
|
|
* @returns Role name string, or 'user' if the role is not found.
|
|
*/
|
|
async function getRoleName(roleId) {
|
|
const rows = await (0, connection_1.query)('SELECT name FROM roles WHERE id = $1', [roleId]);
|
|
return rows[0]?.name || 'user';
|
|
}
|
|
const ADMIN_LIST_FROM_SQL = `
|
|
FROM users u
|
|
JOIN roles r ON r.id = u.role_id
|
|
LEFT JOIN user_admin_stats s ON s.user_id = u.id`;
|
|
function buildAdminListWhere(filters) {
|
|
const whereParts = ['u.deleted_at IS NULL'];
|
|
const values = [];
|
|
let i = 1;
|
|
if (filters.search?.trim()) {
|
|
const term = filters.search.trim();
|
|
const emailHash = (0, crypto_1.hashForIndex)(term);
|
|
const idPattern = `${term}%`;
|
|
whereParts.push(`(u.id::text = $${i} OR u.id::text LIKE $${i + 1} OR u.email_hash = $${i + 2}
|
|
OR UPPER(u.referral_code) = UPPER($${i + 3}) OR u.referral_code ILIKE $${i + 4})`);
|
|
values.push(term, idPattern, emailHash, term, `${term}%`);
|
|
i += 5;
|
|
}
|
|
if (filters.roleName) {
|
|
whereParts.push(`r.name = $${i++}`);
|
|
values.push(filters.roleName);
|
|
}
|
|
if (typeof filters.emailVerified === 'boolean') {
|
|
whereParts.push(`u.email_verified = $${i++}`);
|
|
values.push(filters.emailVerified);
|
|
}
|
|
if (filters.country?.trim()) {
|
|
whereParts.push(`u.country_of_residence = $${i++}`);
|
|
values.push(filters.country.trim().toUpperCase());
|
|
}
|
|
if (typeof filters.inactiveSinceDays === 'number' && filters.inactiveSinceDays > 0) {
|
|
whereParts.push(`COALESCE(s.last_activity_at, u.updated_at, u.created_at) < NOW() - ($${i}::text || ' days')::interval`);
|
|
values.push(filters.inactiveSinceDays);
|
|
i += 1;
|
|
}
|
|
if (filters.minMainBalance !== undefined) {
|
|
whereParts.push(`COALESCE(s.main_balance_raw, 0) >= $${i++}`);
|
|
values.push(filters.minMainBalance.toString());
|
|
}
|
|
if (filters.maxMainBalance !== undefined) {
|
|
whereParts.push(`COALESCE(s.main_balance_raw, 0) <= $${i++}`);
|
|
values.push(filters.maxMainBalance.toString());
|
|
}
|
|
if (filters.minBonusReceived !== undefined) {
|
|
whereParts.push(`COALESCE(s.total_bonus_received_raw, 0) >= $${i++}`);
|
|
values.push(filters.minBonusReceived.toString());
|
|
}
|
|
if (filters.maxBonusReceived !== undefined) {
|
|
whereParts.push(`COALESCE(s.total_bonus_received_raw, 0) <= $${i++}`);
|
|
values.push(filters.maxBonusReceived.toString());
|
|
}
|
|
if (filters.accountStatus === 'active') {
|
|
whereParts.push(`u.is_enabled = TRUE
|
|
AND u.is_account_non_locked = TRUE
|
|
AND u.is_account_non_expired = TRUE
|
|
AND u.is_credentials_non_expired = TRUE
|
|
AND u.withdrawals_suspended = FALSE
|
|
AND u.under_surveillance = FALSE`);
|
|
}
|
|
else if (filters.accountStatus === 'disabled') {
|
|
whereParts.push(`u.is_enabled = FALSE`);
|
|
}
|
|
else if (filters.accountStatus === 'suspended') {
|
|
whereParts.push(`(u.is_enabled = TRUE AND (
|
|
u.is_account_non_locked = FALSE
|
|
OR u.withdrawals_suspended = TRUE
|
|
OR u.under_surveillance = TRUE
|
|
OR u.is_account_non_expired = FALSE
|
|
OR u.is_credentials_non_expired = FALSE
|
|
))`);
|
|
}
|
|
if (filters.hasReceivedBonus === true) {
|
|
whereParts.push(`COALESCE(s.total_bonus_received_raw, 0) > 0`);
|
|
}
|
|
else if (filters.hasReceivedBonus === false) {
|
|
whereParts.push(`COALESCE(s.total_bonus_received_raw, 0) = 0`);
|
|
}
|
|
if (filters.createdFrom) {
|
|
whereParts.push(`u.created_at >= $${i++}::timestamptz`);
|
|
values.push(filters.createdFrom);
|
|
}
|
|
if (filters.createdTo) {
|
|
whereParts.push(`u.created_at <= $${i++}::timestamptz`);
|
|
values.push(filters.createdTo);
|
|
}
|
|
if (filters.minAge !== undefined || filters.maxAge !== undefined) {
|
|
whereParts.push(`u.date_of_birth IS NOT NULL`);
|
|
if (filters.minAge !== undefined) {
|
|
whereParts.push(`EXTRACT(YEAR FROM AGE(CURRENT_DATE, u.date_of_birth)) >= $${i++}`);
|
|
values.push(filters.minAge);
|
|
}
|
|
if (filters.maxAge !== undefined) {
|
|
whereParts.push(`EXTRACT(YEAR FROM AGE(CURRENT_DATE, u.date_of_birth)) <= $${i++}`);
|
|
values.push(filters.maxAge);
|
|
}
|
|
}
|
|
if (typeof filters.totpEnabled === 'boolean') {
|
|
whereParts.push(`u.totp_enabled = $${i++}`);
|
|
values.push(filters.totpEnabled);
|
|
}
|
|
if (typeof filters.underSurveillance === 'boolean') {
|
|
whereParts.push(`u.under_surveillance = $${i++}`);
|
|
values.push(filters.underSurveillance);
|
|
}
|
|
if (filters.userIds?.length) {
|
|
whereParts.push(`u.id = ANY($${i++}::uuid[])`);
|
|
values.push(filters.userIds);
|
|
}
|
|
if (filters.activityFilter === 'active_in_period' && filters.activityPeriodFrom && filters.activityPeriodTo) {
|
|
whereParts.push(`u.id IN (
|
|
SELECT user_id FROM audit_logs
|
|
WHERE action = 'login'
|
|
AND created_at >= $${i}::timestamptz AND created_at <= $${i + 1}::timestamptz
|
|
UNION
|
|
SELECT user_id FROM candle_predict_bets
|
|
WHERE created_at >= $${i}::timestamptz AND created_at <= $${i + 1}::timestamptz
|
|
)`);
|
|
values.push(filters.activityPeriodFrom, filters.activityPeriodTo);
|
|
i += 2;
|
|
}
|
|
else if (filters.activityFilter === 'inactive_before_period' && filters.activityPeriodFrom) {
|
|
whereParts.push(`COALESCE(s.last_activity_at, u.created_at) < $${i}::timestamptz`);
|
|
values.push(filters.activityPeriodFrom);
|
|
i += 1;
|
|
}
|
|
else if (filters.activityFilter === 'online_now') {
|
|
// Resolved upstream to userIds (game WebSocket presence).
|
|
}
|
|
else if (filters.activityFilter === 'online_app') {
|
|
// Resolved upstream to userIds (app session presence).
|
|
}
|
|
else if (filters.activityFilter === 'staff') {
|
|
whereParts.push(`r.name IN ('admin', 'moderator')`);
|
|
}
|
|
const whereSql = whereParts.length ? `WHERE ${whereParts.join(' AND ')}` : '';
|
|
return { whereSql, values };
|
|
}
|
|
/** True when any filter narrows the user set (exact COUNT required). */
|
|
function adminListHasActiveFilters(filters) {
|
|
return !!(filters.search?.trim() ||
|
|
filters.roleName ||
|
|
typeof filters.emailVerified === 'boolean' ||
|
|
filters.country?.trim() ||
|
|
(typeof filters.inactiveSinceDays === 'number' && filters.inactiveSinceDays > 0) ||
|
|
filters.minMainBalance !== undefined ||
|
|
filters.maxMainBalance !== undefined ||
|
|
filters.minBonusReceived !== undefined ||
|
|
filters.maxBonusReceived !== undefined ||
|
|
filters.accountStatus ||
|
|
typeof filters.hasReceivedBonus === 'boolean' ||
|
|
filters.createdFrom ||
|
|
filters.createdTo ||
|
|
filters.minAge !== undefined ||
|
|
filters.maxAge !== undefined ||
|
|
typeof filters.totpEnabled === 'boolean' ||
|
|
typeof filters.underSurveillance === 'boolean' ||
|
|
(filters.userIds?.length ?? 0) > 0 ||
|
|
!!filters.activityFilter ||
|
|
!!filters.activityPeriodFrom ||
|
|
!!filters.activityPeriodTo);
|
|
}
|
|
async function estimateUsersCount() {
|
|
const rows = await (0, connection_1.query)(`SELECT COALESCE(c.reltuples, 0)::bigint::text AS estimate
|
|
FROM pg_class c
|
|
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
WHERE c.relname = 'users' AND n.nspname = current_schema()
|
|
LIMIT 1`);
|
|
return Math.max(0, parseInt(rows[0]?.estimate ?? '0', 10));
|
|
}
|
|
function adminListOrderBy(sortBy, sortDir) {
|
|
return (0, adminListCursor_1.adminListOrderBySql)(sortBy, sortDir);
|
|
}
|
|
const ADMIN_LIST_SELECT_SQL = `
|
|
SELECT u.id, u.email_hash, u.email_encrypted,
|
|
u.first_name, u.middle_name, u.last_name,
|
|
TO_CHAR(u.date_of_birth, 'YYYY-MM-DD') AS date_of_birth,
|
|
u.role_id, r.name AS role_name, u.email_verified, u.totp_enabled,
|
|
u.is_enabled, u.is_account_non_expired, u.is_account_non_locked,
|
|
u.is_credentials_non_expired,
|
|
u.country_of_residence, u.nationality, u.referral_code,
|
|
u.first_deposit_at, u.first_deposit_transaction_id,
|
|
u.withdrawals_suspended, u.under_surveillance,
|
|
u.security_suspended_at, u.created_at, u.updated_at,
|
|
COALESCE(s.main_balance_raw, 0)::text AS main_balance_raw,
|
|
COALESCE(s.bonus_balance_raw, 0)::text AS bonus_balance_raw,
|
|
COALESCE(s.total_bonus_received_raw, 0)::text AS total_bonus_received_raw,
|
|
COALESCE(s.prediction_count, 0) AS prediction_count,
|
|
COALESCE(s.total_stake_raw, 0)::text AS total_stake_raw,
|
|
COALESCE(s.total_payout_raw, 0)::text AS total_payout_raw,
|
|
COALESCE(s.net_pnl_raw, 0)::text AS net_pnl_raw,
|
|
s.last_login_at,
|
|
COALESCE(s.last_activity_at, u.updated_at, u.created_at) AS last_activity_at`;
|
|
async function resolveAdminListFilters(filters) {
|
|
if (filters.activityFilter === 'online_now') {
|
|
const ids = await (0, onlineUsersRepository_1.listConnectedOnGameUserIds)();
|
|
const { activityFilter: _af, ...rest } = filters;
|
|
return {
|
|
...rest,
|
|
userIds: ids.length ? ids : [onlineUsersRepository_1.EMPTY_ONLINE_USER_FILTER],
|
|
};
|
|
}
|
|
if (filters.activityFilter === 'online_app') {
|
|
const ids = await (0, onlineUsersRepository_1.listConnectedInAppUserIds)();
|
|
const { activityFilter: _af, ...rest } = filters;
|
|
return {
|
|
...rest,
|
|
userIds: ids.length ? ids : [onlineUsersRepository_1.EMPTY_ONLINE_USER_FILTER],
|
|
};
|
|
}
|
|
return filters;
|
|
}
|
|
/**
|
|
* Lists users for the admin panel with search, filtering, sorting, and pagination.
|
|
* Supports keyset (cursor) pagination and optional COUNT skipping for scale.
|
|
*/
|
|
async function listForAdmin(options) {
|
|
const { sortBy, sortDir, limit, offset, cursor, includeTotal, ...filters } = options;
|
|
const resolvedFilters = await resolveAdminListFilters(filters);
|
|
const limitNum = Math.min(limit, 100);
|
|
const fetchLimit = limitNum + 1;
|
|
const sb = sortBy ?? 'created_at';
|
|
const sd = (sortDir ?? 'desc').toLowerCase() === 'asc' ? 'asc' : 'desc';
|
|
const orderBySql = adminListOrderBy(sb, sd);
|
|
const { whereSql, values: filterValues } = buildAdminListWhere(resolvedFilters);
|
|
const hasFilters = adminListHasActiveFilters(resolvedFilters);
|
|
let keysetSql = '';
|
|
const decodedCursor = cursor ? (0, adminListCursor_1.decodeAdminListCursor)(cursor) : null;
|
|
const listValues = [...filterValues];
|
|
if (decodedCursor && decodedCursor.sortBy === sb && decodedCursor.sortDir === sd) {
|
|
const keyset = (0, adminListCursor_1.buildKeysetSql)(sb, sd, decodedCursor, listValues, listValues.length + 1);
|
|
keysetSql = keyset.sql;
|
|
}
|
|
const useOffset = !keysetSql && (offset ?? 0) > 0;
|
|
let total = null;
|
|
let totalIsExact = false;
|
|
if (includeTotal !== false) {
|
|
if (hasFilters) {
|
|
const countRows = await (0, connection_1.query)(`SELECT COUNT(*) AS count ${ADMIN_LIST_FROM_SQL} ${whereSql}`, filterValues);
|
|
total = parseInt(countRows[0]?.count || '0', 10);
|
|
totalIsExact = true;
|
|
}
|
|
else {
|
|
total = await estimateUsersCount();
|
|
totalIsExact = false;
|
|
}
|
|
}
|
|
const effectiveWhere = whereSql
|
|
? `${whereSql}${keysetSql}`
|
|
: keysetSql
|
|
? `WHERE ${keysetSql.trim().replace(/^AND\s+/, '')}`
|
|
: '';
|
|
let limitOffsetSql;
|
|
if (useOffset) {
|
|
listValues.push(fetchLimit, Math.max(0, offset ?? 0));
|
|
limitOffsetSql = `LIMIT $${listValues.length - 1} OFFSET $${listValues.length}`;
|
|
}
|
|
else {
|
|
listValues.push(fetchLimit);
|
|
limitOffsetSql = `LIMIT $${listValues.length}`;
|
|
}
|
|
const rows = await (0, connection_1.query)(`${ADMIN_LIST_SELECT_SQL}
|
|
${ADMIN_LIST_FROM_SQL}
|
|
${effectiveWhere}
|
|
ORDER BY ${orderBySql}
|
|
${limitOffsetSql}`, listValues);
|
|
const hasMore = rows.length > limitNum;
|
|
const users = hasMore ? rows.slice(0, limitNum) : rows;
|
|
const nextCursor = hasMore && users.length > 0 ? (0, adminListCursor_1.buildCursorFromRow)(sb, sd, users[users.length - 1]) : null;
|
|
return { users, total, totalIsExact, nextCursor, hasMore };
|
|
}
|
|
/**
|
|
* Retrieves detailed user information for the admin panel.
|
|
* @param userId - ID of the user to fetch.
|
|
* @returns Admin detail row, or null if the user does not exist.
|
|
*/
|
|
async function getForAdmin(userId) {
|
|
const rows = await (0, connection_1.query)(`SELECT u.id, u.email_encrypted, u.role_id, r.name as role_name, u.email_verified, u.totp_enabled,
|
|
u.is_enabled, u.is_account_non_expired, u.is_account_non_locked, u.is_credentials_non_expired,
|
|
u.withdrawals_suspended, u.under_surveillance, u.security_suspended_at, u.created_at
|
|
FROM users u JOIN roles r ON r.id = u.role_id
|
|
WHERE u.id = $1 AND u.deleted_at IS NULL`, [userId]);
|
|
return rows[0] || null;
|
|
}
|
|
/**
|
|
* Updates Spring Security-style account flag fields for a user.
|
|
* Only flags present in the input object are modified.
|
|
* @param userId - ID of the user to update.
|
|
* @param flags - Account flag values to set.
|
|
* @param flags.is_enabled - Whether the account is enabled.
|
|
* @param flags.is_account_non_expired - Whether the account has not expired.
|
|
* @param flags.is_account_non_locked - Whether the account is not locked.
|
|
* @param flags.is_credentials_non_expired - Whether credentials have not expired.
|
|
* @returns Resolves when applicable fields have been updated (no-op if flags is empty).
|
|
*/
|
|
async function updateAccountFlags(userId, flags) {
|
|
const updates = [];
|
|
const values = [];
|
|
let i = 1;
|
|
if (flags.is_enabled !== undefined) {
|
|
updates.push(`is_enabled = $${i++}`);
|
|
values.push(flags.is_enabled);
|
|
}
|
|
if (flags.is_account_non_expired !== undefined) {
|
|
updates.push(`is_account_non_expired = $${i++}`);
|
|
values.push(flags.is_account_non_expired);
|
|
}
|
|
if (flags.is_account_non_locked !== undefined) {
|
|
updates.push(`is_account_non_locked = $${i++}`);
|
|
values.push(flags.is_account_non_locked);
|
|
}
|
|
if (flags.is_credentials_non_expired !== undefined) {
|
|
updates.push(`is_credentials_non_expired = $${i++}`);
|
|
values.push(flags.is_credentials_non_expired);
|
|
}
|
|
if (updates.length === 0)
|
|
return;
|
|
values.push(userId);
|
|
await (0, connection_1.query)(`UPDATE users SET ${updates.join(', ')}, updated_at = NOW() WHERE id = $${i}`, values);
|
|
}
|
|
/**
|
|
* Updates security surveillance and withdrawal suspension flags.
|
|
*/
|
|
async function updateSecurityFlags(userId, flags) {
|
|
const { encryptSensitive } = await Promise.resolve().then(() => __importStar(require('../utils/crypto')));
|
|
const updates = [];
|
|
const values = [];
|
|
let i = 1;
|
|
if (flags.withdrawals_suspended !== undefined) {
|
|
updates.push(`withdrawals_suspended = $${i++}`);
|
|
values.push(flags.withdrawals_suspended);
|
|
}
|
|
if (flags.under_surveillance !== undefined) {
|
|
updates.push(`under_surveillance = $${i++}`);
|
|
values.push(flags.under_surveillance);
|
|
}
|
|
if (flags.security_reason_encrypted !== undefined) {
|
|
updates.push(`security_reason_encrypted = $${i++}`);
|
|
values.push(encryptSensitive(flags.security_reason_encrypted));
|
|
}
|
|
if (flags.set_suspended_at) {
|
|
updates.push(`security_suspended_at = NOW()`);
|
|
}
|
|
if (flags.clear_security_reason) {
|
|
updates.push(`security_reason_encrypted = NULL`);
|
|
updates.push(`security_suspended_at = NULL`);
|
|
}
|
|
if (updates.length === 0)
|
|
return;
|
|
values.push(userId);
|
|
await (0, connection_1.query)(`UPDATE users SET ${updates.join(', ')}, updated_at = NOW() WHERE id = $${i}`, values);
|
|
}
|
|
/**
|
|
* Loads a user's profile fields for display or editing.
|
|
* @param userId - ID of the user.
|
|
* @returns Profile row with name, DOB, and encrypted contact fields, or null if not found.
|
|
*/
|
|
async function getProfileForUser(userId) {
|
|
const rows = await (0, connection_1.query)('SELECT id, first_name, middle_name, last_name, date_of_birth, email_encrypted, phone_encrypted FROM users WHERE id = $1', [userId]);
|
|
return rows[0] || null;
|
|
}
|
|
/**
|
|
* Loads profile and account metadata for the authenticated user's GET /me response.
|
|
* @param userId - ID of the user.
|
|
* @returns Profile with role and security flags, or null if not found.
|
|
*/
|
|
async function getSelfProfileForUser(userId) {
|
|
const rows = await (0, connection_1.query)(`SELECT u.id, u.first_name, u.middle_name, u.last_name, u.date_of_birth,
|
|
u.email_encrypted, u.phone_encrypted, u.gender,
|
|
u.country_of_residence, u.nationality,
|
|
r.name AS role_name,
|
|
u.email_verified, u.totp_enabled, u.created_at
|
|
FROM users u
|
|
JOIN roles r ON r.id = u.role_id
|
|
WHERE u.id = $1`, [userId]);
|
|
return rows[0] || null;
|
|
}
|
|
/**
|
|
* Updates a user's profile and contact information.
|
|
* Only fields present in the data object are modified.
|
|
* @param userId - ID of the user to update.
|
|
* @param data - Profile fields to set.
|
|
* @param data.first_name - Optional given name.
|
|
* @param data.middle_name - Optional middle name.
|
|
* @param data.last_name - Optional family name.
|
|
* @param data.date_of_birth - Optional date of birth (ISO date string).
|
|
* @param data.emailHash - Optional new indexed email hash.
|
|
* @param data.emailEncrypted - Optional new encrypted email.
|
|
* @param data.phoneHash - Optional new indexed phone hash.
|
|
* @param data.phoneEncrypted - Optional new encrypted phone number.
|
|
* @returns Resolves when applicable fields have been updated (no-op if data is empty).
|
|
*/
|
|
async function updateProfile(userId, data) {
|
|
const updates = [];
|
|
const values = [];
|
|
let i = 1;
|
|
if (data.first_name !== undefined) {
|
|
updates.push(`first_name = $${i++}`);
|
|
values.push(data.first_name);
|
|
}
|
|
if (data.middle_name !== undefined) {
|
|
updates.push(`middle_name = $${i++}`);
|
|
values.push(data.middle_name);
|
|
}
|
|
if (data.last_name !== undefined) {
|
|
updates.push(`last_name = $${i++}`);
|
|
values.push(data.last_name);
|
|
}
|
|
if (data.date_of_birth !== undefined) {
|
|
updates.push(`date_of_birth = $${i++}`);
|
|
values.push(data.date_of_birth);
|
|
}
|
|
if (data.emailHash !== undefined) {
|
|
updates.push(`email_hash = $${i++}`);
|
|
values.push(data.emailHash);
|
|
}
|
|
if (data.emailEncrypted !== undefined) {
|
|
updates.push(`email_encrypted = $${i++}`);
|
|
values.push(data.emailEncrypted);
|
|
}
|
|
if (data.phoneHash !== undefined) {
|
|
updates.push(`phone_hash = $${i++}`);
|
|
values.push(data.phoneHash);
|
|
}
|
|
if (data.phoneEncrypted !== undefined) {
|
|
updates.push(`phone_encrypted = $${i++}`);
|
|
values.push(data.phoneEncrypted);
|
|
}
|
|
if (data.country_of_residence !== undefined) {
|
|
updates.push(`country_of_residence = $${i++}`);
|
|
values.push(data.country_of_residence);
|
|
}
|
|
if (data.nationality !== undefined) {
|
|
updates.push(`nationality = $${i++}`);
|
|
values.push(data.nationality);
|
|
}
|
|
if (data.gender !== undefined) {
|
|
updates.push(`gender = $${i++}`);
|
|
values.push(data.gender);
|
|
}
|
|
if (updates.length === 0)
|
|
return;
|
|
values.push(userId);
|
|
await (0, connection_1.query)(`UPDATE users SET ${updates.join(', ')}, updated_at = NOW() WHERE id = $${i}`, values);
|
|
}
|
|
/**
|
|
* Updates a user's password hash.
|
|
* @param userId - ID of the user.
|
|
* @param passwordHash - New bcrypt password hash.
|
|
* @returns Resolves when the password has been updated.
|
|
*/
|
|
async function updatePassword(userId, passwordHash) {
|
|
await (0, connection_1.query)('UPDATE users SET password_hash = $1, token_version = token_version + 1, updated_at = NOW() WHERE id = $2', [passwordHash, userId]);
|
|
}
|
|
/**
|
|
* Returns the current JWT invalidation version for a user.
|
|
*/
|
|
async function getTokenVersion(userId) {
|
|
const rows = await (0, connection_1.query)('SELECT token_version FROM users WHERE id = $1', [userId]);
|
|
return rows[0]?.token_version ?? null;
|
|
}
|
|
/**
|
|
* Bumps token_version to invalidate all outstanding access JWTs (e.g. logout everywhere).
|
|
*/
|
|
async function incrementTokenVersion(userId) {
|
|
await (0, connection_1.query)('UPDATE users SET token_version = token_version + 1, updated_at = NOW() WHERE id = $1', [userId]);
|
|
}
|
|
/**
|
|
* Soft-deletes a user: anonymizes PII, disables account, bumps token version.
|
|
* @returns false if user was already deleted or not found.
|
|
*/
|
|
async function softDeleteUser(userId, tombstoneEmailHash) {
|
|
const rows = await (0, connection_1.query)(`UPDATE users SET
|
|
deleted_at = NOW(),
|
|
is_enabled = FALSE,
|
|
email_encrypted = NULL,
|
|
phone_encrypted = NULL,
|
|
phone_hash = NULL,
|
|
first_name = NULL,
|
|
middle_name = NULL,
|
|
last_name = NULL,
|
|
date_of_birth = NULL,
|
|
email_hash = $1,
|
|
totp_secret_encrypted = NULL,
|
|
totp_enabled = FALSE,
|
|
token_version = token_version + 1,
|
|
updated_at = NOW()
|
|
WHERE id = $2 AND deleted_at IS NULL
|
|
RETURNING id`, [tombstoneEmailHash, userId]);
|
|
return rows.length > 0;
|
|
}
|
|
/** Main ledger balance (micro-USDT) from admin stats snapshot. */
|
|
async function getUserMainBalanceRaw(userId) {
|
|
const rows = await (0, connection_1.query)(`SELECT COALESCE(s.main_balance_raw, 0)::text AS main_balance_raw
|
|
FROM users u
|
|
LEFT JOIN user_admin_stats s ON s.user_id = u.id
|
|
WHERE u.id = $1`, [userId]);
|
|
return BigInt(rows[0]?.main_balance_raw ?? '0');
|
|
}
|
|
/**
|
|
* Sets the email_verified flag for a user.
|
|
* @param userId - User UUID
|
|
* @param verified - Whether the email has been confirmed
|
|
*/
|
|
async function setEmailVerified(userId, verified) {
|
|
await (0, connection_1.query)('UPDATE users SET email_verified = $1, updated_at = NOW() WHERE id = $2', [verified, userId]);
|
|
}
|
|
async function countUsersWithRole(roleName) {
|
|
const rows = await (0, connection_1.query)(`SELECT COUNT(DISTINCT uid)::text AS count FROM (
|
|
SELECT ur.user_id AS uid
|
|
FROM user_roles ur
|
|
JOIN roles r ON r.id = ur.role_id
|
|
WHERE r.name = $1
|
|
UNION
|
|
SELECT u.id AS uid
|
|
FROM users u
|
|
JOIN roles r ON r.id = u.role_id
|
|
WHERE r.name = $1
|
|
) t`, [roleName]);
|
|
return parseInt(rows[0]?.count ?? '0', 10);
|
|
}
|
|
async function getRoleIdByName(roleName) {
|
|
const rows = await (0, connection_1.query)('SELECT id FROM roles WHERE name = $1', [roleName]);
|
|
if (!rows[0])
|
|
throw new Error(`Unknown role: ${roleName}`);
|
|
return rows[0].id;
|
|
}
|
|
async function updateUserRole(userId, roleId) {
|
|
await (0, connection_1.query)('UPDATE users SET role_id = $1, updated_at = NOW() WHERE id = $2', [roleId, userId]);
|
|
}
|
|
//# sourceMappingURL=userRepository.js.map
|