2022-08-29 18:09:28 +00:00
|
|
|
import { NextApiRequest, NextApiResponse } from 'next';
|
|
|
|
import { getAccessToken } from '../../lib/api/remote';
|
|
|
|
|
|
|
|
import Cookies from 'cookies';
|
2022-09-09 18:50:28 +00:00
|
|
|
import { COOKIE_KEYS, REDIRECT_URL } from '../../lib/constants';
|
2022-08-29 18:34:46 +00:00
|
|
|
import { decrypt } from '../../lib/utils/crypto';
|
|
|
|
|
2022-09-11 09:31:09 +00:00
|
|
|
const inProd = process.env.NODE_ENV === 'production';
|
|
|
|
|
2022-08-29 18:09:28 +00:00
|
|
|
export default async function handler(
|
|
|
|
req: NextApiRequest,
|
|
|
|
res: NextApiResponse
|
|
|
|
) {
|
2022-09-09 14:37:42 +00:00
|
|
|
if (!req.query.code || !req.query.state) {
|
|
|
|
return res.redirect('/');
|
|
|
|
}
|
|
|
|
|
|
|
|
const getAuth = await getAccessToken(req.query.code as string);
|
2022-09-11 09:31:09 +00:00
|
|
|
const cookies = new Cookies(req, res, { keys: COOKIE_KEYS, secure: inProd });
|
2022-08-29 18:34:46 +00:00
|
|
|
|
2022-09-09 14:37:42 +00:00
|
|
|
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 ||
|
2022-09-09 18:50:28 +00:00
|
|
|
parsedState.redirect_uri !== REDIRECT_URL
|
2022-09-09 14:37:42 +00:00
|
|
|
) {
|
|
|
|
return res.redirect('/');
|
2022-08-29 18:09:28 +00:00
|
|
|
}
|
2022-08-29 18:34:46 +00:00
|
|
|
|
2022-09-09 14:37:42 +00:00
|
|
|
cookies.set('authorization', getAuth.access_token, {
|
|
|
|
expires: new Date(Date.now() + getAuth.expires_in * 1000),
|
2022-09-11 09:31:09 +00:00
|
|
|
secure: inProd,
|
2022-09-09 18:50:28 +00:00
|
|
|
sameSite: 'strict',
|
2022-09-09 14:37:42 +00:00
|
|
|
signed: true,
|
|
|
|
});
|
|
|
|
|
|
|
|
cookies.set('validation', undefined, {
|
|
|
|
expires: new Date(0),
|
2022-09-11 09:31:09 +00:00
|
|
|
secure: inProd,
|
2022-09-09 18:50:28 +00:00
|
|
|
sameSite: 'strict',
|
2022-09-09 14:37:42 +00:00
|
|
|
signed: true,
|
|
|
|
});
|
2022-08-29 18:09:28 +00:00
|
|
|
}
|
2022-09-09 14:37:42 +00:00
|
|
|
|
|
|
|
res.redirect('/');
|
2022-08-29 18:09:28 +00:00
|
|
|
}
|