1<?php
2/**
3 * This file is part of the FreeDSx LDAP package.
4 *
5 * (c) Chad Sikorra <Chad.Sikorra@gmail.com>
6 *
7 * For the full copyright and license information, please view the LICENSE
8 * file that was distributed with this source code.
9 */
10
11namespace FreeDSx\Ldap\Protocol\ServerProtocolHandler;
12
13use FreeDSx\Ldap\Entry\Dn;
14use FreeDSx\Ldap\Operation\LdapResult;
15use FreeDSx\Ldap\Operation\Response\ExtendedResponse;
16use FreeDSx\Ldap\Operation\ResultCode;
17use FreeDSx\Ldap\Protocol\LdapMessageRequest;
18use FreeDSx\Ldap\Protocol\LdapMessageResponse;
19use FreeDSx\Ldap\Protocol\Queue\ServerQueue;
20use FreeDSx\Ldap\Server\RequestHandler\RequestHandlerInterface;
21use FreeDSx\Ldap\Server\Token\TokenInterface;
22
23/**
24 * Handles a whoami request.
25 *
26 * @author Chad Sikorra <Chad.Sikorra@gmail.com>
27 */
28class ServerWhoAmIHandler implements ServerProtocolHandlerInterface
29{
30    /**
31     * {@inheritDoc}
32     */
33    public function handleRequest(LdapMessageRequest $message, TokenInterface $token, RequestHandlerInterface $dispatcher, ServerQueue $queue, array $options): void
34    {
35        $userId = $token->getUsername();
36
37        if ($userId !== null) {
38            try {
39                (new Dn($userId))->toArray();
40                $userId = 'dn:' . $userId;
41            } catch (\Exception $e) {
42                $userId = 'u:' . $userId;
43            }
44        }
45
46        $queue->sendMessage(new LdapMessageResponse(
47            $message->getMessageId(),
48            new ExtendedResponse(new LdapResult(ResultCode::SUCCESS), null, $userId)
49        ));
50    }
51}
52