Skip to content
Permalink
c71eb13d40
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
190 lines (157 sloc) 5.73 KB
import express from "express";
import fido2lib from "@dannymoerkerke/fido2-lib";
import base64url from "base64url";
import crypto from "crypto";
import bcrypt from "bcrypt";
import cfg from "config";
import User from "../models/user.js";
import { verifyPassword } from "../helpers/utils.js";
// import { accountVerificationTemplate } from "../helpers/emailTemplates.js";
// import mailTo from "../helpers/mailer.js";
// import AccountVerificationCode from "../models/accountVerificationCode.js";
const mode = process.env.NODE_ENV || "dev";
const config = cfg.get(mode);
const router = express.Router();
const { Fido2Lib } = fido2lib;
const fido = new Fido2Lib({
timeout: 60000,
rpName: "FIDO2.APP",
challengeSize: 128,
attestation: "none",
cryptoParams: [-7, -257],
authenticatorAttachment: "platform",
authenticatorRequireResidentKey: false,
authenticatorUserVerification: "required",
});
router.post("/registration-options", async (req, res) => {
const { email } = req.body;
if (!email) {
return res.status(400).json({ error: "Missing email field" });
}
const userExists = await User.findOne({ email });
if (userExists) {
return res.status(400).json({ error: "User already exists" });
}
req.session.userHandle = crypto.randomBytes(32);
const registrationOptions = await fido.attestationOptions();
req.session.challenge = Buffer.from(registrationOptions.challenge);
registrationOptions.user.id = req.session.userHandle;
registrationOptions.challenge = Buffer.from(registrationOptions.challenge);
// iOS
registrationOptions.authenticatorSelection = {
authenticatorAttachment: "platform",
};
res.json(registrationOptions);
});
router.post("/register", async (req, res) => {
const { credential, email, firstName, lastName, password, userAgent } = req.body;
const challenge = new Uint8Array(req.session.challenge.data).buffer;
const base64RawId = credential.rawId;
credential.rawId = new Uint8Array(Buffer.from(credential.rawId, "base64")).buffer;
credential.response.attestationObject = base64url.decode(
credential.response.attestationObject,
"base64"
);
credential.response.clientDataJSON = base64url.decode(
credential.response.clientDataJSON,
"base64"
);
const attestationExpectations = {
challenge,
origin: config.siteUrl,
factor: "either",
};
try {
const regResult = await fido.attestationResult(credential, attestationExpectations);
const publicKey = regResult.authnrData.get("credentialPublicKeyPem");
const prevCounter = regResult.authnrData.get("counter");
const hash = bcrypt.hashSync(password, 10);
const user = await User.create({
id: req.session.userHandle,
credentialId: base64RawId,
firstName,
lastName,
email,
password: hash,
userAgent: userAgent,
publicKey: publicKey,
prevCounter: prevCounter
});
user.save();
// const secretVerificationCode = crypto.randomBytes(32).toString("hex");
// const verificationCode = await AccountVerificationCode.create({
// email: user.email,
// code: secretVerificationCode,
// });
// verificationCode.save();
// await mailTo(
// [email],
// accountVerificationTemplate(
// `${config.siteUrl}/verification/verify-account/${user.email}/${secretVerificationCode}`
// )
// );
res.json({ status: "ok" });
} catch (e) {
console.log("error", e);
res.status(500).json({ error: e });
}
});
router.post("/authentication-options", async (req, res) => {
const authnOptions = await fido.assertionOptions();
const { email } = req.body;
const user = await User.findOne({ email });
if (!user) {
return res.status(401).json({ error: "User does not exist." });
}
// if (user.status !== "active") {
// return res.status(401).json({ error: "Please activate your account first." });
// }
req.session.challenge = Buffer.from(authnOptions.challenge);
req.session.userHandle = user.id;
authnOptions.challenge = Buffer.from(authnOptions.challenge);
authnOptions.rawId = user.credentialId;
res.json(authnOptions);
});
router.post("/authenticate", async (req, res) => {
const { credential, authDuration, password, email, method } = req.body;
const user = await User.findOne({ email });
if (!user) {
return res.status(401).json({ error: "Incorrect login details" });
}
// if (user.status !== "active") {
// return res.status(401).json({ error: "Please activate your account first." });
// }
if (method === "password") {
try {
if (verifyPassword(user, password)) {
return res.status(200).json({ status: "ok" });
} else return res.status(401).json({ error: "Incorrect login details" });
} catch (err) {
return res.status(500).json({ error: "Server error: " + err.message });
}
} else {
credential.rawId = new Uint8Array(Buffer.from(credential.rawId, "base64")).buffer;
const challenge = new Uint8Array(req.session.challenge.data).buffer;
const { publicKey, prevCounter } = user
if (publicKey === "undefined" || prevCounter === undefined) {
res.status(404).json({ error: "Credential not found" });
} else {
const assertionExpectations = {
challenge,
origin: config.siteUrl,
factor: "either",
publicKey,
prevCounter,
userHandle: new Uint8Array(Buffer.from(req.session.userHandle, "base64")).buffer,
};
try {
await fido.assertionResult(credential, assertionExpectations);
await User.findOneAndUpdate({ email: email }, { authDuration: authDuration });
res.json({ status: "ok" });
} catch (e) {
res.status(500).json({ error: "Failed due internal server error: " + e.message });
}
}
}
});
export default router;