Completed
Pull Request — master (#20)
by Pavel
02:51
created

TokenController::failUnknownToken()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
namespace App\Controller;
4
5
use App\Requests\GetTokenRequest;
6
use App\Requests\RefreshTokenRequest;
7
use App\Model\User;
8
use App\Model\AccessToken;
9
use App\Model\RefreshToken;
10
use Slim\Http\Request;
11
use Slim\Http\Response;
12
use App\Common\JsonException;
13
14
class TokenController extends BaseController
15
{
16
    const TOKEN_TYPE = 'Bearer';
17
18
    /**
19
     * @api {post} /token Получение токена
20
     * @apiName CreateToken
21
     * @apiGroup Token
22
     *
23
     * @apiDescription Метод для получения авторизационного токена. Токен необходим для выполнения запросов к АПИ.
24
     * Полученный токен отправляется в заголовке запроса:
25
     * <br/>
26
     * <strong>Authorization: Bearer xxxxxxxxxxxxxxxxxxxxxxxxxxxxx</strong>
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 \Psr\Http\Message\ResponseInterface
57
     * @throws JsonException
58
     */
59
    public function getToken(Request $request, Response $response)
60
    {
61
        $params = $request->getParsedBody();
62
63
        $this->validateRequestParams($params, 'token', new GetTokenRequest());
64
65
        $user = User::findUserByEmail($params['data']['attributes']['username']);
66
        if (!$user || !password_verify($params['data']['attributes']['password'], $user->password)) {
67
            throw new JsonException('token', 400, 'Invalid Attribute', 'Invalid password or username');
68
        }
69
70
        return $this->buildTokens($request, $response, $user);
71
    }
72
73
    /**
74
     * @api {post} /refresh-token Обновление токена
75
     * @apiName RefreshToken
76
     * @apiGroup Token
77
     *
78
     * @apiDescription Метод для обновления access_token по refresh_token
79
     *
80
     * @apiParam {String} refresh_token Токен для обновления
81
     *
82
     * @apiParamExample {json} Пример запроса:
83
     *    {
84
     *      "data":{
85
     *        "attributes":{
86
     *          "refresh_token":"092ea7e36f6b9bf462cb3ca1f6f86b80"
87
     *        }
88
     *      }
89
     *    }
90
     *
91
     * @apiSuccessExample {json} Успешно (200)
92
     *     HTTP/1.1 200 OK
93
     *     {
94
     *       "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOmZhbHNlLCJhdWQiOiJza2VsZXRvbi5kZXYiLCJpYXQiOjE0NzY0Mjk4NjksImV4cCI6MTQ3NjQzMzQ2OX0.NJn_-lK28kEZyZqygLr6B-FZ2zC2-1unStayTGicP5g",
95
     *       "expires_in": 3600,
96
     *       "token_type": "Bearer",
97
     *       "refresh_token": "092ea7e36f6b9bf462cb3ca1f6f86b80"
98
     *     }
99
     *
100
     * @apiUse StandardErrors
101
     */
102
103
    /**
104
     * @param Request  $request
105
     * @param Response $response
106
     *
107
     * @return \Psr\Http\Message\ResponseInterface
108
     * @throws JsonException
109
     */
110
    public function refreshToken(Request $request, Response $response)
111
    {
112
        $params = $request->getParsedBody();
113
114
        $this->validateRequestParams($params, 'token', new RefreshTokenRequest());
115
116
        $user = RefreshToken::getUserByToken($params['data']['attributes']['refresh_token']);
117
        if (!$user) {
118
            throw new JsonException('token', 400, 'Invalid Attribute', 'Invalid refresh_token');
119
        }
120
121
        return $this->buildTokens($request, $response, $user);
122
    }
123
124
    /**
125
     * @param Request $request
126
     * @param Response $response
127
     * @param User $user
128
     * @return \Psr\Http\Message\ResponseInterface
129
     */
130
    protected function buildTokens(Request $request, Response $response, User $user)
131
    {
132
        $accessToken = AccessToken::createToken(
133
            $user,
134
            $request->getUri()->getHost(),
135
            $this->settings['accessToken']
136
        );
137
        $refreshToken = RefreshToken::createToken($user);
138
139
        $result = [
140
            'token_type'    => self::TOKEN_TYPE,
141
            'access_token'  => $accessToken,
142
            'refresh_token' => $refreshToken,
143
            'expires_in'    => $this->settings['accessToken']['ttl'],
144
        ];
145
146
        return $this->apiRenderer->jsonResponse($response, 200, json_encode($result));
147
    }
148
}
149