97 lines
2.6 KiB
TypeScript
97 lines
2.6 KiB
TypeScript
import {
|
|
APIGatewayProxyEvent,
|
|
APIGatewayProxyResult,
|
|
Context,
|
|
} from 'aws-lambda';
|
|
import { JwtPayload } from 'jsonwebtoken';
|
|
import { prismaClient } from '../../../../common/database/prisma.lambda.service';
|
|
import { safeHandler } from '../../../../common/utils/handlers/safeHandler';
|
|
import ApiError from '../../../../common/utils/helper/ApiError';
|
|
import { TokenService } from '../../../host/services/token.service';
|
|
|
|
const tokenService = new TokenService(prismaClient);
|
|
|
|
export const handler = safeHandler(
|
|
async (
|
|
event: APIGatewayProxyEvent,
|
|
context?: Context,
|
|
): Promise<APIGatewayProxyResult> => {
|
|
// Parse request body
|
|
let body: { refreshToken?: string };
|
|
|
|
try {
|
|
body = event.body ? JSON.parse(event.body) : {};
|
|
} catch (error) {
|
|
throw new ApiError(400, 'Invalid JSON in request body');
|
|
}
|
|
|
|
const { refreshToken } = body;
|
|
|
|
if (!refreshToken) {
|
|
throw new ApiError(400, 'Refresh token is required');
|
|
}
|
|
|
|
// Verify refresh token
|
|
const decodedToken = await tokenService.verifyRefreshToken(refreshToken);
|
|
|
|
if (!decodedToken || typeof decodedToken === 'string') {
|
|
throw new ApiError(401, 'Invalid or expired refresh token');
|
|
}
|
|
|
|
const payload = decodedToken as JwtPayload;
|
|
|
|
if (payload.type !== 'refresh') {
|
|
throw new ApiError(401, 'Token is not a refresh token');
|
|
}
|
|
|
|
const userId = payload.sub;
|
|
|
|
if (!userId) {
|
|
throw new ApiError(401, 'Invalid token payload');
|
|
}
|
|
|
|
// Check if user exists
|
|
const user = await prismaClient.user.findUnique({
|
|
where: { id: parseInt(userId, 10) },
|
|
select: { id: true, isActive: true },
|
|
});
|
|
|
|
if (!user || !user.isActive) {
|
|
throw new ApiError(401, 'User not found or inactive');
|
|
}
|
|
|
|
// Check if refresh token exists in database and is not blacklisted
|
|
const tokenRecord = await prismaClient.token.findFirst({
|
|
where: {
|
|
token: refreshToken,
|
|
userXid: parseInt(userId, 10),
|
|
tokenType: 'refresh',
|
|
isBlackListed: false,
|
|
},
|
|
});
|
|
|
|
if (!tokenRecord) {
|
|
throw new ApiError(401, 'Refresh token is invalid or blacklisted');
|
|
}
|
|
|
|
// Generate new access token
|
|
const newAccessToken = await tokenService.generateAuthToken(Number(userId));
|
|
|
|
return {
|
|
statusCode: 200,
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'Access-Control-Allow-Origin': '*',
|
|
},
|
|
body: JSON.stringify({
|
|
success: true,
|
|
message: 'Access token generated successfully',
|
|
data: {
|
|
accessToken: newAccessToken.access.token,
|
|
accessTokenExpires: newAccessToken.access.expires,
|
|
},
|
|
}),
|
|
};
|
|
},
|
|
);
|