-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathLoginPresenter.php
More file actions
343 lines (300 loc) · 11.2 KB
/
LoginPresenter.php
File metadata and controls
343 lines (300 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
<?php
namespace App\V1Module\Presenters;
use App\Helpers\MetaFormats\Attributes\Post;
use App\Helpers\MetaFormats\Attributes\Path;
use App\Helpers\MetaFormats\Validators\VArray;
use App\Helpers\MetaFormats\Validators\VEmail;
use App\Helpers\MetaFormats\Validators\VInt;
use App\Helpers\MetaFormats\Validators\VString;
use App\Exceptions\BadRequestException;
use App\Exceptions\ForbiddenRequestException;
use App\Exceptions\FrontendErrorMappings;
use App\Exceptions\InvalidAccessTokenException;
use App\Exceptions\InvalidApiArgumentException;
use App\Exceptions\WrongCredentialsException;
use App\Helpers\ExternalLogin\ExternalServiceAuthenticator;
use App\Helpers\MetaFormats\Validators\VUuid;
use App\Model\Entity\SecurityEvent;
use App\Model\Entity\User;
use App\Model\Repository\Logins;
use App\Model\Repository\SecurityEvents;
use App\Model\Repository\Users;
use App\Model\View\UserViewFactory;
use App\Security\AccessManager;
use App\Security\ACL\IUserPermissions;
use App\Security\CredentialsAuthenticator;
use App\Security\Identity;
use App\Security\Roles;
use App\Security\TokenScope;
use Nette\Security\AuthenticationException;
use Nette\Http\IResponse;
/**
* Endpoints used to log a user in
*/
class LoginPresenter extends BasePresenter
{
/**
* @var AccessManager
* @inject
*/
public $accessManager;
/**
* @var CredentialsAuthenticator
* @inject
*/
public $credentialsAuthenticator;
/**
* @var ExternalServiceAuthenticator
* @inject
*/
public $externalServiceAuthenticator;
/**
* @var Logins
* @inject
*/
public $logins;
/**
* @var SecurityEvents
* @inject
*/
public $securityEvents;
/**
* @var Users
* @inject
*/
public $users;
/**
* @var UserViewFactory
* @inject
*/
public $userViewFactory;
/**
* @var IUserPermissions
* @inject
*/
public $userAcl;
/**
* @var Roles
* @inject
*/
public $roles;
/**
* Sends response with an access token, if the user exists.
* @param User $user
* @param int|null $expiration in seconds, null for default expiration
* @throws AuthenticationException
* @throws ForbiddenRequestException
* @throws InvalidAccessTokenException
*/
private function sendAccessTokenResponse(User $user, ?int $expiration = null)
{
if ($expiration !== null && ($expiration > $this->accessManager->getExpiration() || $expiration <= 0)) {
$expiration = null; // invalid values are ignored
}
$token = $this->accessManager->issueToken($user, null, [TokenScope::MASTER, TokenScope::REFRESH], $expiration);
$this->getUser()->login(new Identity($user, $this->accessManager->decodeToken($token)));
$this->sendSuccessResponse(
[
"accessToken" => $token,
"user" => $this->userViewFactory->getFullUser($user)
]
);
}
/**
* Log in using user credentials
* @POST
* @throws AuthenticationException
* @throws ForbiddenRequestException
* @throws InvalidAccessTokenException
* @throws WrongCredentialsException
*/
#[Post("username", new VEmail(), "User's E-mail")]
#[Post("password", new VString(1), "Password")]
#[Post("expiration", new VInt(), "Token expiration in seconds (not greater than the default)", required: false)]
public function actionDefault()
{
$req = $this->getRequest();
$username = $req->getPost("username");
$password = $req->getPost("password");
$expiration = $req->getPost("expiration");
$user = $this->credentialsAuthenticator->authenticate($username, $password);
$this->verifyUserIpLock($user);
$user->updateLastAuthenticationAt();
$this->users->flush();
$event = SecurityEvent::createLoginEvent($this->getHttpRequest()->getRemoteAddress(), $user);
$this->securityEvents->persist($event);
$this->sendAccessTokenResponse($user, $expiration);
}
/**
* Log in using an external authentication service
* @POST
* @throws AuthenticationException
* @throws ForbiddenRequestException
* @throws InvalidAccessTokenException
* @throws WrongCredentialsException
* @throws BadRequestException
*/
#[Post("token", new VString(1), "JWT external authentication token")]
#[Post("expiration", new VInt(), "Token expiration in seconds (not greater than the default)", required: false)]
#[Path("authenticatorName", new VString(), "Identifier of the external authenticator", required: true)]
public function actionExternal($authenticatorName)
{
$req = $this->getRequest();
$user = $this->externalServiceAuthenticator->authenticate($authenticatorName, $req->getPost("token"));
$this->verifyUserIpLock($user);
$user->updateLastAuthenticationAt();
$this->users->flush();
$event = SecurityEvent::createExternalLoginEvent($this->getHttpRequest()->getRemoteAddress(), $user);
$this->securityEvents->persist($event);
$this->sendAccessTokenResponse($user, $req->getPost("expiration"));
}
public function checkTakeOver($userId)
{
$user = $this->users->findOrThrow($userId);
if (!$this->userAcl->canTakeOver($user)) {
throw new ForbiddenRequestException();
}
}
/**
* Takeover user account with specified user identification.
* @POST
* @LoggedIn
* @throws AuthenticationException
* @throws ForbiddenRequestException
* @throws InvalidAccessTokenException
*/
#[Path("userId", new VUuid(), required: true)]
public function actionTakeOver($userId)
{
$user = $this->users->findOrThrow($userId);
$this->sendAccessTokenResponse($user);
}
/**
* @throws ForbiddenRequestException
*/
public function checkRefresh()
{
if (!$this->isInScope(TokenScope::REFRESH)) {
throw new ForbiddenRequestException(
sprintf("Only tokens in the '%s' scope can be refreshed", TokenScope::REFRESH)
);
}
}
/**
* Refresh the access token of current user
* @POST
* @LoggedIn
* @throws ForbiddenRequestException
*/
public function actionRefresh()
{
$token = $this->getAccessToken();
$user = $this->getCurrentUser();
if (!$user->isAllowed()) {
throw new ForbiddenRequestException(
"Forbidden Request - User account was disabled",
IResponse::S403_Forbidden,
FrontendErrorMappings::E403_002__USER_NOT_ALLOWED
);
}
$user->updateLastAuthenticationAt();
$this->users->flush();
$event = SecurityEvent::createRefreshTokenEvent($this->getHttpRequest()->getRemoteAddress(), $user);
$this->securityEvents->persist($event);
$this->sendSuccessResponse(
[
"accessToken" => $this->accessManager->issueRefreshedToken($token),
"user" => $this->userViewFactory->getFullUser($user)
]
);
}
public function checkIssueRestrictedToken()
{
if (!$this->getAccessToken()->isInScope(TokenScope::MASTER)) {
throw new ForbiddenRequestException("Restricted tokens cannot be used to issue new tokens");
}
}
/**
* Issue a new access token with a restricted set of scopes
* @POST
* @LoggedIn
* @throws BadRequestException
* @throws ForbiddenRequestException
* @throws InvalidApiArgumentException
*/
#[Post("effectiveRole", new VString(), "Effective user role contained within issued token", required: false)]
#[Post("scopes", new VArray(), "A list of requested scopes")]
#[Post("expiration", new VInt(), "How long should the token be valid (in seconds)", required: false)]
public function actionIssueRestrictedToken()
{
$request = $this->getRequest();
// The scopes are not filtered in any way - ACL won't allow anything that the user cannot do in a full session
$scopes = $request->getPost("scopes");
$effectiveRole = $request->getPost("effectiveRole");
$expiration = $request->getPost("expiration") !== null ? intval($request->getPost("expiration")) : null;
$this->validateScopeRoles($scopes, $expiration);
$this->validateEffectiveRole($effectiveRole);
$user = $this->getCurrentUser();
if (!$user->isAllowed()) {
throw new ForbiddenRequestException(
"Forbidden Request - User account was disabled",
IResponse::S403_Forbidden,
FrontendErrorMappings::E403_002__USER_NOT_ALLOWED
);
}
$user->updateLastAuthenticationAt();
$this->users->flush();
$event = SecurityEvent::createIssueTokenEvent($this->getHttpRequest()->getRemoteAddress(), $user);
$this->securityEvents->persist($event);
$this->sendSuccessResponse(
[
"accessToken" => $this->accessManager->issueToken($user, $effectiveRole, $scopes, $expiration),
"user" => $this->userViewFactory->getFullUser($user),
]
);
}
private function validateScopeRoles(?array $scopes, $expiration)
{
$forbiddenScopes = [
TokenScope::CHANGE_PASSWORD =>
"Password change tokens can only be issued through the password reset endpoint",
TokenScope::EMAIL_VERIFICATION => "E-mail verification tokens must be received via e-mail",
];
// check if any of given scopes is among the forbidden ones
$violations = array_intersect(array_keys($forbiddenScopes), $scopes);
if ($violations) {
throw new ForbiddenRequestException($forbiddenScopes[$violations[0]]);
}
$restrictedScopes = [
TokenScope::MASTER => $this->accessManager->getExpiration()
];
foreach (array_intersect(array_keys($restrictedScopes), $scopes) as $match) {
if ($expiration !== null && $restrictedScopes[$match] < $expiration) {
throw new ForbiddenRequestException(
sprintf(
"Cannot issue token with scope '%s' and expiration period longer than '%d' seconds",
$match,
$restrictedScopes[$match]
)
);
}
}
}
private function validateEffectiveRole(?string $effectiveRole)
{
if ($effectiveRole == null) {
return;
}
if (!$this->roles->validateRole($effectiveRole)) {
throw new InvalidApiArgumentException('effectiveRole', "Unknown user role '$effectiveRole'");
}
$role = $this->getCurrentUser()->getRole();
if (!$this->roles->isInRole($role, $effectiveRole)) {
throw new BadRequestException(
"Cannot issue token with effective role '$effectiveRole' higher than the actual one '$role'",
FrontendErrorMappings::E400_002__BAD_REQUEST_FORBIDDEN_EFFECTIVE_ROLE,
["effectiveRole" => $effectiveRole, "role" => $role]
);
}
}
}