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

50 lines
1.4 KiB
TypeScript
Raw Normal View History

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