games_app/backend/dist/controllers/authController.js
2026-06-29 15:01:23 +02:00

305 lines
12 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.login = login;
exports.refresh = refresh;
exports.setup2FA = setup2FA;
exports.enable2FA = enable2FA;
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");
/**
* 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 = e instanceof Error ? e.message : 'Registration failed';
res.status(400).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 });
}
}
/**
* 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 } = 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: req.get('user-agent') || undefined,
visitorSupportToken: (0, optionalAuth_1.readVisitorToken)(req),
});
res.json(result);
}
catch (e) {
const msg = e instanceof Error ? e.message : 'Login failed';
const code = e.code;
const status = code === 'EMAIL_NOT_VERIFIED' ? 403 : 401;
res.status(status).json(code ? { error: msg, code } : { error: msg });
}
}
/**
* 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 result = await authService.setupTotp(userId);
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;
}
await authService.enableTotp(userId, code);
res.json({ message: '2FA enabled' });
}
catch (e) {
const msg = e instanceof Error ? e.message : 'Invalid code';
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);
res.json({ message: 'Password updated' });
}
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