Completed
Push — master ( 347dc9...7ddec5 )
by Alexey
07:24
created

UserController::behaviors()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 23
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 23
rs 9.0856
c 0
b 0
f 0
cc 1
eloc 15
nc 1
nop 0
1
<?php
2
3
namespace api\modules\v1\controllers;
4
5
use Yii;
6
use api\modules\v1\models\User;
7
use yii\rest\ActiveController;
8
use yii\filters\auth\CompositeAuth;
9
use yii\filters\auth\HttpBasicAuth;
10
use yii\filters\auth\HttpBearerAuth;
11
use yii\filters\auth\QueryParamAuth;
12
13
/**
14
 * Class UserController
15
 * @package api\modules\v1\controllers
16
 */
17
class UserController extends ActiveController
18
{
19
    /**
20
     * @var string
21
     */
22
    public $modelClass = 'api\modules\v1\models\User';
23
24
    /**
25
     * @inheritdoc
26
     */
27
    public function behaviors()
28
    {
29
        $behaviors = parent::behaviors();
30
        $behaviors['authenticator'] = [
31
            'class' => CompositeAuth::className(),
32
            'only' => ['update'],
33
            'authMethods' => [
34
                'bearerAuth' => [
35
                    'class' => HttpBearerAuth::className(),
36
                ],
37
                'paramAuth' => [
38
                    'class' => QueryParamAuth::className(),
39
                    'tokenParam' => 'auth_key', // This value can be changed to its own, for example hash
40
                ],
41
                'basicAuth' => [
42
                    'class' => HttpBasicAuth::className(),
43
                    'auth' => function ($username, $password) {
44
                        return $this->processBasicAuth($username, $password);
45
                    }
46
                ],
47
            ]
48
        ];
49
        return $behaviors;
50
    }
51
52
    /**
53
     * @param string $username
54
     * @param string $password
55
     * @return User|null
56
     */
57
    protected function processBasicAuth($username, $password)
58
    {
59
        /** @var User $modelClass */
60
        $modelClass = $this->modelClass;
61
        /** @var User $user */
62
        if ($user = $modelClass::find()->where(['username' => $username])->one()) {
63
            return $user->validatePassword($password) ? $user : null;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $user->validatePa...assword) ? $user : null also could return the type array which is incompatible with the documented return type null|api\modules\v1\models\User.
Loading history...
64
        }
65
        return null;
66
    }
67
}
68