Cas.php 8.28 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;
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
11
use Zend\Authentication\Exception\UnexpectedValueException;
use Zend\Authentication\Result as AuthenticationResult;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
12
13
14
use Zend\EventManager\EventManager;
use Zend\EventManager\EventManagerAwareInterface;
use Zend\EventManager\EventManagerInterface;
15
use Zend\Router\Http\TreeRouteStack;
16
use Zend\ServiceManager\ServiceLocatorAwareTrait;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
17
18
19
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>
 */
26
class Cas extends AbstractAdapter implements EventManagerAwareInterface, ServiceLocatorAwareInterface
Bertrand Gauthier's avatar
Bertrand Gauthier committed
27
{
28
    use ServiceLocatorAwareTrait;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
29
30
31
32
33

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

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

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

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

50
51
52
53
54
    /**
     * @var LdapPeopleMapper
     */
    protected $ldapPeopleMapper;

Bertrand Gauthier's avatar
Bertrand Gauthier committed
55
    /**
56
     * Réalise l'authentification.
57
     *
Bertrand Gauthier's avatar
Bertrand Gauthier committed
58
59
60
61
62
63
64
     * @param AuthEvent $e
     * @return boolean
     * @throws UnexpectedValueException
     * @see ChainableAdapter
     */
    public function authenticate(AuthEvent $e)
    {
65
66
67
68
69
70
71
72
//        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)
73
                    ->setMessages(['Authentication successful.']);
74
75
            return;
        }
76

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

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

84
        $this->getCasClient()->forceAuthentication();
Bertrand Gauthier's avatar
Bertrand Gauthier committed
85
86
87
88

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

89
        $identity = $this->getCasClient(false)->getUser();
90

Bertrand Gauthier's avatar
Bertrand Gauthier committed
91
        error_reporting($oldErrorReporting);
92

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

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

        /* @var $userService User */
105
        $userService = $this->serviceLocator->get('unicaen-auth_user_service');
106
        $userService->userAuthenticated($ldapPeople);
Bertrand Gauthier's avatar
Bertrand Gauthier committed
107
    }
108

109
    /**
110
     *
111
112
113
114
115
116
117
118
     * @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
        }
119

120
        $router = $this->serviceLocator->get('router'); /* @var $router TreeRouteStack */
121
122
        $returnUrl = $router->getRequestUri()->setPath($router->getBaseUrl())->toString();
        $this->getCasClient()->logoutWithRedirectService($returnUrl);
123
    }
124

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

138
139
140
        if (!$initClient) {
            return $this->casClient;
        }
141

142
143
144
145
146
147
148
        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'];
        }
149

150
        $options = $this->casOptions;
151

152
        if (array_key_exists('debug', $options) && (bool) $options['debug']) {
153
            $this->casClient->setDebug();
154
        }
155

156
        // initialize phpCAS
157
        $this->casClient->client($options['version'], $options['hostname'], $options['port'], $options['uri'], true);
158
        // no SSL validation for the CAS server
159
        $this->casClient->setNoCasServerValidation();
160

161
162
        return $this->casClient;
    }
163

164
165
    /**
     * Spécifie le client CAS.
166
     *
167
168
169
170
171
172
173
     * @param phpCAS $casClient
     * @return self
     */
    public function setCasClient(phpCAS $casClient)
    {
        $this->casClient = $casClient;
        return $this;
174
    }
175

Bertrand Gauthier's avatar
Bertrand Gauthier committed
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
    /**
     * @param ModuleOptions $options
     */
    public function setOptions(ModuleOptions $options)
    {
        $this->options = $options;
    }

    /**
     * @return ModuleOptions
     */
    public function getOptions()
    {
        if (!$this->options instanceof ModuleOptions) {
            $options = array_merge(
191
192
                    $this->serviceLocator->get('zfcuser_module_options')->toArray(),
                    $this->serviceLocator->get('unicaen-auth_module_options')->toArray());
Bertrand Gauthier's avatar
Bertrand Gauthier committed
193
194
195
196
197
            $this->setOptions(new ModuleOptions($options));
        }
        return $this->options;
    }

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

Bertrand Gauthier's avatar
Bertrand Gauthier committed
233
    /**
234
     * {@inheritdoc}
Bertrand Gauthier's avatar
Bertrand Gauthier committed
235
236
237
238
239
240
     */
    public function setEventManager(EventManagerInterface $eventManager)
    {
        $this->eventManager = $eventManager;
        return $this;
    }
Bertrand Gauthier's avatar
Bertrand Gauthier committed
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
281
282
283
284

    /**
     * @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
285
}