QrcodeLoginForm.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. namespace common\modules\user\models;
  3. use Yii;
  4. use yii\base\Model;
  5. /**
  6. * Login form.
  7. */
  8. class QrcodeLoginForm extends Model
  9. {
  10. public $access_token;
  11. public $qrcode_hash;
  12. public $rememberMe = false; // 自动登录
  13. private $_user;
  14. /**
  15. * {@inheritdoc}
  16. */
  17. public function rules()
  18. {
  19. return [
  20. [['access_token', 'qrcode_hash'], 'required'],
  21. ['rememberMe', 'boolean'],
  22. ['qrcode_hash', 'validateQrcodeHash'],
  23. ];
  24. }
  25. public function attributeLabels()
  26. {
  27. return [
  28. 'access_token' => '访问令牌',
  29. 'qrcode_hash' => '二维码哈希',
  30. 'rememberMe' => '记住我',
  31. ];
  32. }
  33. /**
  34. * Validates the password.
  35. * This method serves as the inline validation for password.
  36. *
  37. * @param string $attribute the attribute currently being validated
  38. * @param array $params the additional name-value pairs given in the rule
  39. */
  40. public function validateQrcodeHash($attribute, $params)
  41. {
  42. if (!$this->hasErrors()) {
  43. $user = $this->getUser();
  44. if (!$user || !$user->validateQrcodeHash($this->qrcode_hash)) {
  45. $this->addError($attribute, '等待微信扫码登录');
  46. }
  47. }
  48. }
  49. /**
  50. * Logs in a user using the provided username and password.
  51. *
  52. * @return bool whether the user is logged in successfully
  53. */
  54. public function login()
  55. {
  56. if ($this->validate()) {
  57. return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
  58. } else {
  59. return false;
  60. }
  61. }
  62. /**
  63. * 管理员登录
  64. * @return bool
  65. * @author nodelog
  66. */
  67. public function loginAdmin()
  68. {
  69. if ($this->validate()) {
  70. if ($this->getUser()->getIsAdmin()) {
  71. return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
  72. } else {
  73. $this->addError('username', '无权登录');
  74. return false;
  75. }
  76. } else {
  77. return false;
  78. }
  79. }
  80. /**
  81. * Finds user by [[username]].
  82. *
  83. * @return User|null
  84. */
  85. protected function getUser()
  86. {
  87. if ($this->_user === null) {
  88. $this->_user = User::findIdentityByAccessToken($this->access_token);
  89. }
  90. return $this->_user;
  91. }
  92. }