nodejs-authentication/app/v1/middlewares/verifyPasswordPwned.js
2025-03-11 10:51:27 +00:00

45 lines
1.2 KiB
JavaScript

const axios = require("axios");
const crypto = require("crypto");
const verifyPwned = async (req, res, next) => {
try {
var query = req.body;
if (query.hasOwnProperty('password')) {
const password = query.password;
const hash = crypto.createHash("sha1").update(password).digest("hex");
const prefix = hash.slice(0, 5);
const suffix = hash.slice(5);
const pwned = await axios.get("https://api.pwnedpasswords.com/range/" + prefix);
var pwnd_data = pwned.data.split("\r\n");
pwnd_data = pwnd_data.map((elm) => elm.slice(0, elm.indexOf(":")));
var password_leaked = false
pwnd_data.forEach((elm) => {
if (suffix === elm.toLowerCase()) {
password_leaked = true
}
});
if (password_leaked) {
return res.status(400).send(
{ code: 400, error: "Please choose another one - Leaked password" }
);
} else {
next();
}
} else {
return res.status(401).send({ code: 401, error: 'Please specific your password and confirm password' });
}
} catch (error) {
return res.status(500).send({ code: 401, error: 'Internal Server Error' });
}
};
module.exports = {
verifyPwned
}