Db.php 8.44 KB
Newer Older
1
<?php
2

3
4
namespace UnicaenAuth\Authentication\Adapter;

5
use Interop\Container\ContainerInterface;
6
use UnicaenApp\ServiceManager\ServiceLocatorAwareInterface;
7
use UnicaenApp\ServiceManager\ServiceLocatorAwareTrait;
8
use UnicaenAuth\Options\ModuleOptions;
9
use UnicaenAuth\Options\Traits\ModuleOptionsAwareTrait;
10
11
use Zend\Authentication\Result as AuthenticationResult;
use Zend\Crypt\Password\Bcrypt;
12
use Zend\EventManager\EventInterface;
13
14
15
16
use Zend\ServiceManager\ServiceManager;
use Zend\Session\Container as SessionContainer;
use ZfcUser\Entity\UserInterface;
use ZfcUser\Mapper\UserInterface as UserMapperInterface;
17
18

/**
Bertrand Gauthier's avatar
Bertrand Gauthier committed
19
20
21
 * Adpater d'authentification à partir de la base de données.
 * 
 * Ajout par rapport à la classe mère : si aucune base de données ou table n'existe,
22
 * l'authentification ne plante pas (i.e. renvoit false).
23
24
25
 *
 * @author Bertrand GAUTHIER <bertrand.gauthier@unicaen.fr>
 */
26
class Db extends AbstractAdapter implements ServiceLocatorAwareInterface
27
{
28
29
    use ModuleOptionsAwareTrait;

30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
    const TYPE = 'db';

    /**
     * @var string
     */
    protected $type = self::TYPE;

    /**
     * @var UserMapperInterface
     */
    protected $mapper;

    /**
     * @var callable
     */
    protected $credentialPreprocessor;

    /**
     * @var ServiceManager
     */
    protected $serviceManager;

    /**
     * @var \ZfcUser\Options\ModuleOptions
     */
    protected $options;

57
58
    use ServiceLocatorAwareTrait;

59
    /**
60
61
     * Set service locator
     *
62
     * @param ContainerInterface $serviceLocator
63
64
     * @return self
     * @deprecated Abandonnez l'injection du service locator, svp
65
     */
66
    public function setServiceLocator(ContainerInterface $serviceLocator)
67
68
69
70
71
72
    {
        $this->serviceLocator = $serviceLocator;
        $this->serviceManager = $serviceLocator;

        return $this;
    }
73

74
75
76
77
78
79
80
81
82
    /**
     * Called when user id logged out
     * @param EventInterface $e
     */
    public function logout(EventInterface $e)
    {
        $this->getStorage()->clear();
    }

83
84
85
    /**
     * Authentification.
     *
86
     * @param EventInterface $e
87
88
     * @return boolean
     */
89
    public function authenticate(EventInterface $e)
90
    {
91
92
93
94
95
        $type = $e->getTarget()->getRequest()->getPost()->get('type');
        if ($type !== $this->type) {
            return;
        }

96
97
98
99
        // 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().
        if ($e->getTarget()->getIdentity()) {
100
            return true;
101
        }
102
103
104
105
106
107
108
109
110
111

        $e = $e->getTarget();
        if ($this->isSatisfied()) {
            $storage = $this->getStorage()->read();
            $e->setIdentity($storage['identity'])
                ->setCode(AuthenticationResult::SUCCESS)
                ->setMessages(array('Authentication successful.'));
            return;
        }

112
113
114
115
        if (! $this->isEnabled()) {
            return;
        }

116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
        $identity   = $e->getRequest()->getPost()->get('identity');
        $credential = $e->getRequest()->getPost()->get('credential');
        $credential = $this->preProcessCredential($credential);
        /** @var UserInterface|null $userObject */
        $userObject = null;

        // Cycle through the configured identity sources and test each
        $fields = $this->getOptions()->getAuthIdentityFields();
        while (!is_object($userObject) && count($fields) > 0) {
            $mode = array_shift($fields);
            switch ($mode) {
                case 'username':
                    $userObject = $this->getMapper()->findByUsername($identity);
                    break;
                case 'email':
                    $userObject = $this->getMapper()->findByEmail($identity);
                    break;
            }
134
        }
135
136
137
138
139

        if (!$userObject) {
            $e->setCode(AuthenticationResult::FAILURE_IDENTITY_NOT_FOUND)
                ->setMessages(array('A record with the supplied identity could not be found.'));
            $this->setSatisfied(false);
140
141
            return false;
        }
142

143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
        if ($this->getOptions()->getEnableUserState()) {
            // Don't allow user to login if state is not in allowed list
            if (!in_array($userObject->getState(), $this->getOptions()->getAllowedLoginStates())) {
                $e->setCode(AuthenticationResult::FAILURE_UNCATEGORIZED)
                    ->setMessages(array('A record with the supplied identity is not active.'));
                $this->setSatisfied(false);
                return false;
            }
        }

        $bcrypt = new Bcrypt();
        $bcrypt->setCost($this->getOptions()->getPasswordCost());
        if (!$bcrypt->verify($credential, $userObject->getPassword())) {
            // Password does not match
            $e->setCode(AuthenticationResult::FAILURE_CREDENTIAL_INVALID)
                ->setMessages(array('Supplied credential is invalid.'));
            $this->setSatisfied(false);
            return false;
        }

        // regen the id
        $session = new SessionContainer($this->getStorage()->getNameSpace());
        $session->getManager()->regenerateId();

        // Success!
        $e->setIdentity($userObject->getId());
        // Update user's password hash if the cost parameter has changed
        $this->updateUserPasswordHash($userObject, $credential, $bcrypt);
        $this->setSatisfied(true);
        $storage = $this->getStorage()->read();
        $storage['identity'] = $e->getIdentity();
        $this->getStorage()->write($storage);
        $e->setCode(AuthenticationResult::SUCCESS)
            ->setMessages(array('Authentication successful.'));
    }

179
180
181
182
183
184
185
186
187
188
189
190
191
192
    /**
     * @return bool
     */
    protected function isEnabled()
    {
        $config = $this->moduleOptions->getDb();

        if (isset($config['enabled'])) {
            return (bool) $config['enabled'];
        }

        return false;
    }

193
194
195
196
197
198
199
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
    protected function updateUserPasswordHash(UserInterface $userObject, $password, Bcrypt $bcrypt)
    {
        $hash = explode('$', $userObject->getPassword());
        if ($hash[2] === $bcrypt->getCost()) {
            return;
        }
        $userObject->setPassword($bcrypt->create($password));
        $this->getMapper()->update($userObject);
        return $this;
    }

    public function preProcessCredential($credential)
    {
        $processor = $this->getCredentialPreprocessor();
        if (is_callable($processor)) {
            return $processor($credential);
        }

        return $credential;
    }

    /**
     * getMapper
     *
     * @return UserMapperInterface
     */
    public function getMapper()
    {
        if (null === $this->mapper) {
            $this->mapper = $this->getServiceManager()->get('zfcuser_user_mapper');
        }

        return $this->mapper;
    }

    /**
     * setMapper
     *
     * @param UserMapperInterface $mapper
     * @return \ZfcUser\Authentication\Adapter\Db
     */
    public function setMapper(UserMapperInterface $mapper)
    {
        $this->mapper = $mapper;

        return $this;
    }

    /**
     * Get credentialPreprocessor.
     *
     * @return callable
     */
    public function getCredentialPreprocessor()
    {
        return $this->credentialPreprocessor;
    }

    /**
     * Set credentialPreprocessor.
     *
     * @param callable $credentialPreprocessor
     * @return $this
     */
    public function setCredentialPreprocessor($credentialPreprocessor)
    {
        $this->credentialPreprocessor = $credentialPreprocessor;
        return $this;
    }

    /**
     * Retrieve service manager instance
     *
     * @return ServiceManager
     */
    public function getServiceManager()
    {
        return $this->serviceManager;
    }

    /**
     * Set service manager instance
     *
     * @param ContainerInterface $serviceManager
     */
    public function setServiceManager(ContainerInterface $serviceManager)
    {
        $this->serviceManager = $serviceManager;
281
282
283
    }

    /**
284
     * @param \ZfcUser\Options\ModuleOptions $options
285
286
     * @return self
     */
287
    public function setOptions(\ZfcUser\Options\ModuleOptions $options)
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
    {
        $this->options = $options;
        return $this;
    }

    /**
     * @return ModuleOptions
     */
    public function getOptions()
    {
        if (!$this->options instanceof ModuleOptions) {
            $this->setOptions($this->getServiceManager()->get('unicaen-auth_module_options'));
        }
        return $this->options;
    }
}