· 8 years ago · Dec 26, 2017, 03:00 PM
1<?php
2
3namespace api\components;
4
5use common\models\User;
6use yii\helpers\ArrayHelper;
7use yii\web\BadRequestHttpException;
8
9class QueryParamAuth extends \yii\filters\auth\QueryParamAuth
10{
11 /**
12 * @var string the parameter name for passing the access token
13 */
14 public $tokenParam = 'access-token';
15
16 /**
17 * @var string
18 */
19 public $serviceId = 'service_id';
20
21 /**
22 * @inheritdoc
23 */
24 public function authenticate($user, $request, $response)
25 {
26 $headers = $request->getHeaders();
27 $authorization = $headers->get('authorization');
28 $params = $request->get();
29 if (is_null($authorization) && !isset($params['secret_key'])) {
30 return true;
31 }
32
33 if (!ArrayHelper::getValue($params, 'landing_id')) {
34 return true;
35 }
36
37 if (!is_null($authorization)) {
38 $authorizationParamsArr = explode(':', $authorization);
39
40 $serviceId = ArrayHelper::getValue($authorizationParamsArr, 0);
41 $timestamp = ArrayHelper::getValue($authorizationParamsArr, 1);
42 $signature = ArrayHelper::getValue($authorizationParamsArr, 2);
43 } elseif (isset($params['secret_key']) && isset($params['service_id']) && isset($params['timestamp'])) {
44 $serviceId = ArrayHelper::getValue($params, 'service_id');
45 $timestamp = ArrayHelper::getValue($params, 'timestamp');
46 $signature = ArrayHelper::getValue($params, 'secret_key');
47
48 unset($params['service_id']);
49 unset($params['timestamp']);
50 unset($params['secret_key']);
51 }
52
53 if ($signature) {
54 $signature = str_replace(' ', '+', $signature);
55 }
56
57 if (time() - $timestamp > 600) {
58 throw new BadRequestHttpException('timestamp - time is over');
59 }
60
61 $profile = User::find()->where(['id' => $serviceId])->one();
62 if (is_null($profile)) {
63 throw new BadRequestHttpException('service_id wrong');
64 }
65 $accessToken = $profile->auth_key;
66 $signature2 = $this->generationSignature($serviceId, $timestamp, $params, $accessToken);
67
68 if ($signature != $signature2) {
69 throw new BadRequestHttpException('signature - invalid signature');
70 }
71
72 if (!empty($accessToken)) {
73 $identity = $user->loginByAccessToken($accessToken, get_class($this));
74 if ($identity !== null) {
75 return $identity;
76 }
77 }
78
79 return true;
80 }
81
82 /**
83 * @param $serviceId
84 * @param $timestamp
85 * @param $params
86 * @param $secretKey
87 * @return string
88 */
89 private function generationSignature($serviceId, $timestamp, $params, $secretKey)
90 {
91 $data = $serviceId . $timestamp . http_build_query($params);
92 $signature = base64_encode(hash_hmac('sha256', $data, $secretKey, true));
93
94 return $signature;
95 }
96}