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