CustomerLogin.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. /**
  3. * FecShop file.
  4. *
  5. * @link http://www.fecshop.com/
  6. * @copyright Copyright (c) 2016 FecShop Software LLC
  7. * @license http://www.fecshop.com/license/
  8. */
  9. namespace fecshop\models\mysqldb\customer;
  10. use fecshop\models\mysqldb\Customer;
  11. use Yii;
  12. use yii\base\Model;
  13. /**
  14. * @author Terry Zhao <2358269014@qq.com>
  15. * @since 1.0
  16. */
  17. class CustomerLogin extends Model
  18. {
  19. public $email;
  20. public $password;
  21. //public $captcha;
  22. private $_customer;
  23. public function rules()
  24. {
  25. return [
  26. [['email', 'password'], 'required'],
  27. ['email', 'email'],
  28. ['password', 'validatePassword'],
  29. ];
  30. }
  31. public function validatePassword($attribute, $params)
  32. {
  33. if (!$this->hasErrors()) {
  34. $customer = $this->getCustomer();
  35. if (!$customer) {
  36. $this->addError($attribute, 'email is not exist');
  37. } elseif (!$customer->validatePassword($this->password)) {
  38. $this->addError($attribute, 'user password is not correct');
  39. }
  40. }
  41. }
  42. public function getCustomer()
  43. {
  44. if ($this->_customer === null) {
  45. $this->_customer = Customer::findByEmail($this->email);
  46. }
  47. return $this->_customer;
  48. }
  49. /**
  50. * @param int $duration the duration in seconds
  51. * 对于参数$duration:
  52. * 1. 当不开启cookie时,$duration的设置是无效的,yii2只会从user组件Yii::$app->user->authTimeout
  53. * 中读取过期时间
  54. * 2. 当开启cookie,$duration是有效的,会设置cookie的过期时间。
  55. * 如果不传递时间,默认使用 Yii::$service->session->timeout的值。
  56. * 总之,为了方便处理cookie和session的超时时间,统一使用
  57. * session的超时时间,这样做的好处为,可以让account 和 cart session的超时时间保持一致
  58. * @return bool whether the user is logged in
  59. */
  60. public function login($duration = 0)
  61. {
  62. if (!$duration) {
  63. if (Yii::$service->session->timeout) {
  64. $duration = Yii::$service->session->timeout;
  65. }
  66. }
  67. if ($this->validate()) {
  68. return \Yii::$app->user->login($this->getCustomer(), $duration);
  69. } else {
  70. return false;
  71. }
  72. }
  73. }