Advertisement
Guest User

Untitled

a guest
Mar 13th, 2017
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.71 KB | None | 0 0
  1. <?php
  2.  
  3. namespace app\models;
  4.  
  5. use yii\base\Model;
  6. use Yii;
  7.  
  8. /**
  9. * Simplified model with validation rules.
  10. * All characters are allowed (you want emojis in the password? Go ahead).
  11. * There are three basic rules for the user:
  12. * 1) Minimum password length.
  13. * 2) Minimum password entropy.
  14. * 3) Don't use common names you see on the screen as password.
  15. *
  16. * @property string $email
  17. */
  18. class User extends Model
  19. {
  20. const MIN_PASSWORD = 10;
  21. const MAX_PASSWORD = 64;
  22. const MIN_ENTROPY = 2;
  23.  
  24. /**
  25. * @var string Raw password to be validated
  26. */
  27. public $rawPassword;
  28.  
  29. /**
  30. * @inheritdoc
  31. */
  32. public function rules()
  33. {
  34. return [
  35. // obviously we need these 2
  36. [['email', 'rawPassword'], 'required'],
  37. // email should be email, also Yii 2 limits max email size to 254 characters so we don't have to worry about that
  38. ['email', 'email'],
  39. // email needs to be unique in database to identify user
  40. ['email', 'unique'],
  41. // password must not be shorter than self::MIN_PASSWORD
  42. // 10 characters minimum is required nowadays
  43. // but it shouldn't be a problem especially when we don't force bullshit composition
  44. // maximum limit is not that important but we should add reasonable one as well
  45. ['rawPassword', 'string', 'min' => self::MIN_PASSWORD, 'max' => self::MAX_PASSWORD],
  46. // lazy copy-paste check: password must not be the same as user's email address
  47. ['rawPassword', 'compare', 'compareAttribute' => 'email', 'operator' => '!='],
  48. // lazy copy-paste check: password must not be the same as application's name
  49. ['rawPassword', 'compare', 'compareValue' => Yii::$app->name, 'operator' => '!='],
  50. // lazy copy-paste check: password must not be the same as application's URL
  51. ['rawPassword', 'compare', 'compareValue' => \yii\helpers\Url::home(), 'operator' => '!='],
  52. // password's entropy must be greater than self::MIN_ENTROPY (the smaller number = more repetition allowed)
  53. // some examples: 'aaaaaaaaaa' => 0, '0123456789' => 3.322
  54. ['rawPassword', function ($attribute, $params, $validator) {
  55. $entropy = 0;
  56. $size = mb_strlen($this->$attribute, Yii::$app->charset ?: 'UTF-8');
  57. foreach (count_chars($this->$attribute, 1) as $frequency) {
  58. $p = $frequency / $size;
  59. $entropy -= $p * log($p) / log(2);
  60. }
  61. if ($entropy < self::MIN_ENTROPY) {
  62. $this->addError($attribute, 'You must choose more complex password.');
  63. }
  64. }],
  65. ];
  66. }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement