infoalloggi-monorepo/apps/infoalloggi/src/lib/basicPwGenerator.ts

31 lines
998 B
TypeScript
Raw Normal View History

2025-08-04 17:45:44 +02:00
export const generatePassword = (length = 10) => {
2025-08-28 18:27:07 +02:00
const upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const lower = "abcdefghijklmnopqrstuvwxyz";
const numbers = "0123456789";
const special = "!@#$%^&*()_+[]{}<>?/|";
2025-08-04 17:45:44 +02:00
2025-08-28 18:27:07 +02:00
// Ensure at least one from each required set
const required = [
upper[Math.floor(Math.random() * upper.length)],
lower[Math.floor(Math.random() * lower.length)],
numbers[Math.floor(Math.random() * numbers.length)],
special[Math.floor(Math.random() * special.length)],
];
2025-08-04 17:45:44 +02:00
2025-08-28 18:27:07 +02:00
const allChars = upper + lower + numbers + special;
const remainingLength = length - required.length;
const passwordArr = [...required];
2025-08-04 17:45:44 +02:00
2025-08-28 18:27:07 +02:00
for (let i = 0; i < remainingLength; i++) {
passwordArr.push(allChars[Math.floor(Math.random() * allChars.length)]);
}
2025-08-04 17:45:44 +02:00
2025-08-28 18:27:07 +02:00
// Fisher-Yates shuffle
for (let i = passwordArr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[passwordArr[i], passwordArr[j]] = [passwordArr[j], passwordArr[i]];
}
2025-08-04 17:45:44 +02:00
2025-08-28 18:27:07 +02:00
return passwordArr.join("");
2025-08-04 17:45:44 +02:00
};