Skip to content

Instantly share code, notes, and snippets.

@aflansburg
Last active July 1, 2020 22:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aflansburg/5ac21684e167ecf1f755c8d7dc0cec40 to your computer and use it in GitHub Desktop.
Save aflansburg/5ac21684e167ecf1f755c8d7dc0cec40 to your computer and use it in GitHub Desktop.
Very basic JS password strength test
// example usage - feel free to edit the STRENGTH_CRITERIA in the Password class
const { Password } = require('./Password')
const password_strong = new Password('Password123');
const password_weak = new Password('password');
const password_very_weak = new Password('1234');
password_strong.getPasswordStrength();
// { result: 'pretty strong', weakness: [ [ 'spec_char_count' ] ] }
password_weak.getPasswordStrength();
// {
// result: 'weak',
// weakness: [ [ 'spec_char_count' ], [ 'capital_letter_count' ] ]
// }
password_very_weak.getPasswordStrength();
// {
// result: 'very weak',
// weakness: [
// [ 'alpha_numeric_count' ],
// [ 'spec_char_count' ],
// [ 'capital_letter_count' ]
// ]
// }
class Password {
constructor(password){
this.password = password;
this.getPassword = () => password
this.STRENGTH_CRITERIA = {
length: 8,
alpha_numeric_count: 8,
spec_char_count: 1,
capital_letter_count: 1
};
this.spec_char_count = password.split('').filter(char => '!@#$^&%*()+=-[]/{}|:<>?,.'.split('').includes(char))
.length;
this.alpha_numeric_count = password
.split('')
.filter(char => !'!@#$^&%*()+=-[]/{}|:<>?,.'.split('').includes(char)).length;
this.capital_letter_count = password
.split('')
.filter(char => !'!@#$^&%*()+=-[]/{}|:<>?,.0123456789'.split('').includes(char))
.filter(char => char === char.toUpperCase()).length;
}
getPasswordStrength() {
let passwordStrength = {
result: null,
weakness: []
};
Object.keys(this.STRENGTH_CRITERIA).forEach(key => {
if (this[key] < this.STRENGTH_CRITERIA[key]) {
passwordStrength = {
...passwordStrength,
result: getResult([...passwordStrength.weakness, [key]]),
weakness: [...passwordStrength.weakness, [key]]
};
}
});
function getResult(weakness){
if (weakness.length == 2) {
return 'weak';
} else if (weakness.length >= 3) {
return 'very weak';
} else {
return 'pretty strong';
}
}
return passwordStrength;
}
}
module.exports = {
Password
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment