Ldap.php 9.13 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
18
use Zend\EventManager\EventManager;
use Zend\EventManager\EventManagerAwareInterface;
use Zend\EventManager\EventManagerInterface;
use ZfcUser\Authentication\Adapter\AbstractAdapter;
use ZfcUser\Authentication\Adapter\AdapterChainEvent as AuthEvent;
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 AuthEvent|\Zend\EventManager\Event $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(\Zend\EventManager\Event $e)
Bertrand Gauthier's avatar
Bertrand Gauthier committed
89
90
    {
        if ($this->isSatisfied()) {
91
92
93
94
95
            try {
                $storage = $this->getStorage()->read();
            } catch (ExceptionInterface $e) {
                throw new RuntimeException("Erreur de lecture du storage");
            }
Bertrand Gauthier's avatar
Bertrand Gauthier committed
96
            $e->setIdentity($storage['identity'])
97
98
                ->setCode(AuthenticationResult::SUCCESS)
                ->setMessages(['Authentication successful.']);
Bertrand Gauthier's avatar
Bertrand Gauthier committed
99
100
101
            return;
        }

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

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

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

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

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

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

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

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

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

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

        // LDAP auth
        $result  = $this->getLdapAuthAdapter()->setUsername($username)->setPassword($credential)->authenticate();
195
196
197
198
199
200
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');
            $eventClasse->setTarget($this)->setParams([
                'result' => $result
            ]);
            $this->getEventManager()->trigger($eventClasse);
        }

206
        $success = $result->isValid();
207

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

217
218
        return $success;
    }
219

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

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

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

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

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

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

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