Ldap.php 9.39 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;
7
use UnicaenApp\ServiceManager\ServiceLocatorAwareInterface;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
8
use UnicaenAuth\Options\ModuleOptions;
9
use UnicaenAuth\Service\User;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
10
use Zend\Authentication\Adapter\Ldap as LdapAuthAdapter;
11
12
use Zend\Authentication\Exception\ExceptionInterface;
use Zend\Authentication\Result as AuthenticationResult;
Laurent Lécluse's avatar
Laurent Lécluse committed
13
use Zend\EventManager\Event;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
14
15
16
use Zend\EventManager\EventManager;
use Zend\EventManager\EventManagerAwareInterface;
use Zend\EventManager\EventManagerInterface;
17
use Zend\ServiceManager\ServiceLocatorAwareTrait;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
18
19
20
use ZfcUser\Authentication\Adapter\AbstractAdapter;
use ZfcUser\Authentication\Adapter\AdapterChainEvent as AuthEvent;
use ZfcUser\Authentication\Adapter\ChainableAdapter;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
21
22
23
24
25
26

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

31
    const USURPATION_USERNAMES_SEP = '=';
Bertrand Gauthier's avatar
Bertrand Gauthier committed
32
33

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

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

43
44
45
46
47
    /**
     * @var LdapPeopleMapper
     */
    protected $ldapPeopleMapper;

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

53
    /**
54
     * @var string
55
56
     */
    protected $usernameUsurpe;
57

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

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

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

89
        $success = $this->authenticateUsername($username, $credential);
90

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

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

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

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

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

146
        return [];
Bertrand Gauthier's avatar
Bertrand Gauthier committed
147
148
    }

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

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

        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);
        }

185
        $success = $result->isValid();
186

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

196
197
        return $success;
    }
198

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

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

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

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

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

    /**
Bertrand Gauthier's avatar
Bertrand Gauthier committed
286
287
288
     * Retrieve EventManager instance
     *
     * @return EventManagerInterface
Bertrand Gauthier's avatar
Bertrand Gauthier committed
289
     */
Bertrand Gauthier's avatar
Bertrand Gauthier committed
290
    public function getEventManager()
Bertrand Gauthier's avatar
Bertrand Gauthier committed
291
    {
Bertrand Gauthier's avatar
Bertrand Gauthier committed
292
        return $this->eventManager;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
293
    }
294

Bertrand Gauthier's avatar
Bertrand Gauthier committed
295
    /**
Bertrand Gauthier's avatar
Bertrand Gauthier committed
296
297
298
299
     * Inject an EventManager instance
     *
     * @param  EventManagerInterface $eventManager
     * @return Ldap
Bertrand Gauthier's avatar
Bertrand Gauthier committed
300
     */
Bertrand Gauthier's avatar
Bertrand Gauthier committed
301
    public function setEventManager(EventManagerInterface $eventManager)
Bertrand Gauthier's avatar
Bertrand Gauthier committed
302
    {
303
304
305
306
        $eventManager->setIdentifiers([
            __NAMESPACE__,
            __CLASS__,
        ]);
Bertrand Gauthier's avatar
Bertrand Gauthier committed
307
308
        $this->eventManager = $eventManager;
        return $this;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
309
310
    }
}