Ldap.php 9.81 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;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
12
13
14
use Zend\EventManager\EventManager;
use Zend\EventManager\EventManagerAwareInterface;
use Zend\EventManager\EventManagerInterface;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
15
16
use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\ServiceManagerAwareInterface;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
17
18
19
use ZfcUser\Authentication\Adapter\AbstractAdapter;
use ZfcUser\Authentication\Adapter\AdapterChainEvent as AuthEvent;
use ZfcUser\Authentication\Adapter\ChainableAdapter;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
20
21
22
23
24
25
26
27

/**
 * LDAP authentication adpater
 *
 * @author Bertrand GAUTHIER <bertrand.gauthier@unicaen.fr>
 */
class Ldap extends AbstractAdapter implements ServiceManagerAwareInterface, EventManagerAwareInterface
{
28
    const USURPATION_USERNAMES_SEP = '=';
29

Bertrand Gauthier's avatar
Bertrand Gauthier committed
30
31
32
33
34
35
    /**
     * @var ServiceManager
     */
    protected $serviceManager;

    /**
Bertrand Gauthier's avatar
Bertrand Gauthier committed
36
     * @var EventManager
Bertrand Gauthier's avatar
Bertrand Gauthier committed
37
38
     */
    protected $eventManager;
39

Bertrand Gauthier's avatar
Bertrand Gauthier committed
40
    /**
Bertrand Gauthier's avatar
Bertrand Gauthier committed
41
     * @var LdapAuthAdapter
Bertrand Gauthier's avatar
Bertrand Gauthier committed
42
     */
Bertrand Gauthier's avatar
Bertrand Gauthier committed
43
    protected $ldapAuthAdapter;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
44

45
46
47
48
49
    /**
     * @var LdapPeopleMapper
     */
    protected $ldapPeopleMapper;

Bertrand Gauthier's avatar
Bertrand Gauthier committed
50
    /**
Bertrand Gauthier's avatar
Bertrand Gauthier committed
51
     * @var ModuleOptions
Bertrand Gauthier's avatar
Bertrand Gauthier committed
52
     */
Bertrand Gauthier's avatar
Bertrand Gauthier committed
53
    protected $options;
54

55
    /**
56
     * @var string
57
58
     */
    protected $usernameUsurpe;
59

Bertrand Gauthier's avatar
Bertrand Gauthier committed
60
    /**
61
     *
Bertrand Gauthier's avatar
Bertrand Gauthier committed
62
63
     * @param AuthEvent $e
     * @return boolean
64
65
     * @throws \Zend\Authentication\Adapter\Exception\ExceptionInterface
     * @throws \Zend\Ldap\Exception\LdapException
Bertrand Gauthier's avatar
Bertrand Gauthier committed
66
67
68
69
70
     * @see ChainableAdapter
     */
    public function authenticate(AuthEvent $e)
    {
        if ($this->isSatisfied()) {
71
72
73
74
75
            try {
                $storage = $this->getStorage()->read();
            } catch (ExceptionInterface $e) {
                throw new RuntimeException("Erreur de lecture du storage");
            }
Bertrand Gauthier's avatar
Bertrand Gauthier committed
76
            $e->setIdentity($storage['identity'])
77
78
                ->setCode(AuthenticationResult::SUCCESS)
                ->setMessages(['Authentication successful.']);
Bertrand Gauthier's avatar
Bertrand Gauthier committed
79
80
81
            return;
        }

Bertrand Gauthier's avatar
Bertrand Gauthier committed
82
        $username   = $e->getRequest()->getPost()->get('identity');
Bertrand Gauthier's avatar
Bertrand Gauthier committed
83
84
        $credential = $e->getRequest()->getPost()->get('credential');

85
86
87
88
89
90
        if (function_exists('mb_strtolower')) {
            $username = mb_strtolower($username, 'UTF-8');
        } else {
            $username = strtolower($username);
        }

91
        $success = $this->authenticateUsername($username, $credential);
92

Bertrand Gauthier's avatar
Bertrand Gauthier committed
93
        // Failure!
94
        if (! $success) {
Bertrand Gauthier's avatar
Bertrand Gauthier committed
95
            $e->setCode(AuthenticationResult::FAILURE)
96
97
98
99
100
101
102
103
104
105
106
                ->setMessages(['LDAP bind failed.']);
            $this->setSatisfied(false);
            return false;
        }

        // recherche de l'individu dans l'annuaire LDAP
        $ldapPeople = $this->getLdapPeopleMapper()->findOneByUsername($username);
        if (!$ldapPeople) {
            $e
                ->setCode(AuthenticationResult::FAILURE)
                ->setMessages(['Authentication failed.']);
Bertrand Gauthier's avatar
Bertrand Gauthier committed
107
108
109
            $this->setSatisfied(false);
            return false;
        }
110

111
        $e->setIdentity($this->usernameUsurpe ?: $username);
Bertrand Gauthier's avatar
Bertrand Gauthier committed
112
        $this->setSatisfied(true);
113
114
115
116
117
118
119
        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
120
        $e->setCode(AuthenticationResult::SUCCESS)
121
            ->setMessages(['Authentication successful.']);
122

123
124
125
        /* @var $userService User */
        $userService = $this->getServiceManager()->get('unicaen-auth_user_service');
        $userService->userAuthenticated($ldapPeople);
Bertrand Gauthier's avatar
Bertrand Gauthier committed
126
127
    }

128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
    /**
     * 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
            ];
        }
147

148
        return [];
Bertrand Gauthier's avatar
Bertrand Gauthier committed
149
150
    }

151
152
    /**
     * Authentifie l'identifiant et le mot de passe spécifiés.
153
     *
154
     * @param string $username   Identifiant de connexion
155
156
     * @param string $credential Mot de passe
     * @return boolean
157
158
     * @throws \Zend\Authentication\Adapter\Exception\ExceptionInterface
     * @throws \Zend\Ldap\Exception\LdapException
159
160
161
162
163
164
165
     */
    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;
166
167
168
        $usernames = self::extractUsernamesUsurpation($username);
        if (count($usernames) === 2) {
            list ($username, $this->usernameUsurpe) = $usernames;
169
170
171
172
173
174
175
            if (!in_array($username, $this->getOptions()->getUsurpationAllowedUsernames())) {
                $this->usernameUsurpe = null;
            }
        }

