88 lines
2.5 KiB
TypeScript
88 lines
2.5 KiB
TypeScript
import { ROLE, USER_STATUS } from '../../../common/utils/constants/common.constant';
|
|
import { APIGatewayProxyEvent, APIGatewayProxyResult, Context } from 'aws-lambda';
|
|
import { prismaClient } from '../../../common/database/prisma.lambda.service';
|
|
import { safeHandler } from '../../../common/utils/handlers/safeHandler';
|
|
import ApiError from '../../../common/utils/helper/ApiError';
|
|
import { generateOtpHelper } from '../../../common/utils/helper/sendOtp';
|
|
import { MinglarService } from './../services/minglar.service';
|
|
import { sendOtpEmailForMinglarAdmin } from '../services/sendOTPEmail.service';
|
|
|
|
const minglarService = new MinglarService(prismaClient);
|
|
|
|
export const handler = safeHandler(async (
|
|
event: APIGatewayProxyEvent,
|
|
context?: Context
|
|
): Promise<APIGatewayProxyResult> => {
|
|
// Parse request body
|
|
let body: { email?: string };
|
|
|
|
try {
|
|
body = event.body ? JSON.parse(event.body) : {};
|
|
} catch (error) {
|
|
throw new ApiError(400, 'Invalid JSON in request body');
|
|
}
|
|
|
|
const { email } = body;
|
|
|
|
if (!email) {
|
|
throw new ApiError(400, 'Email is required');
|
|
}
|
|
|
|
const emailToLowerCase = email.toLowerCase()
|
|
|
|
const user = await prismaClient.user.findUnique({
|
|
where: { emailAddress: emailToLowerCase, isActive: true, userStatus: USER_STATUS.INVITED },
|
|
select: { emailAddress: true, id: true, userPassword: true, roleXid: true },
|
|
});
|
|
|
|
if (!user) {
|
|
throw new ApiError(403, 'You are not allowed to register directly. Please contact minglar admin.');
|
|
}
|
|
|
|
if (![ROLE.MINGLAR_ADMIN, ROLE.CO_ADMIN, ROLE.ACCOUNT_MANAGER].includes(user.roleXid)) {
|
|
throw new ApiError(403, 'You are not allowed to register directly. Please contact minglar admin.');
|
|
}
|
|
|
|
|
|
if (user.userPassword) {
|
|
throw new ApiError(404, 'User is already registered. Please login.');
|
|
}
|
|
|
|
let newUser;
|
|
|
|
if (user && !user.userPassword) {
|
|
// ✅ User already exists but without password → reuse record
|
|
newUser = user;
|
|
}
|
|
|
|
const otpResult = await generateOtpHelper(
|
|
prismaClient, // ⭐ pass Prisma from here
|
|
Number(newUser?.id),
|
|
newUser?.emailAddress,
|
|
'Register',
|
|
6,
|
|
5
|
|
);
|
|
|
|
|
|
if (!otpResult || !otpResult.otp) {
|
|
throw new ApiError(500, 'Failed to send OTP');
|
|
}
|
|
|
|
await sendOtpEmailForMinglarAdmin(newUser?.emailAddress, otpResult.otp);
|
|
|
|
return {
|
|
statusCode: 200,
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'Access-Control-Allow-Origin': '*',
|
|
},
|
|
body: JSON.stringify({
|
|
success: true,
|
|
message: 'OTP sent successfully.',
|
|
data: {},
|
|
}),
|
|
};
|
|
});
|
|
|