Spaces:
No application file
No application file
File size: 2,239 Bytes
d2897cd |
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 |
<?php
namespace Mautic\UserBundle\Security\SAML\User;
use LightSaml\Model\Assertion\Assertion;
use LightSaml\Model\Protocol\Response;
use LightSaml\SpBundle\Security\User\UsernameMapperInterface;
use Mautic\UserBundle\Entity\User;
class UserMapper implements UsernameMapperInterface
{
/**
* @param array<string, mixed> $attributes
*/
public function __construct(
private array $attributes
) {
}
public function getUser(Response $response): User
{
$user = new User();
foreach ($response->getAllAssertions() as $assertion) {
$this->setValuesFromAssertion($assertion, $user);
}
return $user;
}
public function getUsername(Response $response): ?string
{
$user = $this->getUser($response);
return $user->getUserIdentifier();
}
private function setValuesFromAssertion(Assertion $assertion, User $user): void
{
$attributes = $this->extractAttributes($assertion);
// use email as the user by default
if (isset($attributes['email'])) {
$user->setEmail($attributes['email']);
$user->setUsername($attributes['email']);
}
if (isset($attributes['username']) && !empty($attributes['username'])) {
$user->setUsername($attributes['username']);
}
if (isset($attributes['firstname'])) {
$user->setFirstname($attributes['firstname']);
}
if (isset($attributes['lastname'])) {
$user->setLastName($attributes['lastname']);
}
}
private function extractAttributes(Assertion $assertion): array
{
$attributes = [];
foreach ($this->attributes as $key => $attributeName) {
if (!$attributeName) {
continue;
}
foreach ($assertion->getAllAttributeStatements() as $attributeStatement) {
$attribute = $attributeStatement->getFirstAttributeByName($attributeName);
if ($attribute && $attribute->getFirstAttributeValue()) {
$attributes[$key] = $attribute->getFirstAttributeValue();
}
}
}
return $attributes;
}
}
|