From 628e760b8bacbd1e70b29a0e4c732486caef1055 Mon Sep 17 00:00:00 2001 From: Aswin V Date: Tue, 22 Feb 2022 13:47:41 +0530 Subject: [PATCH] Validate email and build SAML response --- pages/api/saml/auth.ts | 44 ++++++++++++++++++++++++++++++++++++++---- 1 file changed, 40 insertions(+), 4 deletions(-) diff --git a/pages/api/saml/auth.ts b/pages/api/saml/auth.ts index 67bf527..4704a4c 100644 --- a/pages/api/saml/auth.ts +++ b/pages/api/saml/auth.ts @@ -1,8 +1,44 @@ -import type { NextApiRequest, NextApiResponse } from "next"; +import type { NextApiRequest, NextApiResponse } from 'next'; +import type { User } from 'types'; +import { + createResponseForm, + createResponseXML, + fetchPrivateKey, + fetchPublicKey, + signResponseXML, +} from 'utils'; -export async function handler(req: NextApiRequest, res: NextApiResponse) { - if (req.method === "POST") { - res.status(200).json({ name: "John Doe" }); +export default async function handler(req: NextApiRequest, res: NextApiResponse) { + if (req.method === 'POST') { + console.log(req.body); + const email = req.body.email; + if (!email.endsWith('@example.com')) { + res.status(403).send(`${email} denied access`); + } + const id = email.replace('@example.com', ''); + const user: User = { + id, + email, + firstName: id, + lastName: id, + }; + console.log(`πŸ•ΊπŸ»`, user); + + const xml = await createResponseXML({ + idpIdentityId: req.body.audience, + audience: req.body.audience, + acsUrl: req.body.acsUrl, + user: user, + }); + + const signingKey = await fetchPrivateKey(); + const publicKey = await fetchPublicKey(); + const xmlSigned = await signResponseXML(xml, signingKey, publicKey); + const encodedSamlResponse = Buffer.from(xmlSigned).toString('base64'); + + const html = createResponseForm(req.body.relayState, encodedSamlResponse, req.body.acsUrl); + + res.send(html); } else { res.status(405).send(`Method ${req.method} Not Allowed`); }