Ldap.php 9.4 KB
Newer Older
Bertrand Gauthier's avatar
Bertrand Gauthier committed
1
<?php
2

Bertrand Gauthier's avatar
Bertrand Gauthier committed
3
4
namespace UnicaenAuth\Authentication\Adapter;

5
6
use UnicaenApp\Exception\RuntimeException;
use UnicaenApp\Mapper\Ldap\People as LdapPeopleMapper;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
7
use UnicaenAuth\Options\ModuleOptions;
8
use UnicaenAuth\Service\User;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
9
use Zend\Authentication\Adapter\Ldap as LdapAuthAdapter;
10
11
use Zend\Authentication\Exception\ExceptionInterface;
use Zend\Authentication\Result as AuthenticationResult;
Laurent Lécluse's avatar
Laurent Lécluse committed
12
use Zend\EventManager\Event;
13
use Zend\EventManager\EventInterface;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
14
15
16
17
18
use Zend\EventManager\EventManager;
use Zend\EventManager\EventManagerAwareInterface;
use Zend\EventManager\EventManagerInterface;
use ZfcUser\Authentication\Adapter\AbstractAdapter;
use ZfcUser\Authentication\Adapter\ChainableAdapter;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
19
20
21
22
23
24

/**
 * LDAP authentication adpater
 *
 * @author Bertrand GAUTHIER <bertrand.gauthier@unicaen.fr>
 */
