Passed
Pull Request — 1.11.x (#5763)
by Angel Fernando Quiroz
21:22 queued 12:43
created

AzureSyncUsersCommand::getAzureUsers()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 40
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 27
c 1
b 0
f 0
dl 0
loc 40
rs 9.1768
cc 5
nc 5
nop 1
1
<?php
2
3
/* For license terms, see /license.txt */
4
5
use League\OAuth2\Client\Token\AccessTokenInterface;
6
7
class AzureSyncUsersCommand extends AzureCommand
8
{
9
    /**
10
     * @throws Exception
11
     *
12
     * @return Generator<int, string>
13
     */
14
    public function __invoke(): Generator
15
    {
16
        yield 'Synchronizing users from Azure.';
17
18
        $token = $this->provider->getAccessToken(
19
            'client_credentials',
20
            ['resource' => $this->provider->resource]
21
        );
22
23
        $existingUsers = [];
24
25
        foreach ($this->getAzureUsers($token) as $azureUserInfo) {
26
            try {
27
                $userId = $this->plugin->registerUser(
28
                    $token,
29
                    $this->provider,
30
                    $azureUserInfo,
31
                    'users/'.$azureUserInfo['id'].'/memberOf',
32
                    'id',
33
                    'id'
34
                );
35
            } catch (Exception $e) {
36
                yield $e->getMessage();
37
38
                continue;
39
            }
40
41
            $existingUsers[] = $userId;
42
43
            $userInfo = api_get_user_info($userId);
44
45
            yield sprintf('User info: %s', serialize($userInfo));
46
        }
47
48
        if ('true' === $this->plugin->get(AzureActiveDirectory::SETTING_DEACTIVATE_NONEXISTING_USERS)) {
49
            yield '----------------';
50
51
            yield 'Trying deactivate non-existing users in Azure';
52
53
            $users = UserManager::getRepository()->findByAuthSource('azure');
54
            $userIdList = array_map(
55
                function ($user) {
56
                    return $user->getId();
57
                },
58
                $users
59
            );
60
61
            $nonExistingUsers = array_diff($userIdList, $existingUsers);
62
63
            UserManager::deactivate_users($nonExistingUsers);
64
65
            yield sprintf(
66
                'Deactivated users IDs: %s',
67
                implode(', ', $nonExistingUsers)
68
            );
69
        }
70
    }
71
72
    /**
73
     * @throws Exception
74
     *
75
     * @return Generator<int, array<string, string>>
76
     */
77
    private function getAzureUsers(AccessTokenInterface $token): Generator
78
    {
79
        $userFields = [
80
            'givenName',
81
            'surname',
82
            'mail',
83
            'userPrincipalName',
84
            'businessPhones',
85
            'mobilePhone',
86
            'accountEnabled',
87
            'mailNickname',
88
            'id',
89
        ];
90
91
        $query = sprintf(
92
            '$top=%d&$select=%s',
93
            AzureActiveDirectory::API_PAGE_SIZE,
94
            implode(',', $userFields)
95
        );
96
97
        do {
98
            try {
99
                $azureUsersRequest = $this->provider->request('get', "users?$query", $token);
100
            } catch (Exception $e) {
101
                throw new Exception('Exception when requesting users from Azure: '.$e->getMessage());
102
            }
103
104
            $azureUsersInfo = $azureUsersRequest['value'] ?? [];
105
106
            foreach ($azureUsersInfo as $azureUserInfo) {
107
                yield $azureUserInfo;
108
            }
109
110
            $hasNextLink = false;
111
112
            if (!empty($azureUsersRequest['@odata.nextLink'])) {
113
                $hasNextLink = true;
114
                $query = parse_url($azureUsersRequest['@odata.nextLink'], PHP_URL_QUERY);
115
            }
116
        } while ($hasNextLink);
117
    }
118
}
119