Cas.php 2.15 KB
Newer Older
Bertrand Gauthier's avatar
Bertrand Gauthier committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<?php
namespace UnicaenAuth\Authentication\Adapter;

use Zend\Authentication\Exception\UnexpectedValueException;
use Zend\Authentication\Result as AuthenticationResult;
use \ZfcUser\Authentication\Adapter\AdapterChainEvent as AuthEvent;
use \ZfcUser\Authentication\Adapter\ChainableAdapter;

/**
 * CAS authentication adpater
 *
 * @author Bertrand GAUTHIER <bertrand.gauthier@unicaen.fr>
 */
class Cas extends Ldap
{

    /**
     * 
     * @param AuthEvent $e
     * @return boolean
     * @throws UnexpectedValueException
     * @see ChainableAdapter
     */
    public function authenticate(AuthEvent $e)
    {
        error_reporting($oldErrorReporting = error_reporting() & ~E_NOTICE);

        require_once __VENDOR_DIR__ . '/gorg/phpcas/CAS.php';

        $infos = $this->getOptions()->getCasConnectionInfos();

        if (array_key_exists('debug', $infos) && (bool) $infos['debug']) {
            \phpCAS::setDebug();
        }

        // initialize phpCAS
        \phpCAS::client(
                $infos['version'], $infos['hostname'], $infos['port'], $infos['uri'], true
        );

        // no SSL validation for the CAS server
        \phpCAS::setNoCasServerValidation();

        \phpCAS::forceAuthentication();

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

        $identity = \phpCAS::getUser();

        error_reporting($oldErrorReporting);

        // nécessaire pour que le "base DN" de l'objet \Zend\Ldap\Ldap soit bien initialisé
        $this->getLdapAdapter()->setUsername($identity)
                ->setPassword('xxx') // peu importe mais pas null
                ->authenticate();
        
        $e->setIdentity($identity);
        $this->setSatisfied(true);
        $storage = $this->getStorage()->read();
        $storage['identity'] = $e->getIdentity();
        $this->getStorage()->write($storage);
        $e->setCode(AuthenticationResult::SUCCESS)
          ->setMessages(array('Authentication successful.'));
        
        $this->getEventManager()->trigger('userAuthenticated', $e);

        $e->stopPropagation();
        
        return true;
    }

}