password-strength.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import React from 'react';
  2. import zxcvbn from 'misago/services/zxcvbn';
  3. export const STYLES = [
  4. 'progress-bar-danger',
  5. 'progress-bar-warning',
  6. 'progress-bar-warning',
  7. 'progress-bar-primary',
  8. 'progress-bar-success'
  9. ];
  10. export const LABELS = [
  11. gettext("Entered password is very weak."),
  12. gettext("Entered password is weak."),
  13. gettext("Entered password is average."),
  14. gettext("Entered password is strong."),
  15. gettext("Entered password is very strong.")
  16. ];
  17. export default class extends React.Component {
  18. constructor(props) {
  19. super(props);
  20. this._score = 0;
  21. this._password = null;
  22. this._inputs = [];
  23. this.state = {
  24. loaded: false
  25. };
  26. }
  27. componentDidMount() {
  28. zxcvbn.load().then(() => {
  29. this.setState({ loaded: true });
  30. });
  31. }
  32. getScore(password, inputs) {
  33. let cacheStale = false;
  34. if (password !== this._password) {
  35. cacheStale = true;
  36. }
  37. if (inputs.length !== this._inputs.length) {
  38. cacheStale = true;
  39. } else {
  40. inputs.map((value, i) => {
  41. if (value.trim() !== this._inputs[i]) {
  42. cacheStale = true;
  43. }
  44. });
  45. }
  46. if (cacheStale) {
  47. this._score = zxcvbn.scorePassword(password, inputs);
  48. this._password = password;
  49. this._inputs = inputs.map(function(value) {
  50. return value.trim();
  51. });
  52. }
  53. return this._score;
  54. }
  55. render() {
  56. if (!this.state.loaded) return null;
  57. /* jshint ignore:start */
  58. let score = this.getScore(this.props.password, this.props.inputs);
  59. return <div className="help-block password-strength">
  60. <div className="progress">
  61. <div className={"progress-bar " + STYLES[score]}
  62. style={{width: (20 + (20 * score)) + '%'}}
  63. role="progress-bar"
  64. aria-valuenow={score}
  65. aria-valuemin="0"
  66. aria-valuemax="4">
  67. <span className="sr-only">
  68. {LABELS[score]}
  69. </span>
  70. </div>
  71. </div>
  72. <p className="text-small">
  73. {LABELS[score]}
  74. </p>
  75. </div>;
  76. /* jshint ignore:end */
  77. }
  78. }