Completed
Push — master ( 4ae1d4...b72490 )
by Alexey
02:37
created

UserController::behaviors()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 29
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 29
rs 8.8571
c 0
b 0
f 0
cc 1
eloc 17
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
31
        // add CORS filter
32
        $behaviors['corsFilter'] = [
33
            'class' => \yii\filters\Cors::className(),
34
        ];
35
        
36
        $behaviors['authenticator'] = [
37
            'class' => CompositeAuth::className(),
38
            'only' => ['update'],
39
            'authMethods' => [
40
                'bearerAuth' => [
41
                    'class' => HttpBearerAuth::className(),
42
                ],
43
                'paramAuth' => [
44
                    'class' => QueryParamAuth::className(),
45
                    'tokenParam' => 'auth_key', // This value can be changed to its own, for example hash
46
                ],
47
                'basicAuth' => [
48
                    'class' => HttpBasicAuth::className(),
49
                    'auth' => function ($username, $password) {
50
                        return $this->processBasicAuth($username, $password);
51
                    }
52
                ],
53
            ]
54
        ];
55
        return $behaviors;
56
    }
57
58
    /**
59
     * @param string $username
60
     * @param string $password
61
     * @return User|null|array
62
     */
63
    protected function processBasicAuth($username, $password)
64
    {
65
        /** @var User $modelClass */
66
        $modelClass = $this->modelClass;
67
        /** @var User $user */
68
        if ($user = $modelClass::find()->where(['username' => $username])->one()) {
69
            return $user->validatePassword($password) ? $user : null;
70
        }
71
        return null;
72
    }
73
}
74