Ldap.php 9.08 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;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
13
14
15
16
17
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
18
19
20
21
22
23

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

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

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

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

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

48
    /**
49
     * @var string
50
51
     */
    protected $usernameUsurpe;
52

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
    /**
     * @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
79
    /**
80
     *
81
     * @param Event $e
Bertrand Gauthier's avatar
Bertrand Gauthier committed
82
     * @return boolean
83
84
     * @throws \Zend\Authentication\Adapter\Exception\ExceptionInterface
     * @throws \Zend\Ldap\Exception\LdapException
Bertrand Gauthier's avatar
Bertrand Gauthier committed
85
86
     * @see ChainableAdapter
     */
87
    public function authenticate(Event $e)
Bertrand Gauthier's avatar
Bertrand Gauthier committed
88
    {
89
90
        $e = $e->getTarget();

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

Bertrand Gauthier's avatar
Bertrand Gauthier committed
103
        $username   = $e->getRequest()->getPost()->get('identity');
Bertrand Gauthier's avatar
Bertrand Gauthier committed
104
105
        $credential = $e->getRequest()->getPost()->get('credential');

106
107
108
109
110
111
        if (function_exists('mb_strtolower')) {
            $username = mb_strtolower($username, 'UTF-8');
        } else {
            $username = strtolower($username);
        }

112
        $success = $this->authenticateUsername($username, $credential);
113

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

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

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

144
        /* @var $userService User */
145
        $this->userService->userAuthenticated($ldapPeople);
Bertrand Gauthier's avatar
Bertrand Gauthier committed
146
147
    }

148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
    /**
     * 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
            ];
        }
167

168
        return [];
Bertrand Gauthier's avatar
Bertrand Gauthier committed
169
170
    }

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

        // LDAP auth
        $result  = $this->getLdapAuthAdapter()->setUsername($username)->setPassword($credential)->authenticate();
196
197
198
199
200

        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');
201
202
            $eventClasse->setTarget($this);
            $eventClasse->setParams([
203
204
                'result' => $result
            ]);
205
            $this->getEventManager()->triggerEvent($eventClasse);
206
207
        }

208
        $success = $result->isValid();
209

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

219
220
        return $success;
    }
221

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

    /**
Bertrand Gauthier's avatar
Bertrand Gauthier committed
253
     * @return ModuleOptions
Bertrand Gauthier's avatar
Bertrand Gauthier committed
254
     */
Bertrand Gauthier's avatar
Bertrand Gauthier committed
255
    public function getOptions()
Bertrand Gauthier's avatar
Bertrand Gauthier committed
256
    {
Bertrand Gauthier's avatar
Bertrand Gauthier committed
257
        return $this->options;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
258
    }
Bertrand Gauthier's avatar
Bertrand Gauthier committed
259

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

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

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

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

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