import * as jwt from 'jsonwebtoken' import { logger } from '../../utils/logger' import { prismaClient as prisma } from '../../prismaClient' export async function handleUnsubscribe(req, res) { const { token } = req.query // if no token was provided if (!token) return res.send('Invalid token') // verify that the token signature matches our env signature try { jwt.verify(token, process.env.APP_SECRET || '') } catch (err) { // if the signature can't be verified let errMessage if (err.name === 'TokenExpiredError') { errMessage = 'This unsubscribe token has expired. You can unsubscribe from this email type in your user settings.' } else { errMessage = 'This unsubscribe token is invalid. You can unsubscribe from this email type in your user settings.' } return res.send(errMessage) } // once the token is verified, we can decode it to get the userId type Jwttoken = { userId: string } const { userId } = jwt.decode(token) // if the token doesn't have the necessary info if (!userId) { return res.send('Invalid token') } // and send a database request to unsubscribe from a particular email type try { await prisma.user.update({ where: { id: userId }, data: { cantDeliverEmail: true, cantDeliverEmailReason: 'BLOCKED' }, }) return res .status(200) .send('You were unsubscribed, you will no longer receive any email notifications') } catch (err) { logger.error(err) return res.send('Something went wrong, we\'re on it') } }