50 lines
1.4 KiB
TypeScript
50 lines
1.4 KiB
TypeScript
import { NextApiRequest, NextApiResponse } from 'next';
|
|
import { getAccessToken } from '../../lib/api/remote';
|
|
|
|
import Cookies from 'cookies';
|
|
import { COOKIE_KEYS, PUBLIC_URL } from '../../lib/constants';
|
|
import { decrypt } from '../../lib/utils/crypto';
|
|
|
|
const redirect = `${PUBLIC_URL}/api/callback`;
|
|
|
|
export default async function handler(
|
|
req: NextApiRequest,
|
|
res: NextApiResponse
|
|
) {
|
|
if (req.query.code) {
|
|
if (!req.query.state) {
|
|
return res.redirect('/');
|
|
}
|
|
|
|
const getAuth = await getAccessToken(req.query.code as string);
|
|
const cookies = new Cookies(req, res, { keys: COOKIE_KEYS });
|
|
|
|
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
|
|
) {
|
|
return res.redirect('/');
|
|
}
|
|
|
|
cookies.set('authorization', getAuth.access_token, {
|
|
expires: new Date(Date.now() + getAuth.expires_in * 1000),
|
|
secure: process.env.NODE_ENV === 'production',
|
|
signed: true,
|
|
});
|
|
|
|
cookies.set('validation', undefined, {
|
|
expires: new Date(0),
|
|
secure: process.env.NODE_ENV === 'production',
|
|
signed: true,
|
|
});
|
|
}
|
|
|
|
res.redirect('/');
|
|
}
|
|
}
|