Przejdź do głównej zawartości

04. Generator haseł

Zbudujesz generator haseł z konfiguracją — długość, wielkie/małe litery, cyfry, znaki specjalne. Z oceną siły hasła i historią wygenerowanych haseł.

Czego się nauczysz?

  • Losowanie znaków z zestawów w JavaScript
  • Suwak (range input) jako kontrolka
  • Clipboard API (kopiowanie do schowka)
  • Ocena siły hasła algorytmem
src/utils/passwordGenerator.js
const CHARS = {
uppercase: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
lowercase: 'abcdefghijklmnopqrstuvwxyz',
digits: '0123456789',
special: '!@#$%^&*()_+-=[]{}|;:,.<>?',
};
export function generatePassword(options) {
const { length, useUppercase, useLowercase, useDigits, useSpecial } = options;
let charset = '';
const guaranteed = [];
if (useUppercase) { charset += CHARS.uppercase; guaranteed.push(randomChar(CHARS.uppercase)); }
if (useLowercase) { charset += CHARS.lowercase; guaranteed.push(randomChar(CHARS.lowercase)); }
if (useDigits) { charset += CHARS.digits; guaranteed.push(randomChar(CHARS.digits)); }
if (useSpecial) { charset += CHARS.special; guaranteed.push(randomChar(CHARS.special)); }
if (!charset) return '';
const remaining = Array.from(
{ length: length - guaranteed.length },
() => randomChar(charset)
);
return shuffle([...guaranteed, ...remaining]).join('');
}
function randomChar(str) {
return str[Math.floor(Math.random() * str.length)];
}
function shuffle(arr) {
return arr.sort(() => Math.random() - 0.5);
}
export function calculateStrength(password) {
let score = 0;
if (password.length >= 8) score++;
if (password.length >= 12) score++;
if (password.length >= 16) score++;
if (/[A-Z]/.test(password)) score++;
if (/[a-z]/.test(password)) score++;
if (/[0-9]/.test(password)) score++;
if (/[^A-Za-z0-9]/.test(password)) score++;
if (score <= 2) return 'weak';
if (score <= 4) return 'medium';
if (score <= 6) return 'strong';
return 'very-strong';
}
  • Suwak długości hasła (8-32 znaki)
  • Checkboxy: wielkie litery, małe litery, cyfry, znaki specjalne
  • Generowanie hasła
  • Kopiowanie do schowka (Clipboard API)
  • Przycisk “Generuj nowe”
Ocena: 3.0

Powodzenia!

Generator haseł to projekt, który można zrobić szybko i elegancko. Gwarantowanie że hasło zawiera co najmniej jeden znak z każdego wybranego zestawu jest subtelnym, ale ważnym detalem — nie pomijaj tego kroku. Clipboard API jest proste: navigator.clipboard.writeText(password).