-
Notifications
You must be signed in to change notification settings - Fork 0
/
oauth2_jwt_sso.module
54 lines (51 loc) · 1.93 KB
/
oauth2_jwt_sso.module
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
<?php
use Drupal\Core\Form\FormStateInterface;
use Drupal\oauth2_jwt_sso\Authentication\Provider\OAuth2JwtSSOProvider;
use Drupal\user\Entity\User;
use Lcobucci\JWT\Parser;
use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
/**
* Implements hook_form_alter().
*/
function oauth2_jwt_sso_form_alter(&$form, FormStateInterface $form_state, $form_id) {
if ($form_id == 'user_login_form') {
$form['#validate'] = [
'::validateName',
'sso_user_login_form_validateRole',
'::validateFinal',
];
}
}
function sso_user_login_form_validateRole(array &$form, FormStateInterface $form_state) {
$inputUser = $form_state->getValue('name');
$inputPwd = trim($form_state->getValue('pass'));
$config = \Drupal::configFactory();
$remote_login_roles = $config->get('oauth2_jwt_sso.settings')
->get('roles_remote_login');
if (user_load_by_name($inputUser) && empty(array_intersect(user_load_by_name($inputUser)->getRoles(), $remote_login_roles))) {
$form_state->getFormObject()->validateAuthentication($form, $form_state);
}
else {
$provider = new OAuth2JwtSSOProvider($config, \Drupal::request()->getSession());
try {
$accessToken = $provider->getAccessToken('password', [
'username' => $inputUser,
'password' => $inputPwd,
'scope' => implode(' ', $remote_login_roles),
]);
$token = (new Parser())->parse($accessToken->getToken());
if ($provider->verifyToken($token) && $user = $provider->tokenAuthUser($token)) {
$form_state->set('uid', $user->id());
$form_state->set('flood_control_user_identifier', $user->id());
$session = \Drupal::request()->getSession();
$session->set('sso-token', $accessToken->getToken());
}
else {
$form_state->setErrorByName('pass', 'Invalidate jwt Token.');
}
}
catch (IdentityProviderException $e) {
$form_state->setErrorByName('pass', $e->getMessage());
}
}
}