Cas.php 8.93 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
use phpCAS;
6
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
10
use Zend\Authentication\Exception\UnexpectedValueException;
use Zend\Authentication\Result as AuthenticationResult;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
11
12
13
use Zend\EventManager\EventManager;
use Zend\EventManager\EventManagerAwareInterface;
use Zend\EventManager\EventManagerInterface;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
14
use Zend\Mvc\Router\Http\TreeRouteStack;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
15
16
17
18
19
use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\ServiceManagerAwareInterface;
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

/**
 * CAS authentication adpater
 *
 * @author Bertrand GAUTHIER <bertrand.gauthier@unicaen.fr>
 */
Bertrand Gauthier's avatar
Bertrand Gauthier committed
26
class Cas extends AbstractAdapter implements ServiceManagerAwareInterface, EventManagerAwareInterface
Bertrand Gauthier's avatar
Bertrand Gauthier committed
27
{
Bertrand Gauthier's avatar
Bertrand Gauthier committed
28
29
30
31
32
33
34
35
36
    /**
     * @var ServiceManager
     */
    protected $serviceManager;

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

Bertrand Gauthier's avatar
Bertrand Gauthier committed
38
39
40
41
    /**
     * @var ModuleOptions
     */
    protected $options;
42
43
44
45
46
47
48
49
50
51

    /**
     * @var array
     */
    protected $casOptions;

    /**
     * @var phpCAS
     */
    protected $casClient;
52

53
54
55
56
57
    /**
     * @var LdapPeopleMapper
     */
    protected $ldapPeopleMapper;

Bertrand Gauthier's avatar
Bertrand Gauthier committed
58
    /**
59
     * Réalise l'authentification.
60
     *
Bertrand Gauthier's avatar
Bertrand Gauthier committed
61
62
63
64
65
66
67
     * @param AuthEvent $e
     * @return boolean
     * @throws UnexpectedValueException
     * @see ChainableAdapter
     */
    public function authenticate(AuthEvent $e)
    {
68
69
70
71
72
73
74
75
//        if ($e->getIdentity()) {
//            return;
//        }
	/* DS : modification liée à une boucle infinie lors de l'authentification CAS */
	if ($this->isSatisfied()) {
            $storage = $this->getStorage()->read();
            $e->setIdentity($storage['identity'])
                    ->setCode(AuthenticationResult::SUCCESS)
76
                    ->setMessages(['Authentication successful.']);
77
78
            return;
        }
79

Bertrand Gauthier's avatar
Bertrand Gauthier committed
80
81
82
83
        $config = $this->getOptions()->getCas();
        if (!$config) {
            return; // NB: l'authentification CAS est désactivée ssi le tableau des options est vide
        }
84

Bertrand Gauthier's avatar
Bertrand Gauthier committed
85
86
        error_reporting($oldErrorReporting = error_reporting() & ~E_NOTICE);

87
        $this->getCasClient()->forceAuthentication();
Bertrand Gauthier's avatar
Bertrand Gauthier committed
88
89
90
91

        // at this step, the user has been authenticated by the CAS server
        // and the user's login name can be read with phpCAS::getUser().

92
        $identity = $this->getCasClient(false)->getUser();
93

Bertrand Gauthier's avatar
Bertrand Gauthier committed
94
        error_reporting($oldErrorReporting);
95

Bertrand Gauthier's avatar
Bertrand Gauthier committed
96
97
98
99
100
101
        $e->setIdentity($identity);
        $this->setSatisfied(true);
        $storage = $this->getStorage()->read();
        $storage['identity'] = $e->getIdentity();
        $this->getStorage()->write($storage);
        $e->setCode(AuthenticationResult::SUCCESS)
102
103
          ->setMessages(['Authentication successful.']);

104
        // recherche de l'individu dans l'annuaire LDAP (il existe forcément puisque l'auth CAS a réussi)
105
106
107
108
109
        $ldapPeople = $this->getLdapPeopleMapper()->findOneByUsername($identity);

        /* @var $userService User */
        $userService = $this->getServiceManager()->get('unicaen-auth_user_service');
        $userService->userAuthenticated($ldapPeople);
Bertrand Gauthier's avatar
Bertrand Gauthier committed
110
    }
111

112
    /**
113
     *
114
115
116
117
118
119
120
121
     * @param AuthEvent $e
     * @see ChainableAdapter
     */
    public function logout(AuthEvent $e)
    {
        if (!$this->getOptions()->getCas()) {
            return; // NB: l'authentification CAS est désactivée ssi le tableau des options est vide
        }
122

123
124
125
126
        if ($this->getCasClient()->isAuthenticated()) {
            $router = $this->getServiceManager()->get('router'); /* @var $router TreeRouteStack */
            $returnUrl = $router->getRequestUri()->setPath($router->getBaseUrl())->toString();
            $this->getCasClient(false)->logoutWithRedirectService($returnUrl);
127
128
        }
    }
129

130
    /**
131
     * Retourne le client CAS.
132
     *
133
134
135
     * @param boolean $initClient
     * @return phpCAS
     * @throws Exception
136
     */
137
    public function getCasClient($initClient = true)
138
    {
139
140
        if (null === $this->casClient) {
            $this->casClient = new phpCAS();
141
        }
142

143
144
145
        if (!$initClient) {
            return $this->casClient;
        }
146

147
148
149
150
151
152
153
        if (null === $this->casOptions) {
            $config = $this->getOptions()->getCas();
            if (!isset($config['connection']['default']['params']) || !$config['connection']['default']['params']) {
                throw new Exception("Les paramètres de connexion au serveur CAS sont invalides.");
            }
            $this->casOptions = $config['connection']['default']['params'];
        }
154

155
        $options = $this->casOptions;
156

157
        if (array_key_exists('debug', $options) && (bool) $options['debug']) {
158
            $this->casClient->setDebug();
159
        }
160

161
        // initialize phpCAS
162
        $this->casClient->client($options['version'], $options['hostname'], $options['port'], $options['uri'], true);
163
        // no SSL validation for the CAS server
164
        $this->casClient->setNoCasServerValidation();
165

166
167
        return $this->casClient;
    }
168

169
170
    /**
     * Spécifie le client CAS.
171
     *
172
173
174
175
176
177
178
     * @param phpCAS $casClient
     * @return self
     */
    public function setCasClient(phpCAS $casClient)
    {
        $this->casClient = $casClient;
        return $this;
179
    }
180

Bertrand Gauthier's avatar
Bertrand Gauthier committed
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
    /**
     * @param ModuleOptions $options
     */
    public function setOptions(ModuleOptions $options)
    {
        $this->options = $options;
    }

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

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
    /**
     * 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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
    /**
     * Get service manager
     *
     * @return ServiceManager
     */
    public function getServiceManager()
    {
        return $this->serviceManager;
    }

    /**
     * Set service manager
     *
     * @param ServiceManager $serviceManager
242
     * @return self
Bertrand Gauthier's avatar
Bertrand Gauthier committed
243
244
245
246
247
248
     */
    public function setServiceManager(ServiceManager $serviceManager)
    {
        $this->serviceManager = $serviceManager;
        return $this;
    }
249

Bertrand Gauthier's avatar
Bertrand Gauthier committed
250
251
252
253
254
255
256
257
258
    /**
     * Retrieve EventManager instance
     *
     * @return EventManagerInterface
     */
    public function getEventManager()
    {
        return $this->eventManager;
    }
259

Bertrand Gauthier's avatar
Bertrand Gauthier committed
260
261
262
263
    /**
     * Inject an EventManager instance
     *
     * @param  EventManagerInterface $eventManager
264
     * @return self
Bertrand Gauthier's avatar
Bertrand Gauthier committed
265
266
267
268
269
270
     */
    public function setEventManager(EventManagerInterface $eventManager)
    {
        $this->eventManager = $eventManager;
        return $this;
    }
Bertrand Gauthier's avatar
Bertrand Gauthier committed
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314

    /**
     * @param TreeRouteStack $router
     */
    public function reconfigureRoutesForCasAuth(TreeRouteStack $router)
    {
        $router->addRoutes([
            // remplace les routes existantes (cf. config du module)
            'zfcuser' => [
                'type'          => 'Literal',
                'priority'      => 1000,
                'options'       => [
                    'route'    => '/auth',
                    'defaults' => [
                        'controller' => 'zfcuser',
                        'action'     => 'index',
                    ],
                ],
                'may_terminate' => true,
                'child_routes'  => [
                    'login'  => [
                        'type'    => 'Literal',
                        'options' => [
                            'route'    => '/connexion',
                            'defaults' => [
                                'controller' => 'zfcuser',
                                'action'     => 'authenticate', // zappe l'action 'login'
                            ],
                        ],
                    ],
                    'logout' => [
                        'type'    => 'Literal',
                        'options' => [
                            'route'    => '/deconnexion',
                            'defaults' => [
                                'controller' => 'zfcuser',
                                'action'     => 'logout',
                            ],
                        ],
                    ],
                ],
            ],
        ]);
    }
Bertrand Gauthier's avatar
Bertrand Gauthier committed
315
}