43 lines
1.5 KiB
JavaScript
43 lines
1.5 KiB
JavaScript
export const generatePassword = (name, email) => {
|
|
// Combine name and email, and convert to lowercase
|
|
const combinedStr = (name + email).toLowerCase();
|
|
|
|
// Define character pools
|
|
const specialChars = "@#*";
|
|
const numbers = "0123456789";
|
|
const alphaLower = combinedStr.match(/[a-z]/g) || [];
|
|
const alphaUpper = combinedStr.match(/[A-Z]/g) || [];
|
|
|
|
// Ensure at least one character from each category
|
|
const specialChar = specialChars.charAt(
|
|
Math.floor(Math.random() * specialChars.length)
|
|
);
|
|
const numberChar = numbers.charAt(Math.floor(Math.random() * numbers.length));
|
|
const lowerChar =
|
|
alphaLower.length > 0
|
|
? alphaLower[Math.floor(Math.random() * alphaLower.length)]
|
|
: String.fromCharCode(Math.floor(Math.random() * 26) + 97);
|
|
const upperChar =
|
|
alphaUpper.length > 0
|
|
? alphaUpper[Math.floor(Math.random() * alphaUpper.length)]
|
|
: String.fromCharCode(Math.floor(Math.random() * 26) + 65);
|
|
|
|
// Combine required characters
|
|
let passwordChars = [specialChar, numberChar, lowerChar, upperChar];
|
|
|
|
// Fill remaining positions with random characters from the combined string
|
|
const allChars = combinedStr + specialChars + numbers;
|
|
while (passwordChars.length < 8) {
|
|
passwordChars.push(
|
|
allChars.charAt(Math.floor(Math.random() * allChars.length))
|
|
);
|
|
}
|
|
|
|
// Shuffle characters to ensure randomness
|
|
passwordChars = passwordChars.sort(() => Math.random() - 0.5);
|
|
|
|
// Generate password of length 8
|
|
const password = passwordChars.slice(0, 8).join("");
|
|
|
|
return password;
|
|
}; |