mocksaml/pages/api/saml/auth.ts

51 lines
1.3 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 {
createResponseForm,
createResponseXML,
fetchPrivateKey,
fetchPublicKey,
signResponseXML,
} from 'utils';
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') {
const email = req.body.email;
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-02-24 17:23:35 +00:00
const id = createHash('sha256').update(email).digest('hex');
2022-02-23 13:48:20 +00:00
2022-02-22 08:17:41 +00:00
const user: User = {
id,
email,
firstName: id,
lastName: id,
};
const xml = await createResponseXML({
2022-02-22 10:20:01 +00:00
idpIdentityId: config.entityId,
2022-02-22 08:17:41 +00:00
audience: req.body.audience,
acsUrl: req.body.acsUrl,
2022-02-23 12:35:58 +00:00
samlReqId: req.body.id,
2022-02-22 08:17:41 +00:00
user: user,
});
2022-02-28 19:14:19 +00:00
const signingKey = fetchPrivateKey();
const publicKey = fetchPublicKey();
2022-02-22 08:17:41 +00:00
const xmlSigned = await signResponseXML(xml, signingKey, publicKey);
2022-02-22 10:20:01 +00:00
2022-02-22 08:17:41 +00:00
const encodedSamlResponse = Buffer.from(xmlSigned).toString('base64');
const html = createResponseForm(req.body.relayState, encodedSamlResponse, req.body.acsUrl);
res.send(html);
2022-02-22 05:36:06 +00:00
} else {
res.status(405).send(`Method ${req.method} Not Allowed`);
}
}