This repository has been archived on 2024-06-14. You can view files and clone it, but cannot push or open issues or pull requests.
icynet-admin/pages/api/callback.ts
2022-09-11 12:31:09 +03:00

50 lines
1.3 KiB
TypeScript

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('/');
}