-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathAccessTokenAuthenticator.php
86 lines (73 loc) · 2.59 KB
/
AccessTokenAuthenticator.php
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
<?php
namespace Crm\UsersModule\Authenticator;
use Crm\ApplicationModule\Authenticator\AuthenticatorInterface;
use Crm\ApplicationModule\Authenticator\BaseAuthenticator;
use Crm\UsersModule\Repository\AccessTokensRepository;
use Crm\UsersModule\Repository\LoginAttemptsRepository;
use Crm\UsersModule\Repository\UsersRepository;
use League\Event\Emitter;
use Nette\Database\Table\IRow;
use Nette\Http\Request;
use Nette\Localization\ITranslator;
use Nette\Security\AuthenticationException;
use Nette\Security\IAuthenticator;
/**
* AccessTokenAuthenticator authenticates user based on accessToken.
*
* Required credentials (use setCredentials()):
*
* - 'accessToken'
*/
class AccessTokenAuthenticator extends BaseAuthenticator
{
private $accessTokensRepository;
private $translator;
/** @var string */
private $accessToken = null;
public function __construct(
Emitter $emitter,
\Tomaj\Hermes\Emitter $hermesEmitter,
Request $request,
AccessTokensRepository $accessTokensRepository,
ITranslator $translator
) {
parent::__construct($emitter, $hermesEmitter, $request);
$this->translator = $translator;
$this->accessTokensRepository = $accessTokensRepository;
}
public function authenticate()
{
if ($this->accessToken !== null) {
return $this->process();
}
return false;
}
public function setCredentials(array $credentials) : AuthenticatorInterface
{
$this->accessToken = $credentials['accessToken'] ?? null;
return $this;
}
public function shouldRegenerateToken(): bool
{
return false;
}
/**
* @throws AuthenticationException
*/
private function process() : IRow
{
$tokenRow = $this->accessTokensRepository->loadToken($this->accessToken);
if (!$tokenRow) {
throw new AuthenticationException($this->translator->translate('users.authenticator.access_token.invalid_token'), IAuthenticator::FAILURE);
}
$user = $tokenRow->user;
if (!$user) {
throw new AuthenticationException($this->translator->translate('users.authenticator.access_token.invalid_token'), IAuthenticator::IDENTITY_NOT_FOUND);
}
if ($user->role === UsersRepository::ROLE_ADMIN) {
throw new AuthenticationException($this->translator->translate('users.authenticator.access_token.autologin_disabled'), IAuthenticator::FAILURE);
}
$this->addAttempt($user->email, $user, $this->source, LoginAttemptsRepository::STATUS_ACCESS_TOKEN_OK);
return $user;
}
}