        // LDAP auth
        $result  = $this->getLdapAuthAdapter()->setUsername($username)->setPassword($credential)->authenticate();
176
177
178
179
180
181
182
183
184
185
186

        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');
            $eventClasse->setTarget($this)->setParams([
                'result' => $result
            ]);
            $this->getEventManager()->trigger($eventClasse);
        }

187
        $success = $result->isValid();
188

189
190
        // verif existence du login usurpé
        if ($this->usernameUsurpe) {
191
            // s'il nexiste pas, échec de l'authentification
192
193
            if (!$this->getLdapAuthAdapter()->getLdap()->searchEntries("(supannAliasLogin=$this->usernameUsurpe)")) {
                $this->usernameUsurpe = null;
194
                $success              = false;
195
196
            }
        }
197

198
199
        return $success;
    }
200

201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
    /**
     * get ldap people mapper
     *
     * @return LdapPeopleMapper
     */
    public function getLdapPeopleMapper()
    {
        if (null === $this->ldapPeopleMapper) {
            $this->ldapPeopleMapper = $this->getServiceManager()->get('ldap_people_mapper');
        }
        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
226
    /**
Bertrand Gauthier's avatar
Bertrand Gauthier committed
227
     * @param ModuleOptions $options
Bertrand Gauthier's avatar
Bertrand Gauthier committed
228
     */
Bertrand Gauthier's avatar
Bertrand Gauthier committed
229
    public function setOptions(ModuleOptions $options)
Bertrand Gauthier's avatar
Bertrand Gauthier committed
230
    {
Bertrand Gauthier's avatar
Bertrand Gauthier committed
231
        $this->options = $options;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
232
233
234
    }

    /**
Bertrand Gauthier's avatar
Bertrand Gauthier committed
235
     * @return ModuleOptions
Bertrand Gauthier's avatar
Bertrand Gauthier committed
236
     */
Bertrand Gauthier's avatar
Bertrand Gauthier committed
237
    public function getOptions()
Bertrand Gauthier's avatar
Bertrand Gauthier committed
238
    {
Bertrand Gauthier's avatar
Bertrand Gauthier committed
239
240
        if (!$this->options instanceof ModuleOptions) {
            $options = array_merge(
241
242
                $this->getServiceManager()->get('zfcuser_module_options')->toArray(),
                $this->getServiceManager()->get('unicaen-auth_module_options')->toArray());
Bertrand Gauthier's avatar
Bertrand Gauthier committed
243
244
245
            $this->setOptions(new ModuleOptions($options));
        }
        return $this->options;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
246
    }
Bertrand Gauthier's avatar
Bertrand Gauthier committed
247

Bertrand Gauthier's avatar
Bertrand Gauthier committed
248
    /**
Bertrand Gauthier's avatar
Bertrand Gauthier committed
249
     * @return \UnicaenApp\Options\ModuleOptions
Bertrand Gauthier's avatar
Bertrand Gauthier committed
250
     */
Bertrand Gauthier's avatar
Bertrand Gauthier committed
251
    public function getAppModuleOptions()
Bertrand Gauthier's avatar
Bertrand Gauthier committed
252
    {
Bertrand Gauthier's avatar
Bertrand Gauthier committed
253
        return $this->getServiceManager()->get('unicaen-app_module_options');
Bertrand Gauthier's avatar
Bertrand Gauthier committed
254
255
256
257
    }

    /**
     * get ldap connection adapter
258
     *
Bertrand Gauthier's avatar
Bertrand Gauthier committed
259
     * @return LdapAuthAdapter
Bertrand Gauthier's avatar
Bertrand Gauthier committed
260
     */
Bertrand Gauthier's avatar
Bertrand Gauthier committed
261
    public function getLdapAuthAdapter()
Bertrand Gauthier's avatar
Bertrand Gauthier committed
262
    {
Bertrand Gauthier's avatar
Bertrand Gauthier committed
263
        if (null === $this->ldapAuthAdapter) {
264
            $options = [];
Bertrand Gauthier's avatar
Bertrand Gauthier committed
265
266
267
268
269
270
            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
271
        }
Bertrand Gauthier's avatar
Bertrand Gauthier committed
272
        return $this->ldapAuthAdapter;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
273
274
275
276
    }

    /**
     * set ldap connection adapter
277
     *
Bertrand Gauthier's avatar
Bertrand Gauthier committed
278
     * @param LdapAuthAdapter $authAdapter
Bertrand Gauthier's avatar
Bertrand Gauthier committed
279
280
     * @return Ldap
     */
Bertrand Gauthier's avatar
Bertrand Gauthier committed
281
    public function setLdapAuthAdapter(LdapAuthAdapter $authAdapter)
Bertrand Gauthier's avatar
Bertrand Gauthier committed
282
    {
Bertrand Gauthier's avatar
Bertrand Gauthier committed
283
        $this->ldapAuthAdapter = $authAdapter;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
284
285
286
287
        return $this;
    }

    /**
Bertrand Gauthier's avatar
Bertrand Gauthier committed
288
289
290
     * Get service manager
     *
     * @return ServiceManager
Bertrand Gauthier's avatar
Bertrand Gauthier committed
291
     */
Bertrand Gauthier's avatar
Bertrand Gauthier committed
292
    public function getServiceManager()
Bertrand Gauthier's avatar
Bertrand Gauthier committed
293
    {
Bertrand Gauthier's avatar
Bertrand Gauthier committed
294
        return $this->serviceManager;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
295
296
297
    }

    /**
Bertrand Gauthier's avatar
Bertrand Gauthier committed
298
299
300
301
     * Set service manager
     *
     * @param ServiceManager $serviceManager
     * @return Ldap
Bertrand Gauthier's avatar
Bertrand Gauthier committed
302
     */
Bertrand Gauthier's avatar
Bertrand Gauthier committed
303
    public function setServiceManager(ServiceManager $serviceManager)
Bertrand Gauthier's avatar
Bertrand Gauthier committed
304
    {
Bertrand Gauthier's avatar
Bertrand Gauthier committed
305
306
        $this->serviceManager = $serviceManager;
        return $this;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
307
    }
308

Bertrand Gauthier's avatar
Bertrand Gauthier committed
309
    /**
Bertrand Gauthier's avatar
Bertrand Gauthier committed
310
311
312
     * Retrieve EventManager instance
     *
     * @return EventManagerInterface
Bertrand Gauthier's avatar
Bertrand Gauthier committed
313
     */
Bertrand Gauthier's avatar
Bertrand Gauthier committed
314
    public function getEventManager()
Bertrand Gauthier's avatar
Bertrand Gauthier committed
315
    {
Bertrand Gauthier's avatar
Bertrand Gauthier committed
316
        return $this->eventManager;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
317
    }
318

Bertrand Gauthier's avatar
Bertrand Gauthier committed
319
    /**
Bertrand Gauthier's avatar
Bertrand Gauthier committed
320
321
322
323
     * Inject an EventManager instance
     *
     * @param  EventManagerInterface $eventManager
     * @return Ldap
Bertrand Gauthier's avatar
Bertrand Gauthier committed
324
     */
Bertrand Gauthier's avatar
Bertrand Gauthier committed
325
    public function setEventManager(EventManagerInterface $eventManager)
Bertrand Gauthier's avatar
Bertrand Gauthier committed
326
    {
327
328
329
330
        $eventManager->setIdentifiers([
            __NAMESPACE__,
            __CLASS__,
        ]);
Bertrand Gauthier's avatar
Bertrand Gauthier committed
331
332
        $this->eventManager = $eventManager;
        return $this;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
333
334
    }
}