25
class Ldap extends AbstractAdapter implements EventManagerAwareInterface
Bertrand Gauthier's avatar
Bertrand Gauthier committed
26
{
27
    const USURPATION_USERNAMES_SEP = '=';
Bertrand Gauthier's avatar
Bertrand Gauthier committed
28
29

    /**
Bertrand Gauthier's avatar
Bertrand Gauthier committed
30
     * @var EventManager
Bertrand Gauthier's avatar
Bertrand Gauthier committed
31
32
     */
    protected $eventManager;
33

Bertrand Gauthier's avatar
Bertrand Gauthier committed
34
    /**
Bertrand Gauthier's avatar
Bertrand Gauthier committed
35
     * @var LdapAuthAdapter
Bertrand Gauthier's avatar
Bertrand Gauthier committed
36
     */
Bertrand Gauthier's avatar
Bertrand Gauthier committed
37
    protected $ldapAuthAdapter;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
38

39
40
41
42
43
    /**
     * @var LdapPeopleMapper
     */
    protected $ldapPeopleMapper;

Bertrand Gauthier's avatar
Bertrand Gauthier committed
44
    /**
Bertrand Gauthier's avatar
Bertrand Gauthier committed
45
     * @var ModuleOptions
Bertrand Gauthier's avatar
Bertrand Gauthier committed
46
     */
Bertrand Gauthier's avatar
Bertrand Gauthier committed
47
    protected $options;
48

49
    /**
50
     * @var string
51
52
     */
    protected $usernameUsurpe;
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
    /**
     * @var User
     */
    private $userService;

    /**
     * @param User $userService
     */
    public function setUserService(User $userService)
    {
        $this->userService = $userService;
    }

    /**
     * @var \UnicaenApp\Options\ModuleOptions
     */
    private $appModuleOptions;

    /**
     * @param \UnicaenApp\Options\ModuleOptions $appModuleOptions
     */
    public function setAppModuleOptions(\UnicaenApp\Options\ModuleOptions $appModuleOptions)
    {
        $this->appModuleOptions = $appModuleOptions;
    }

Bertrand Gauthier's avatar
Bertrand Gauthier committed
80
    /**
81
     *
82
     * @param EventInterface $e
Bertrand Gauthier's avatar
Bertrand Gauthier committed
83
     * @return boolean
84
85
     * @throws \Zend\Authentication\Adapter\Exception\ExceptionInterface
     * @throws \Zend\Ldap\Exception\LdapException
Bertrand Gauthier's avatar
Bertrand Gauthier committed
86
87
     * @see ChainableAdapter
     */
88
    public function authenticate(EventInterface $e)
Bertrand Gauthier's avatar
Bertrand Gauthier committed
89
    {
90
91
92
93
94
        // NB: Dans la version 3.0.0 de zf-commons/zfc-user, cette méthode prend un EventInterface.
        // Mais dans la branche 3.x, c'est un AdapterChainEvent !
        // Si un jour c'est un AdapterChainEvent qui est attendu, plus besoin de faire $e->getTarget().
        $e = $e->getTarget();

Bertrand Gauthier's avatar
Bertrand Gauthier committed
95
        if ($this->isSatisfied()) {
96
97
98
99
100
            try {
                $storage = $this->getStorage()->read();
            } catch (ExceptionInterface $e) {
                throw new RuntimeException("Erreur de lecture du storage");
            }
Bertrand Gauthier's avatar
Bertrand Gauthier committed
101
            $e->setIdentity($storage['identity'])
102
103
                ->setCode(AuthenticationResult::SUCCESS)
                ->setMessages(['Authentication successful.']);
Bertrand Gauthier's avatar
Bertrand Gauthier committed
104
105
106
            return;
        }

Bertrand Gauthier's avatar
Bertrand Gauthier committed
107
        $username   = $e->getRequest()->getPost()->get('identity');
Bertrand Gauthier's avatar
Bertrand Gauthier committed
108
109
        $credential = $e->getRequest()->getPost()->get('credential');

110
111
112
113
114
115
        if (function_exists('mb_strtolower')) {
            $username = mb_strtolower($username, 'UTF-8');
        } else {
            $username = strtolower($username);
        }

116
        $success = $this->authenticateUsername($username, $credential);
117

Bertrand Gauthier's avatar
Bertrand Gauthier committed
118
        // Failure!
119
        if (! $success) {
Bertrand Gauthier's avatar
Bertrand Gauthier committed
120
            $e->setCode(AuthenticationResult::FAILURE)
121
122
123
124
125
126
                ->setMessages(['LDAP bind failed.']);
            $this->setSatisfied(false);
            return false;
        }

        // recherche de l'individu dans l'annuaire LDAP
127
        $ldapPeople = $this->getLdapPeopleMapper()->findOneByUsername($this->usernameUsurpe ?: $username);
128
129
130
131
        if (!$ldapPeople) {
            $e
                ->setCode(AuthenticationResult::FAILURE)
                ->setMessages(['Authentication failed.']);
Bertrand Gauthier's avatar
Bertrand Gauthier committed
132
133
134
            $this->setSatisfied(false);
            return false;
        }
135

136
        $e->setIdentity($this->usernameUsurpe ?: $username);
Bertrand Gauthier's avatar
Bertrand Gauthier committed
137
        $this->setSatisfied(true);
138
139
140
141
142
143
144
        try {
            $storage = $this->getStorage()->read();
            $storage['identity'] = $e->getIdentity();
            $this->getStorage()->write($storage);
        } catch (ExceptionInterface $e) {
            throw new RuntimeException("Erreur de concernant le storage");
        }
Bertrand Gauthier's avatar
Bertrand Gauthier committed
145
        $e->setCode(AuthenticationResult::SUCCESS)
146
            ->setMessages(['Authentication successful.']);
147

148
        /* @var $userService User */
149
        $this->userService->userAuthenticated($ldapPeople);
Bertrand Gauthier's avatar
Bertrand Gauthier committed
150
151
    }

152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
    /**
     * Extrait le loginUsurpateur et le loginUsurpé si l'identifiant spécifé est de la forme
     * "loginUsurpateur=loginUsurpé".
     *
     * @param string $identifiant Identifiant, éventuellement de la forme "loginUsurpateur=loginUsurpé"
     * @return array
     * [loginUsurpateur, loginUsurpé] si l'identifiant est de la forme "loginUsurpateur=loginUsurpé" ;
     * [] sinon.
     */
    static public function extractUsernamesUsurpation($identifiant)
    {
        if (strpos($identifiant, self::USURPATION_USERNAMES_SEP) > 0) {
            list($identifiant, $usernameUsurpe) = explode(self::USURPATION_USERNAMES_SEP, $identifiant, 2);

            return [
                $identifiant,
                $usernameUsurpe
            ];
        }
171

172
        return [];
Bertrand Gauthier's avatar
Bertrand Gauthier committed
173
174
    }

175
176
    /**
     * Authentifie l'identifiant et le mot de passe spécifiés.
177
     *
178
     * @param string $username   Identifiant de connexion
179
180
     * @param string $credential Mot de passe
     * @return boolean
181
182
     * @throws \Zend\Authentication\Adapter\Exception\ExceptionInterface
     * @throws \Zend\Ldap\Exception\LdapException
183
184
185
186
187
188
189
     */
    public function authenticateUsername($username, $credential)
    {
        // si 2 logins sont fournis, cela active l'usurpation d'identité (à n'utiliser que pour les tests) :
        // - le format attendu est "loginUsurpateur=loginUsurpé"
        // - le mot de passe attendu est celui du compte usurpateur (loginUsurpateur)
        $this->usernameUsurpe = null;
190
191
192
        $usernames = self::extractUsernamesUsurpation($username);
        if (count($usernames) === 2) {
            list ($username, $this->usernameUsurpe) = $usernames;
193
194
195
196
197
198
199
            if (!in_array($username, $this->getOptions()->getUsurpationAllowedUsernames())) {
                $this->usernameUsurpe = null;
            }
        }

        // LDAP auth
        $result  = $this->getLdapAuthAdapter()->setUsername($username)->setPassword($credential)->authenticate();
200
201
202
203
204

        if ($result && count($result->getMessages())) {
            // Obtenir le message LDAP
            // $msg = preg_replace('/\[0x\d* \((.*)\):/','$1', $event->getParam('result')->getMessages()[1]);
            $eventClasse = new Event('authentication.ldap.error');
205
206
            $eventClasse->setTarget($this);
            $eventClasse->setParams([
207
208
                'result' => $result
            ]);
209
            $this->getEventManager()->triggerEvent($eventClasse);
210
211
        }

212
        $success = $result->isValid();
213

214
215
        // verif existence du login usurpé
        if ($this->usernameUsurpe) {
216
            // s'il nexiste pas, échec de l'authentification
217
218
            if (!$this->getLdapAuthAdapter()->getLdap()->searchEntries("(supannAliasLogin=$this->usernameUsurpe)")) {
                $this->usernameUsurpe = null;
219
                $success              = false;
220
221
            }
        }
222

223
224
        return $success;
    }
225

226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
    /**
     * get ldap people mapper
     *
     * @return LdapPeopleMapper
     */
    public function getLdapPeopleMapper()
    {
        return $this->ldapPeopleMapper;
    }

    /**
     * set ldap people mapper
     *
     * @param LdapPeopleMapper $mapper
     * @return self
     */
    public function setLdapPeopleMapper(LdapPeopleMapper $mapper)
    {
        $this->ldapPeopleMapper = $mapper;
        return $this;
    }

Bertrand Gauthier's avatar
Bertrand Gauthier committed
248
    /**
Bertrand Gauthier's avatar
Bertrand Gauthier committed
249
     * @param ModuleOptions $options
Bertrand Gauthier's avatar
Bertrand Gauthier committed
250
     */
Bertrand Gauthier's avatar
Bertrand Gauthier committed
251
    public function setOptions(ModuleOptions $options)
Bertrand Gauthier's avatar
Bertrand Gauthier committed
252
    {
Bertrand Gauthier's avatar
Bertrand Gauthier committed
253
        $this->options = $options;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
254
255
256
    }

    /**
Bertrand Gauthier's avatar
Bertrand Gauthier committed
257
     * @return ModuleOptions
Bertrand Gauthier's avatar
Bertrand Gauthier committed
258
     */
Bertrand Gauthier's avatar
Bertrand Gauthier committed
259
    public function getOptions()
Bertrand Gauthier's avatar
Bertrand Gauthier committed
260
    {
Bertrand Gauthier's avatar
Bertrand Gauthier committed
261
        return $this->options;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
262
    }
Bertrand Gauthier's avatar
Bertrand Gauthier committed
263

Bertrand Gauthier's avatar
Bertrand Gauthier committed
264
    /**
Bertrand Gauthier's avatar
Bertrand Gauthier committed
265
     * @return \UnicaenApp\Options\ModuleOptions
Bertrand Gauthier's avatar
Bertrand Gauthier committed
266
     */
Bertrand Gauthier's avatar
Bertrand Gauthier committed
267
    public function getAppModuleOptions()
Bertrand Gauthier's avatar
Bertrand Gauthier committed
268
    {
269
        return $this->appModuleOptions;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
270
271
272
273
    }

    /**
     * get ldap connection adapter
274
     *
Bertrand Gauthier's avatar
Bertrand Gauthier committed
275
     * @return LdapAuthAdapter
Bertrand Gauthier's avatar
Bertrand Gauthier committed
276
     */
Bertrand Gauthier's avatar
Bertrand Gauthier committed
277
    public function getLdapAuthAdapter()
Bertrand Gauthier's avatar
Bertrand Gauthier committed
278
    {
Bertrand Gauthier's avatar
Bertrand Gauthier committed
279
        if (null === $this->ldapAuthAdapter) {
280
            $options = [];
Bertrand Gauthier's avatar
Bertrand Gauthier committed
281
282
283
284
285
286
            if (($config = $this->getAppModuleOptions()->getLdap())) {
                foreach ($config['connection'] as $name => $connection) {
                    $options[$name] = $connection['params'];
                }
            }
            $this->ldapAuthAdapter = new LdapAuthAdapter($options); // NB: array(array)
Bertrand Gauthier's avatar
Bertrand Gauthier committed
287
        }
Bertrand Gauthier's avatar
Bertrand Gauthier committed
288
        return $this->ldapAuthAdapter;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
289
290
291
292
    }

    /**
     * set ldap connection adapter
293
     *
Bertrand Gauthier's avatar
Bertrand Gauthier committed
294
     * @param LdapAuthAdapter $authAdapter
Bertrand Gauthier's avatar
Bertrand Gauthier committed
295
296
     * @return Ldap
     */
Bertrand Gauthier's avatar
Bertrand Gauthier committed
297
    public function setLdapAuthAdapter(LdapAuthAdapter $authAdapter)
Bertrand Gauthier's avatar
Bertrand Gauthier committed
298
    {
Bertrand Gauthier's avatar
Bertrand Gauthier committed
299
        $this->ldapAuthAdapter = $authAdapter;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
300
301
302
303
        return $this;
    }

    /**
Bertrand Gauthier's avatar
Bertrand Gauthier committed
304
305
306
     * Retrieve EventManager instance
     *
     * @return EventManagerInterface
Bertrand Gauthier's avatar
Bertrand Gauthier committed
307
     */
Bertrand Gauthier's avatar
Bertrand Gauthier committed
308
    public function getEventManager()
Bertrand Gauthier's avatar
Bertrand Gauthier committed
309
    {
Bertrand Gauthier's avatar
Bertrand Gauthier committed
310
        return $this->eventManager;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
311
    }
312

Bertrand Gauthier's avatar
Bertrand Gauthier committed
313
    /**
314
     * {@inheritdoc}
Bertrand Gauthier's avatar
Bertrand Gauthier committed
315
     */
Bertrand Gauthier's avatar
Bertrand Gauthier committed
316
    public function setEventManager(EventManagerInterface $eventManager)
Bertrand Gauthier's avatar
Bertrand Gauthier committed
317
    {
318
319
320
321
        $eventManager->setIdentifiers([
            __NAMESPACE__,
            __CLASS__,
        ]);
Bertrand Gauthier's avatar
Bertrand Gauthier committed
322
323
        $this->eventManager = $eventManager;
        return $this;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
324
325
    }
}