71 lines
2.0 KiB
TypeScript
71 lines
2.0 KiB
TypeScript
import { APIGatewayProxyEvent, APIGatewayProxyResult, Context } from 'aws-lambda';
|
|
import { safeHandler } from '../../../../../common/utils/handlers/safeHandler';
|
|
import { prismaClient } from '../../../../../common/database/prisma.lambda.service';
|
|
import { HostService } from '../../../services/host.service';
|
|
import { TokenService } from '../../../services/token.service';
|
|
import { GetHostLoginResponseDTO } from '../../../dto/host.dto';
|
|
import ApiError from '../../../../../common/utils/helper/ApiError';
|
|
|
|
const hostService = new HostService(prismaClient);
|
|
const tokenService = new TokenService(prismaClient);
|
|
|
|
export const handler = safeHandler(async (
|
|
event: APIGatewayProxyEvent,
|
|
context?: Context
|
|
): Promise<APIGatewayProxyResult> => {
|
|
// Parse request body
|
|
let body: { emailAddress?: string; userPassword?: string };
|
|
|
|
try {
|
|
body = event.body ? JSON.parse(event.body) : {};
|
|
} catch (error) {
|
|
throw new ApiError(400, 'Invalid JSON in request body');
|
|
}
|
|
|
|
const { emailAddress, userPassword } = body;
|
|
|
|
if (!emailAddress || !userPassword) {
|
|
throw new ApiError(400, 'Email and password are required');
|
|
}
|
|
|
|
const emailToLowerCase = emailAddress.toLowerCase()
|
|
|
|
const loginForHost = await hostService.loginForHost(emailToLowerCase, userPassword);
|
|
|
|
if (!loginForHost) {
|
|
throw new ApiError(400, 'Failed to login');
|
|
}
|
|
|
|
if (!loginForHost.userPassword) {
|
|
throw new ApiError(401, 'Invalid credentials');
|
|
}
|
|
|
|
const generateTokenForHost = await tokenService.generateAuthToken(
|
|
loginForHost.id
|
|
);
|
|
|
|
if (!generateTokenForHost) {
|
|
throw new ApiError(500, 'Failed to generate token');
|
|
}
|
|
|
|
const loginForHostResponse = new GetHostLoginResponseDTO(
|
|
loginForHost,
|
|
generateTokenForHost.access.token,
|
|
generateTokenForHost.refresh.token
|
|
);
|
|
|
|
return {
|
|
statusCode: 200,
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'Access-Control-Allow-Origin': '*',
|
|
},
|
|
body: JSON.stringify({
|
|
success: true,
|
|
message: 'Login successful',
|
|
data: loginForHostResponse,
|
|
}),
|
|
};
|
|
});
|
|
|