games_app/backend/dist-test-faq/controllers/authController.js

447 lines
16 KiB
JavaScript

"use strict";
/**
* Auth controller — HTTP handlers for registration, login, token refresh, 2FA, and password changes.
*/
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.register = register;
exports.validateReferralCode = validateReferralCode;
exports.getCaptchaConfig = getCaptchaConfig;
exports.getCaptchaChallenge = getCaptchaChallenge;
exports.login = login;
exports.refresh = refresh;
exports.setup2FA = setup2FA;
exports.enable2FA = enable2FA;
exports.logout = logout;
exports.logoutAll = logoutAll;
exports.disable2FA = disable2FA;
exports.regenerateRecoveryCodes = regenerateRecoveryCodes;
exports.changePassword = changePassword;
exports.sendVerificationEmail = sendVerificationEmail;
exports.verifyEmail = verifyEmail;
exports.resendVerificationEmail = resendVerificationEmail;
exports.forgotPassword = forgotPassword;
exports.resetPassword = resetPassword;
exports.validateResetToken = validateResetToken;
const authService = __importStar(require("../services/authService"));
const emailVerificationService = __importStar(require("../services/emailVerificationService"));
const passwordResetService = __importStar(require("../services/passwordResetService"));
const optionalAuth_1 = require("../middleware/optionalAuth");
const safeError_1 = require("../utils/safeError");
const clientDevice_1 = require("../utils/clientDevice");
const captchaService = __importStar(require("../services/captchaService"));
const settingsRepository = __importStar(require("../repositories/settingsRepository"));
/**
* Registers a new user with email and password.
* @param req - Request body: `email`, `password`.
* @param res - 201 with `{ message, userId }` on success, 400 on validation or registration failure.
*/
async function register(req, res) {
try {
const { email, password, fullName, phone, countryOfResidence, nationality, referralCode, gender, } = req.body;
if (!email || !password || !fullName || !countryOfResidence || !gender) {
res.status(400).json({
error: 'email, password, fullName, countryOfResidence, and gender are required',
});
return;
}
const result = await authService.register({
email,
password,
fullName,
phone,
countryOfResidence,
nationality,
gender,
referralCode,
registrationIp: req.ip || undefined,
userAgent: req.get('user-agent') || undefined,
visitorSupportToken: (0, optionalAuth_1.readVisitorToken)(req),
});
res.status(201).json({
message: 'Registered. Please check your email and click the verification link before signing in.',
userId: result.userId,
referralCode: result.referralCode,
emailVerificationRequired: result.emailVerificationRequired,
});
}
catch (e) {
const msg = (0, safeError_1.clientErrorMessage)(e, 'Registration failed');
const status = msg === 'Email is already registered' || msg === 'Phone number already registered'
? 409
: 400;
res.status(status).json({ error: msg });
}
}
async function validateReferralCode(req, res) {
try {
const code = (req.params.code || req.query.code);
if (!code) {
res.status(400).json({ error: 'Referral code required' });
return;
}
const { validateReferralCode: validate } = await Promise.resolve().then(() => __importStar(require('../services/referralService')));
const result = await validate(code);
res.json(result);
}
catch (e) {
const msg = e instanceof Error ? e.message : 'Validation failed';
res.status(400).json({ error: msg });
}
}
/**
* Public captcha configuration for the login form (Turnstile or built-in math).
*/
async function getCaptchaConfig(_req, res) {
const settings = await settingsRepository.getSettings();
const afterFailures = settings.login_captcha_after_failures;
const provider = captchaService.getCaptchaProvider();
res.json({
enabled: captchaService.isCaptchaAvailable(afterFailures),
provider,
siteKey: provider === 'turnstile' ? captchaService.getCaptchaSiteKey() : null,
afterFailures,
});
}
/**
* Issues a fresh captcha challenge (math prompt, or Turnstile site key hint).
*/
async function getCaptchaChallenge(_req, res) {
const settings = await settingsRepository.getSettings();
if (!captchaService.isCaptchaAvailable(settings.login_captcha_after_failures)) {
res.status(404).json({ error: 'Captcha is disabled' });
return;
}
res.json(captchaService.createLoginCaptchaChallenge());
}
/**
* Authenticates a user with email and password, optionally requiring a TOTP code when 2FA is enabled.
* @param req - Request body: `email`, `password`, optional `totpCode`. IP and user-agent are forwarded for audit.
* @param res - JSON with access/refresh tokens on success, 401 on invalid credentials.
*/
async function login(req, res) {
try {
const { email, password, totpCode, captchaToken } = req.body;
if (!email || !password) {
res.status(400).json({ error: 'Email and password required' });
return;
}
const result = await authService.login(email, password, totpCode, {
ipAddress: req.ip || undefined,
userAgent: (0, clientDevice_1.resolveClientUserAgent)(req),
visitorSupportToken: (0, optionalAuth_1.readVisitorToken)(req),
}, captchaToken);
res.json(result);
}
catch (e) {
const code = e.code;
const status = code === 'EMAIL_NOT_VERIFIED' ? 403
: code === 'ACCOUNT_LOCKED' ? 429
: code === 'CAPTCHA_REQUIRED' || code === 'CAPTCHA_INVALID' ? 400
: 401;
res.status(status).json({
error: (0, safeError_1.clientErrorMessage)(e, 'Login failed'),
...(code ? { code } : {}),
...(e.lockedUntil
? { lockedUntil: e.lockedUntil }
: {}),
...(e.retryAfterMinutes != null
? { retryAfterMinutes: e.retryAfterMinutes }
: {}),
...(e.captcha
? { captcha: e.captcha }
: {}),
});
}
}
/**
* Issues a new access/refresh token pair using a valid refresh token.
* @param req - Request body: `refreshToken`.
* @param res - JSON with new tokens on success, 401 if the refresh token is invalid or expired.
*/
async function refresh(req, res) {
try {
const { refreshToken } = req.body;
if (!refreshToken) {
res.status(400).json({ error: 'Refresh token required' });
return;
}
const result = await authService.refreshTokens(refreshToken);
res.json(result);
}
catch (e) {
const msg = e instanceof Error ? e.message : 'Invalid refresh token';
res.status(401).json({ error: msg });
}
}
/**
* Starts TOTP 2FA setup for the authenticated user and returns the secret and QR code data.
* @param req - Authenticated request; user ID is taken from the JWT.
* @param res - JSON with TOTP setup details on success, 400 on failure.
*/
async function setup2FA(req, res) {
try {
const userId = req.user.userId;
const { password, totpCode } = req.body;
const result = await authService.setupTotp(userId, {
password,
totpCode,
auditContext: {
ipAddress: req.ip || undefined,
userAgent: req.get('user-agent') || undefined,
},
});
res.json(result);
}
catch (e) {
const msg = e instanceof Error ? e.message : 'Setup failed';
res.status(400).json({ error: msg });
}
}
/**
* Confirms and enables TOTP 2FA for the authenticated user using a verification code.
* @param req - Authenticated request. Body: `code` (TOTP verification code).
* @param res - JSON `{ message: '2FA enabled' }` on success, 400 if the code is missing or invalid.
*/
async function enable2FA(req, res) {
try {
const userId = req.user.userId;
const { code } = req.body;
if (!code) {
res.status(400).json({ error: 'Code required' });
return;
}
const result = await authService.enableTotp(userId, code, {
ipAddress: req.ip || undefined,
userAgent: req.get('user-agent') || undefined,
});
res.json({ message: '2FA enabled', recoveryCodes: result.recoveryCodes });
}
catch (e) {
const msg = e instanceof Error ? e.message : 'Invalid code';
res.status(400).json({ error: msg });
}
}
/**
* Revokes the refresh token in the request body (logout).
*/
async function logout(req, res) {
try {
const { refreshToken } = req.body;
if (!refreshToken) {
res.status(400).json({ error: 'Refresh token required' });
return;
}
await authService.logout(refreshToken, {
ipAddress: req.ip || undefined,
userAgent: req.get('user-agent') || undefined,
});
res.json({ message: 'Logged out' });
}
catch (e) {
const msg = e instanceof Error ? e.message : 'Logout failed';
res.status(400).json({ error: msg });
}
}
/**
* Revokes all refresh tokens for the authenticated user.
*/
async function logoutAll(req, res) {
try {
const userId = req.user.userId;
await authService.logoutAll(userId, {
ipAddress: req.ip || undefined,
userAgent: req.get('user-agent') || undefined,
});
res.json({ message: 'Logged out from all devices' });
}
catch (e) {
const msg = e instanceof Error ? e.message : 'Logout failed';
res.status(400).json({ error: msg });
}
}
async function disable2FA(req, res) {
try {
const userId = req.user.userId;
const { password, code } = req.body;
if (!password || !code) {
res.status(400).json({ error: 'password and code are required' });
return;
}
await authService.disableTotp(userId, password, code, {
ipAddress: req.ip || undefined,
userAgent: req.get('user-agent') || undefined,
});
res.json({ message: '2FA disabled' });
}
catch (e) {
const msg = e instanceof Error ? e.message : 'Disable failed';
res.status(400).json({ error: msg });
}
}
async function regenerateRecoveryCodes(req, res) {
try {
const userId = req.user.userId;
const { code } = req.body;
if (!code) {
res.status(400).json({ error: 'TOTP code required' });
return;
}
const result = await authService.regenerateRecoveryCodes(userId, code, {
ipAddress: req.ip || undefined,
userAgent: req.get('user-agent') || undefined,
});
res.json({ recoveryCodes: result.recoveryCodes });
}
catch (e) {
const msg = e instanceof Error ? e.message : 'Regeneration failed';
res.status(400).json({ error: msg });
}
}
/**
* Changes the authenticated user's password after verifying the current password.
* @param req - Authenticated request. Body: `currentPassword`, `newPassword`.
* @param res - JSON `{ message: 'Password updated' }` on success, 400 on validation or auth failure.
*/
async function changePassword(req, res) {
try {
const userId = req.user.userId;
const { currentPassword, newPassword } = req.body;
if (!currentPassword || !newPassword) {
res.status(400).json({ error: 'Current password and new password required' });
return;
}
await authService.changePassword(userId, currentPassword, newPassword, {
ipAddress: req.ip || undefined,
userAgent: req.get('user-agent') || undefined,
});
res.json({ message: 'Password updated. Please sign in again.' });
}
catch (e) {
const msg = e instanceof Error ? e.message : 'Password change failed';
res.status(400).json({ error: msg });
}
}
/**
* Sends a verification email to the authenticated user's address on file.
* @param req - Authenticated request
* @param res - JSON with success message; includes devVerifyUrl in non-production console mode
*/
async function sendVerificationEmail(req, res) {
try {
const userId = req.user.userId;
const result = await emailVerificationService.sendVerificationEmailForUser(userId);
res.json(result);
}
catch (e) {
const msg = e instanceof Error ? e.message : 'Failed to send verification email';
const status = msg === 'Email is already verified' ? 400 : 400;
res.status(status).json({ error: msg });
}
}
/**
* Confirms email ownership using a single-use token from the verification link.
* @param req - Body or query: `token`
* @param res - JSON success message on valid token
*/
async function verifyEmail(req, res) {
try {
const token = (typeof req.body?.token === 'string' ? req.body.token : null) ||
(typeof req.query.token === 'string' ? req.query.token : null);
const result = await emailVerificationService.verifyEmailToken(token || '');
res.json(result);
}
catch (e) {
const msg = e instanceof Error ? e.message : 'Verification failed';
res.status(400).json({ error: msg });
}
}
async function resendVerificationEmail(req, res) {
try {
const { email } = req.body;
if (!email?.trim()) {
res.status(400).json({ error: 'Email is required' });
return;
}
const result = await emailVerificationService.requestVerificationResendByEmail(email);
res.json(result);
}
catch (e) {
const msg = e instanceof Error ? e.message : 'Request failed';
res.status(400).json({ error: msg });
}
}
async function forgotPassword(req, res) {
try {
const { email } = req.body;
if (!email?.trim()) {
res.status(400).json({ error: 'Email is required' });
return;
}
const result = await passwordResetService.requestPasswordReset(email);
res.json(result);
}
catch (e) {
const msg = e instanceof Error ? e.message : 'Request failed';
res.status(400).json({ error: msg });
}
}
async function resetPassword(req, res) {
try {
const { token, newPassword } = req.body;
if (!token || !newPassword) {
res.status(400).json({ error: 'token and newPassword are required' });
return;
}
const result = await passwordResetService.resetPasswordWithToken(token, newPassword);
res.json(result);
}
catch (e) {
const msg = e instanceof Error ? e.message : 'Reset failed';
res.status(400).json({ error: msg });
}
}
async function validateResetToken(req, res) {
try {
const token = req.params.token ||
(typeof req.query.token === 'string' ? req.query.token : '');
const result = await passwordResetService.validateResetToken(token);
res.json(result);
}
catch (e) {
res.status(400).json({ error: e instanceof Error ? e.message : 'Invalid token' });
}
}
//# sourceMappingURL=authController.js.map