Ldap.php 9.46 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;
19
use Zend\Authentication\Storage\Session;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
20
21
22
23
24
25

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

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

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

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

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

50
    /**
51
     * @var string
52
53
     */
    protected $usernameUsurpe;
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
    /**
     * @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
81
    /**
82
     *
83
     * @param EventInterface $e
Bertrand Gauthier's avatar
Bertrand Gauthier committed
84
     * @return boolean
85
86
     * @throws \Zend\Authentication\Adapter\Exception\ExceptionInterface
     * @throws \Zend\Ldap\Exception\LdapException
Bertrand Gauthier's avatar
Bertrand Gauthier committed
87
88
     * @see ChainableAdapter
     */
89
    public function authenticate(EventInterface $e)
Bertrand Gauthier's avatar
Bertrand Gauthier committed
90
    {
91
92
93
94
95
        // 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
96
        if ($this->isSatisfied()) {
97
98
99
100
101
            try {
                $storage = $this->getStorage()->read();
            } catch (ExceptionInterface $e) {
                throw new RuntimeException("Erreur de lecture du storage");
            }
Bertrand Gauthier's avatar
Bertrand Gauthier committed
102
            $e->setIdentity($storage['identity'])
103
104
                ->setCode(AuthenticationResult::SUCCESS)
                ->setMessages(['Authentication successful.']);
Bertrand Gauthier's avatar
Bertrand Gauthier committed
105
106
107
            return;
        }

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

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

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

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

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

137
        $e->setIdentity($this->usernameUsurpe ?: $username);
Bertrand Gauthier's avatar
Bertrand Gauthier committed
138
        $this->setSatisfied(true);
139
140
141
142
143
144
145
        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
146
        $e->setCode(AuthenticationResult::SUCCESS)
147
            ->setMessages(['Authentication successful.']);
148

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

153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
    /**
     * 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
            ];
        }
172

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

176
177
    /**
     * Authentifie l'identifiant et le mot de passe spécifiés.
178
     *
179
     * @param string $username   Identifiant de connexion
180
181
     * @param string $credential Mot de passe
     * @return boolean
182
183
     * @throws \Zend\Authentication\Adapter\Exception\ExceptionInterface
     * @throws \Zend\Ldap\Exception\LdapException
184
185
186
187
188
189
190
     */
    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;
191
192
193
        $usernames = self::extractUsernamesUsurpation($username);
        if (count($usernames) === 2) {
            list ($username, $this->usernameUsurpe) = $usernames;
194
195
196
197
198
199
200
            if (!in_array($username, $this->getOptions()->getUsurpationAllowedUsernames())) {
                $this->usernameUsurpe = null;
            }
        }

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

        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');
206
207
            $eventClasse->setTarget($this);
            $eventClasse->setParams([
208
209
                'result' => $result
            ]);
210
            $this->getEventManager()->triggerEvent($eventClasse);
211
212
        }

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

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

224
225
        return $success;
    }
226

227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
    /**
     * 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
249
    /**
Bertrand Gauthier's avatar
Bertrand Gauthier committed
250
     * @param ModuleOptions $options
Bertrand Gauthier's avatar
Bertrand Gauthier committed
251
     */
Bertrand Gauthier's avatar
Bertrand Gauthier committed
252
    public function setOptions(ModuleOptions $options)
Bertrand Gauthier's avatar
Bertrand Gauthier committed
253
    {
Bertrand Gauthier's avatar
Bertrand Gauthier committed
254
        $this->options = $options;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
255
256
257
    }

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

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

    /**
     * get ldap connection adapter
275
     *
Bertrand Gauthier's avatar
Bertrand Gauthier committed
276
     * @return LdapAuthAdapter
Bertrand Gauthier's avatar
Bertrand Gauthier committed
277
     */
Bertrand Gauthier's avatar
Bertrand Gauthier committed
278
    public function getLdapAuthAdapter()
Bertrand Gauthier's avatar
Bertrand Gauthier committed
279
    {
Bertrand Gauthier's avatar
Bertrand Gauthier committed
280
        if (null === $this->ldapAuthAdapter) {
281
            $options = [];
Bertrand Gauthier's avatar
Bertrand Gauthier committed
282
283
284
285
286
287
            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
288
        }
Bertrand Gauthier's avatar
Bertrand Gauthier committed
289
        return $this->ldapAuthAdapter;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
290
291
292
293
    }

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

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

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