]> BookStack Code Mirror - bookstack/blob - app/Access/Oidc/OidcUserDetails.php
respective book and chapter structure added.
[bookstack] / app / Access / Oidc / OidcUserDetails.php
1 <?php
2
3 namespace BookStack\Access\Oidc;
4
5 use Illuminate\Support\Arr;
6
7 class OidcUserDetails
8 {
9     public function __construct(
10         public ?string $externalId = null,
11         public ?string $email = null,
12         public ?string $name = null,
13         public ?array $groups = null,
14     ) {
15     }
16
17     /**
18      * Check if the user details are fully populated for our usage.
19      */
20     public function isFullyPopulated(bool $groupSyncActive): bool
21     {
22         $hasEmpty = empty($this->externalId)
23             || empty($this->email)
24             || empty($this->name)
25             || ($groupSyncActive && $this->groups === null);
26
27         return !$hasEmpty;
28     }
29
30     /**
31      * Populate user details from the given claim data.
32      */
33     public function populate(
34         ProvidesClaims $claims,
35         string $idClaim,
36         string $displayNameClaims,
37         string $groupsClaim,
38     ): void {
39         $this->externalId = $claims->getClaim($idClaim) ?? $this->externalId;
40         $this->email = $claims->getClaim('email') ?? $this->email;
41         $this->name = static::getUserDisplayName($displayNameClaims, $claims) ?? $this->name;
42         $this->groups = static::getUserGroups($groupsClaim, $claims) ?? $this->groups;
43     }
44
45     protected static function getUserDisplayName(string $displayNameClaims, ProvidesClaims $token): string
46     {
47         $displayNameClaimParts = explode('|', $displayNameClaims);
48
49         $displayName = [];
50         foreach ($displayNameClaimParts as $claim) {
51             $component = $token->getClaim(trim($claim)) ?? '';
52             if ($component !== '') {
53                 $displayName[] = $component;
54             }
55         }
56
57         return implode(' ', $displayName);
58     }
59
60     protected static function getUserGroups(string $groupsClaim, ProvidesClaims $token): ?array
61     {
62         if (empty($groupsClaim)) {
63             return null;
64         }
65
66         $groupsList = Arr::get($token->getAllClaims(), $groupsClaim);
67         if (!is_array($groupsList)) {
68             return null;
69         }
70
71         return array_values(array_filter($groupsList, function ($val) {
72             return is_string($val);
73         }));
74     }
75 }