Completed
Push — master ( 4f3de5...9b9e7a )
by Pavel
05:51
created

TokenController   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 144
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 10

Importance

Changes 2
Bugs 0 Features 1
Metric Value
dl 0
loc 144
rs 10
c 2
b 0
f 1
wmc 6
lcom 1
cbo 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getToken() 0 23 3
A refreshToken() 0 23 2
A buildResponse() 0 9 1
1
<?php
2
namespace App\Controller;
3
4
use App\Requests\GetTokenRequest;
5
use App\Requests\RefreshTokenRequest;
6
use App\Model\User;
7
use App\Model\AccessToken;
8
use App\Model\RefreshToken;
9
10
use Slim\Http\Request;
11
use Slim\Http\Response;
12
13
use App\Common\JsonException;
14
15
final class TokenController extends BaseController
16
{
17
    const TOKEN_TYPE = 'Bearer';
18
19
    /**
20
     * @api {post} /token Получение токена
21
     * @apiName CreateToken
22
     * @apiGroup Token
23
     *
24
     * @apiDescription Метод для получения авторизационного токена. Он отправляется в заголовке запроса:
25
     *
26
     * Authorization: Bearer xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
27
     *
28
     * @apiParam {String} username Логин
29
     * @apiParam {String} password Пароль
30
     *
31
     * @apiParamExample {json} Пример запроса:
32
     *    {
33
     *      "data":{
34
     *        "attributes":{
35
     *          "username":"[email protected]",
36
     *          "password": "qwerty"
37
     *        }
38
     *      }
39
     *    }
40
     *
41
     * @apiSuccessExample {json} Успешно (200)
42
     *     HTTP/1.1 200 OK
43
     *     {
44
     *       "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOmZhbHNlLCJhdWQiOiJza2VsZXRvbi5kZXYiLCJpYXQiOjE0NzY0Mjk4NjksImV4cCI6MTQ3NjQzMzQ2OX0.NJn_-lK28kEZyZqygLr6B-FZ2zC2-1unStayTGicP5g",
45
     *       "expires_in": 3600,
46
     *       "token_type": "Bearer",
47
     *       "refresh_token": "092ea7e36f6b9bf462cb3ca1f6f86b80"
48
     *     }
49
     *
50
     * @apiUse StandardErrors
51
     */
52
    /**
53
     * @param Request  $request
54
     * @param Response $response
55
     *
56
     * @return mixed
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use \Psr\Http\Message\ResponseInterface.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
57
     * @throws JsonException
58
     */
59
    public function getToken(Request $request, Response $response)
60
    {
61
        $params = $request->getParsedBody();
62
63
        $this->validationRequest($params, 'token', new GetTokenRequest());
64
65
        $user = User::findUserByEmail($params['data']['attributes']['username']);
66
67
        if ($user && password_verify($params['data']['attributes']['password'], $user->password)) {
68
            $token = AccessToken::createToken(
69
                $request->getUri()->getHost(),
70
                $this->settings['params']['tokenExpire'],
71
                $user
72
            );
73
            $refreshToken = RefreshToken::createRefreshToken($user);
74
        } else {
75
            throw new JsonException('token', 400, 'Invalid Attribute', 'Invalid password or username');
76
        };
77
78
        $result = $this->buildResponse($token, $refreshToken);
79
80
        return $this->renderer->jsonApiRender($response, 200, json_encode($result));
81
    }
82
83
    /**
84
     * @api {post} /refresh-token Обновление токена
85
     * @apiName RefreshToken
86
     * @apiGroup Token
87
     *
88
     * @apiDescription Метод для обновления access_token по refresh_token
89
     *
90
     * @apiParam {String} refresh_token Токен для обновления
91
     *
92
     * @apiParamExample {json} Пример запроса:
93
     *    {
94
     *      "data":{
95
     *        "attributes":{
96
     *          "refresh_token":"092ea7e36f6b9bf462cb3ca1f6f86b80"
97
     *        }
98
     *      }
99
     *    }
100
     *
101
     * @apiSuccessExample {json} Успешно (200)
102
     *     HTTP/1.1 200 OK
103
     *     {
104
     *       "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOmZhbHNlLCJhdWQiOiJza2VsZXRvbi5kZXYiLCJpYXQiOjE0NzY0Mjk4NjksImV4cCI6MTQ3NjQzMzQ2OX0.NJn_-lK28kEZyZqygLr6B-FZ2zC2-1unStayTGicP5g",
105
     *       "expires_in": 3600,
106
     *       "token_type": "Bearer",
107
     *       "refresh_token": "092ea7e36f6b9bf462cb3ca1f6f86b80"
108
     *     }
109
     *
110
     * @apiUse StandardErrors
111
     */
112
    /**
113
     * @param Request  $request
114
     * @param Response $response
115
     *
116
     * @return mixed
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use \Psr\Http\Message\ResponseInterface.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
117
     * @throws JsonException
118
     */
119
    public function refreshToken(Request $request, Response $response)
120
    {
121
        $params = $request->getParsedBody();
122
123
        $this->validationRequest($params, 'token', new RefreshTokenRequest());
124
125
        $user = RefreshToken::getUserByRefreshToken($params['data']['attributes']['refresh_token']);
126
127
        if ($user) {
128
            $token = AccessToken::createToken(
129
                $request->getUri()->getHost(),
130
                $this->settings['params']['tokenExpire'],
131
                $user
132
            );
133
            $refreshToken = RefreshToken::createRefreshToken($user);
134
        } else {
135
            throw new JsonException('token', 400, 'Invalid Attribute', 'Invalid refresh_token');
136
        };
137
138
        $result = $this->buildResponse($token, $refreshToken);
139
140
        return $this->renderer->jsonApiRender($response, 200, json_encode($result));
141
    }
142
143
    /**
144
     * @param string $token
145
     * @param string $refreshToken
146
     *
147
     * @return array
148
     */
149
    private function buildResponse($token, $refreshToken)
150
    {
151
        return [
152
            'access_token'  => $token,
153
            'expires_in'    => $this->settings['params']['tokenExpire'],
154
            'token_type'    => self::TOKEN_TYPE,
155
            'refresh_token' => $refreshToken,
156
        ];
157
    }
158
}
159