Cas.php 8.22 KB
Newer Older
Bertrand Gauthier's avatar
Bertrand Gauthier committed
1
2
3
<?php
namespace UnicaenAuth\Authentication\Adapter;

4
5
use phpCAS;
use UnicaenApp\Exception;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
6
use UnicaenAuth\Options\ModuleOptions;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
7
8
use Zend\Authentication\Exception\UnexpectedValueException;
use Zend\Authentication\Result as AuthenticationResult;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
9
10
11
use Zend\EventManager\EventManager;
use Zend\EventManager\EventManagerAwareInterface;
use Zend\EventManager\EventManagerInterface;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
12
use Zend\Mvc\Router\Http\TreeRouteStack;
Bertrand Gauthier's avatar
Bertrand Gauthier committed
13
14
15
16
17
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
18
19
20
21
22
23

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

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

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

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

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

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

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

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

80
        $this->getCasClient()->forceAuthentication();
Bertrand Gauthier's avatar
Bertrand Gauthier committed
81
82
83
84

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

85
        $identity = $this->getCasClient(false)->getUser();
86

Bertrand Gauthier's avatar
Bertrand Gauthier committed
87
        error_reporting($oldErrorReporting);
88

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

97
98
99
100
101
102
        // 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 */
        $userService = $this->getServiceManager()->get('unicaen-auth_user_service');
        $userService->userAuthenticated($ldapPeople);
Bertrand Gauthier's avatar
Bertrand Gauthier committed
103
    }
104

105
    /**
106
     *
107
108
109
110
111
112
113
114
     * @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
        }
115

116
117
118
119
        if ($this->getCasClient()->isAuthenticated()) {
            $router = $this->getServiceManager()->get('router'); /* @var $router TreeRouteStack */
            $returnUrl = $router->getRequestUri()->setPath($router->getBaseUrl())->toString();
            $this->getCasClient(false)->logoutWithRedirectService($returnUrl);
120
121
        }
    }
122

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

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

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

148
        $options = $this->casOptions;
149

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

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

159
160
        return $this->casClient;
    }
161

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

Bertrand Gauthier's avatar
Bertrand Gauthier committed
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
    /**
     * @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;
    }

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

    /**
     * Set service manager
     *
     * @param ServiceManager $serviceManager
210
     * @return self
Bertrand Gauthier's avatar
Bertrand Gauthier committed
211
212
213
214
215
216
     */
    public function setServiceManager(ServiceManager $serviceManager)
    {
        $this->serviceManager = $serviceManager;
        return $this;
    }
217

Bertrand Gauthier's avatar
Bertrand Gauthier committed
218
219
220
221
222
223
224
225
226
    /**
     * Retrieve EventManager instance
     *
     * @return EventManagerInterface
     */
    public function getEventManager()
    {
        return $this->eventManager;
    }
227

Bertrand Gauthier's avatar
Bertrand Gauthier committed
228
229
230
231
    /**
     * Inject an EventManager instance
     *
     * @param  EventManagerInterface $eventManager
232
     * @return self
Bertrand Gauthier's avatar
Bertrand Gauthier committed
233
234
235
236
237
238
     */
    public function setEventManager(EventManagerInterface $eventManager)
    {
        $this->eventManager = $eventManager;
        return $this;
    }
Bertrand Gauthier's avatar
Bertrand Gauthier committed
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
281
282

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