password-strength.vue 1.97 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
<template lang="pug">
  .password-strength
    v-progress-linear(
      :color='passwordStrengthColor'
      v-model='passwordStrength'
      height='2'
    )
    .caption(v-if='!hideText', :class='passwordStrengthColor + "--text"') {{passwordStrengthText}}
</template>

<script>
import zxcvbn from 'zxcvbn'
import _ from 'lodash'

export default {
  props: {
    value: {
      type: String,
      default: ''
    },
    hideText: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      passwordStrength: 0,
      passwordStrengthColor: 'grey',
      passwordStrengthText: ''
    }
  },
  watch: {
    value(newValue) {
      this.checkPasswordStrength(newValue)
    }
  },
  methods: {
    checkPasswordStrength: _.debounce(function (pwd) {
      if (!pwd || pwd.length < 1) {
        this.passwordStrength = 0
        this.passwordStrengthColor = 'grey'
        this.passwordStrengthText = ''
        return
      }
      const strength = zxcvbn(pwd)
47
      this.passwordStrength = _.round((strength.score + 1) / 5 * 100)
48 49
      if (this.passwordStrength <= 20) {
        this.passwordStrengthColor = 'red'
50
        this.passwordStrengthText = this.$t('common:password.veryWeak')
51 52
      } else if (this.passwordStrength <= 40) {
        this.passwordStrengthColor = 'orange'
53
        this.passwordStrengthText = this.$t('common:password.weak')
54 55
      } else if (this.passwordStrength <= 60) {
        this.passwordStrengthColor = 'teal'
56
        this.passwordStrengthText = this.$t('common:password.average')
57 58
      } else if (this.passwordStrength <= 80) {
        this.passwordStrengthColor = 'green'
59
        this.passwordStrengthText = this.$t('common:password.strong')
60 61
      } else {
        this.passwordStrengthColor = 'green'
62
        this.passwordStrengthText = this.$t('common:password.veryStrong')
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
      }
    }, 100)
  }
}
</script>

<style lang="scss">

.password-strength > .caption {
  width: 100%;
  left: 0;
  margin: 0;
  position: absolute;
  top: calc(100% + 5px);
}

</style>