password-strength-meter.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /* global zxcvbn */
  2. window.wp = window.wp || {};
  3. var passwordStrength;
  4. (function($){
  5. wp.passwordStrength = {
  6. /**
  7. * Determine the strength of a given password
  8. *
  9. * @param string password1 The password
  10. * @param array blacklist An array of words that will lower the entropy of the password
  11. * @param string password2 The confirmed password
  12. */
  13. meter : function( password1, blacklist, password2 ) {
  14. if ( ! $.isArray( blacklist ) )
  15. blacklist = [ blacklist.toString() ];
  16. if (password1 != password2 && password2 && password2.length > 0)
  17. return 5;
  18. if ( 'undefined' === typeof window.zxcvbn ) {
  19. // Password strength unknown.
  20. return -1;
  21. }
  22. var result = zxcvbn( password1, blacklist );
  23. return result.score;
  24. },
  25. /**
  26. * Builds an array of data that should be penalized, because it would lower the entropy of a password if it were used
  27. *
  28. * @return array The array of data to be blacklisted
  29. */
  30. userInputBlacklist : function() {
  31. var i, userInputFieldsLength, rawValuesLength, currentField,
  32. rawValues = [],
  33. blacklist = [],
  34. userInputFields = [ 'user_login', 'first_name', 'last_name', 'nickname', 'display_name', 'email', 'url', 'description', 'weblog_title', 'admin_email' ];
  35. // Collect all the strings we want to blacklist
  36. rawValues.push( document.title );
  37. rawValues.push( document.URL );
  38. userInputFieldsLength = userInputFields.length;
  39. for ( i = 0; i < userInputFieldsLength; i++ ) {
  40. currentField = $( '#' + userInputFields[ i ] );
  41. if ( 0 === currentField.length ) {
  42. continue;
  43. }
  44. rawValues.push( currentField[0].defaultValue );
  45. rawValues.push( currentField.val() );
  46. }
  47. // Strip out non-alphanumeric characters and convert each word to an individual entry
  48. rawValuesLength = rawValues.length;
  49. for ( i = 0; i < rawValuesLength; i++ ) {
  50. if ( rawValues[ i ] ) {
  51. blacklist = blacklist.concat( rawValues[ i ].replace( /\W/g, ' ' ).split( ' ' ) );
  52. }
  53. }
  54. // Remove empty values, short words, and duplicates. Short words are likely to cause many false positives.
  55. blacklist = $.grep( blacklist, function( value, key ) {
  56. if ( '' === value || 4 > value.length ) {
  57. return false;
  58. }
  59. return $.inArray( value, blacklist ) === key;
  60. });
  61. return blacklist;
  62. }
  63. };
  64. // Back-compat.
  65. passwordStrength = wp.passwordStrength.meter;
  66. })(jQuery);