mocksaml/pages/api/saml/auth.ts

53 lines
1.5 KiB
TypeScript
Raw Normal View History

2022-02-24 17:23:35 +00:00
import { createHash } from 'crypto';
import config from 'lib/env';
import type { NextApiRequest, NextApiResponse } from 'next';
2022-02-22 08:17:41 +00:00
import type { User } from 'types';
import { createResponseXML, signResponseXML } from 'utils';
import saml from '@boxyhq/saml20';
import { getEntityId } from 'lib/entity-id';
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
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 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({
idpIdentityId: getEntityId(config.entityId, req.query.namespace as any),
2022-03-02 23:50:03 +00:00
audience,
acsUrl,
samlReqId: id,
2022-02-22 08:17:41 +00:00
user: user,
});
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`);
}
}