feat: user activation and emails
This commit is contained in:
@@ -1,34 +1,70 @@
|
||||
import * as crypto from 'crypto';
|
||||
import { z } from 'zod';
|
||||
import { fromZodError } from 'zod-validation-error';
|
||||
import SubscribeEmail from '../../../components/emails/subscribe';
|
||||
import prisma from '../../../prisma/prisma';
|
||||
import { ResponseSchema, SubscribeFormSchema } from '../../utils/types';
|
||||
import { ApiResponse } from '../../../utils/apiResponse';
|
||||
import { sendEmail } from '../../../utils/sender';
|
||||
import { ResponseSchema, SubscribeFormSchema } from '../../../utils/types';
|
||||
|
||||
export const dynamic = 'force-dynamic'; // defaults to force-static
|
||||
export async function POST(request: Request) {
|
||||
const body = await request.json();
|
||||
const validation = SubscribeFormSchema.safeParse(body);
|
||||
if (!validation.success) {
|
||||
const message = fromZodError(validation.error);
|
||||
return new Response(message.message, { status: 400 });
|
||||
return ApiResponse(400, 'Bad request');
|
||||
}
|
||||
|
||||
const { email, targetingAllowed } = validation.data;
|
||||
const { email } = validation.data;
|
||||
|
||||
const userAlreadyConfirmed = await prisma.user.findUnique({
|
||||
where: {
|
||||
email,
|
||||
confirmed: true
|
||||
}
|
||||
});
|
||||
|
||||
if (userAlreadyConfirmed) {
|
||||
if (userAlreadyConfirmed.deleted) {
|
||||
await prisma.user.update({
|
||||
where: {
|
||||
email
|
||||
},
|
||||
data: {
|
||||
deleted: false
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const message: z.infer<typeof ResponseSchema> = {
|
||||
message: `Thank you for subscribing!`
|
||||
};
|
||||
|
||||
return ApiResponse(200, JSON.stringify(message));
|
||||
}
|
||||
|
||||
const code = crypto
|
||||
.createHash('sha256')
|
||||
.update(`${process.env.SECRET_HASH}${email}}`)
|
||||
.digest('hex');
|
||||
|
||||
await prisma.user.upsert({
|
||||
create: {
|
||||
email,
|
||||
targetingAllowed
|
||||
code
|
||||
},
|
||||
update: {
|
||||
targetingAllowed
|
||||
code
|
||||
},
|
||||
where: {
|
||||
email
|
||||
}
|
||||
});
|
||||
|
||||
await sendEmail([email], 'Welcome!', SubscribeEmail(code));
|
||||
|
||||
const message: z.infer<typeof ResponseSchema> = {
|
||||
message: `${email} subscribed!`
|
||||
message: `Thank you! You will now receive an email to ${email} to confirm the subscription.`
|
||||
};
|
||||
return new Response(JSON.stringify(message), { status: 200 });
|
||||
|
||||
return ApiResponse(200, JSON.stringify(message));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user