import { NextApiRequest, NextApiResponse } from 'next'; import { getAccessToken } from '../../lib/api/remote'; import Cookies from 'cookies'; import { COOKIE_KEYS, REDIRECT_URL } from '../../lib/constants'; import { decrypt } from '../../lib/utils/crypto'; const inProd = process.env.NODE_ENV === 'production'; export default async function handler( req: NextApiRequest, res: NextApiResponse ) { if (!req.query.code || !req.query.state) { return res.redirect('/'); } const getAuth = await getAccessToken(req.query.code as string); const cookies = new Cookies(req, res, { keys: COOKIE_KEYS, secure: inProd }); if (getAuth) { const decrypted = decrypt(req.query.state as string); const stateToken = cookies.get('validation', { signed: true }); const parsedState = JSON.parse(decrypted); if ( parsedState.state !== stateToken || parsedState.redirect_uri !== REDIRECT_URL ) { return res.redirect('/'); } cookies.set('authorization', getAuth.access_token, { expires: new Date(Date.now() + getAuth.expires_in * 1000), secure: inProd, sameSite: 'strict', signed: true, }); cookies.set('validation', undefined, { expires: new Date(0), secure: inProd, sameSite: 'strict', signed: true, }); } res.redirect('/'); }