checkpassword / server.js
CultriX's picture
Update server.js
e4ae666 verified
const express = require("express");
const axios = require("axios");
const crypto = require("crypto");
const fs = require("fs");
const app = express();
app.use(express.json());
const PORT = process.env.PORT || 8080;
let apiCount = 0;
// Load the API count from a file on server start
fs.readFile("apiCount.txt", "utf8", (err, data) => {
if (!err) {
apiCount = parseInt(data);
}
});
// Endpoint to check if a password is breached
app.post("/checkPassword", async (req, res) => {
try {
apiCount++;
const password = req.body.password;
if (!password) {
return res.status(400).send("Password is required");
}
// Hash the password using SHA-1
const sha1Hash = crypto
.createHash("sha1")
.update(password)
.digest("hex")
.toUpperCase();
// Get the first 5 characters (prefix) of the hash
const prefix = sha1Hash.substring(0, 5);
// Query the Pwned Passwords API
const response = await axios.get(
`https://api.pwnedpasswords.com/range/${prefix}`
);
// Check if the password hash is in the response
const suffixes = response.data.split("\r\n");
let breached = false;
let breachCount = 0;
suffixes.forEach((suffix) => {
const [hashSuffix, count] = suffix.split(":");
if (prefix + hashSuffix === sha1Hash) {
breached = true;
breachCount = parseInt(count);
}
});
// Return the result with api count
if (breached) {
res.json({ breached: true, breachCount, apiCount });
} else {
res.json({ breached: false, apiCount });
}
// Save the updated API count to the file
fs.writeFile("apiCount.txt", apiCount.toString(), (err) => {
if (err) {
console.error("Error saving API count:", err);
}
});
} catch (error) {
console.error("Error:", error);
res.status(500).send("Internal Server Error");
}
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});