You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

104 lines
2.1 KiB

8 months ago
  1. <?php
  2. namespace app\models;
  3. class User extends \yii\base\BaseObject implements \yii\web\IdentityInterface
  4. {
  5. public $id;
  6. public $username;
  7. public $password;
  8. public $authKey;
  9. public $accessToken;
  10. private static $users = [
  11. '100' => [
  12. 'id' => '100',
  13. 'username' => 'admin',
  14. 'password' => 'admin',
  15. 'authKey' => 'test100key',
  16. 'accessToken' => '100-token',
  17. ],
  18. '101' => [
  19. 'id' => '101',
  20. 'username' => 'demo',
  21. 'password' => 'demo',
  22. 'authKey' => 'test101key',
  23. 'accessToken' => '101-token',
  24. ],
  25. ];
  26. /**
  27. * {@inheritdoc}
  28. */
  29. public static function findIdentity($id)
  30. {
  31. return isset(self::$users[$id]) ? new static(self::$users[$id]) : null;
  32. }
  33. /**
  34. * {@inheritdoc}
  35. */
  36. public static function findIdentityByAccessToken($token, $type = null)
  37. {
  38. foreach (self::$users as $user) {
  39. if ($user['accessToken'] === $token) {
  40. return new static($user);
  41. }
  42. }
  43. return null;
  44. }
  45. /**
  46. * Finds user by username
  47. *
  48. * @param string $username
  49. * @return static|null
  50. */
  51. public static function findByUsername($username)
  52. {
  53. foreach (self::$users as $user) {
  54. if (strcasecmp($user['username'], $username) === 0) {
  55. return new static($user);
  56. }
  57. }
  58. return null;
  59. }
  60. /**
  61. * {@inheritdoc}
  62. */
  63. public function getId()
  64. {
  65. return $this->id;
  66. }
  67. /**
  68. * {@inheritdoc}
  69. */
  70. public function getAuthKey()
  71. {
  72. return $this->authKey;
  73. }
  74. /**
  75. * {@inheritdoc}
  76. */
  77. public function validateAuthKey($authKey)
  78. {
  79. return $this->authKey === $authKey;
  80. }
  81. /**
  82. * Validates password
  83. *
  84. * @param string $password password to validate
  85. * @return bool if password provided is valid for current user
  86. */
  87. public function validatePassword($password)
  88. {
  89. return $this->password === $password;
  90. }
  91. }