1 | <?php |
||
60 | class HttpBasicAuth extends AuthMethod |
||
61 | { |
||
62 | /** |
||
63 | * @var string the HTTP authentication realm |
||
64 | */ |
||
65 | public $realm = 'api'; |
||
66 | /** |
||
67 | * @var callable a PHP callable that will authenticate the user with the HTTP basic auth information. |
||
68 | * The callable receives a username and a password as its parameters. It should return an identity object |
||
69 | * that matches the username and password. Null should be returned if there is no such identity. |
||
70 | * The callable will be called only if current user is not authenticated. |
||
71 | * |
||
72 | * The following code is a typical implementation of this callable: |
||
73 | * |
||
74 | * ```php |
||
75 | * function ($username, $password) { |
||
76 | * return \app\models\User::findOne([ |
||
77 | * 'username' => $username, |
||
78 | * 'password' => $password, |
||
79 | * ]); |
||
80 | * } |
||
81 | * ``` |
||
82 | * |
||
83 | * If this property is not set, the username information will be considered as an access token |
||
84 | * while the password information will be ignored. The [[\yii\web\User::loginByAccessToken()]] |
||
85 | * method will be called to authenticate and login the user. |
||
86 | */ |
||
87 | public $auth; |
||
88 | |||
89 | |||
90 | /** |
||
91 | * {@inheritdoc} |
||
92 | */ |
||
93 | 25 | public function authenticate($user, $request, $response) |
|
94 | { |
||
95 | 25 | list($username, $password) = $request->getAuthCredentials(); |
|
96 | |||
97 | 25 | if ($this->auth) { |
|
98 | 10 | if ($username !== null || $password !== null) { |
|
99 | 10 | $identity = $user->getIdentity() ?: call_user_func($this->auth, $username, $password); |
|
100 | |||
101 | 10 | if ($identity === null) { |
|
102 | 4 | $this->handleFailure($response); |
|
103 | 6 | } elseif ($user->getIdentity(false) !== $identity) { |
|
104 | 3 | $user->switchIdentity($identity); |
|
105 | } |
||
106 | |||
107 | 6 | return $identity; |
|
108 | } |
||
109 | 15 | } elseif ($username !== null) { |
|
110 | 12 | $identity = $user->loginByAccessToken($username, get_class($this)); |
|
111 | 12 | if ($identity === null) { |
|
112 | 3 | $this->handleFailure($response); |
|
113 | } |
||
114 | |||
115 | 9 | return $identity; |
|
116 | } |
||
117 | |||
118 | 3 | return null; |
|
119 | } |
||
120 | |||
121 | /** |
||
122 | * {@inheritdoc} |
||
123 | */ |
||
124 | 3 | public function challenge($response) |
|
128 | } |
||
129 |