2022-02-24 17:23:35 +00:00
|
|
|
import { createHash } from 'crypto';
|
|
|
|
|
import config from 'lib/env';
|
2022-03-02 21:02:13 +00:00
|
|
|
import type { NextApiRequest, NextApiResponse } from 'next';
|
2022-02-22 08:17:41 +00:00
|
|
|
import type { User } from 'types';
|
2022-04-26 17:02:12 +00:00
|
|
|
import { createResponseXML, signResponseXML } from 'utils';
|
|
|
|
|
import saml from '@boxyhq/saml20';
|
2022-02-22 05:36:06 +00:00
|
|
|
|
2022-02-22 08:17:41 +00:00
|
|
|
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
|
|
|
|
if (req.method === 'POST') {
|
2022-03-02 23:50:03 +00:00
|
|
|
const { email, audience, acsUrl, id, relayState } = req.body;
|
2022-02-23 13:48:20 +00:00
|
|
|
|
2022-03-02 21:02:13 +00:00
|
|
|
if (!email.endsWith('@example.com') && !email.endsWith('@example.org')) {
|
2022-02-22 08:17:41 +00:00
|
|
|
res.status(403).send(`${email} denied access`);
|
|
|
|
|
}
|
2022-03-02 21:02:13 +00:00
|
|
|
|
2022-03-02 23:50:03 +00:00
|
|
|
const userId = createHash('sha256').update(email).digest('hex');
|
|
|
|
|
const userName = email.split('@')[0];
|
2022-02-23 13:48:20 +00:00
|
|
|
|
2022-02-22 08:17:41 +00:00
|
|
|
const user: User = {
|
2022-03-02 23:50:03 +00:00
|
|
|
id: userId,
|
2022-02-22 08:17:41 +00:00
|
|
|
email,
|
2022-03-02 23:50:03 +00:00
|
|
|
firstName: userName,
|
|
|
|
|
lastName: userName,
|
2022-02-22 08:17:41 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const xml = await createResponseXML({
|
2022-02-22 10:20:01 +00:00
|
|
|
idpIdentityId: config.entityId,
|
2022-03-02 23:50:03 +00:00
|
|
|
audience,
|
|
|
|
|
acsUrl,
|
|
|
|
|
samlReqId: id,
|
2022-02-22 08:17:41 +00:00
|
|
|
user: user,
|
|
|
|
|
});
|
|
|
|
|
|
2022-03-02 21:06:04 +00:00
|
|
|
const xmlSigned = await signResponseXML(xml, config.privateKey, config.publicKey);
|
2022-02-22 08:17:41 +00:00
|
|
|
const encodedSamlResponse = Buffer.from(xmlSigned).toString('base64');
|
2022-04-27 20:16:05 +00:00
|
|
|
const html = saml.createPostForm(acsUrl, [
|
|
|
|
|
{
|
|
|
|
|
name: 'RelayState',
|
|
|
|
|
value: relayState,
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
name: 'SAMLResponse',
|
|
|
|
|
value: encodedSamlResponse,
|
|
|
|
|
},
|
|
|
|
|
]);
|
2022-02-22 08:17:41 +00:00
|
|
|
|
|
|
|
|
res.send(html);
|
2022-02-22 05:36:06 +00:00
|
|
|
} else {
|
|
|
|
|
res.status(405).send(`Method ${req.method} Not Allowed`);
|
|
|
|
|
}
|
|
|
|
|
}
|