Skip to content

Instantly share code, notes, and snippets.

@aflansburg

aflansburg/Password.js

Last active Jul 1, 2020
Embed
What would you like to do?
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