LdapConnectionsTable.php 13.1 KB
<?php
namespace App\Model\Table;

use Cake\ORM\Table;
use Cake\ORM\TableRegistry;
use Cake\Auth\DefaultPasswordHasher;
use Cake\Core\Exception\Exception;

class LdapConnectionsTable extends AppTable
{

    public $useTable = false;

    private $host;

    private $port;

    private $baseDn;

    private $authenticationType;

    private $filter;
    
    /*MCM*/
    // EP
    //private $anonymous;
    private $ldap_authentified;
    private $bindDn;
    private $bindPass;
    /* fin MCM*/

    private $LDAP_USED = TRUE;

    private $fakeLDAPUsers = [];

    public function __construct()
    {
        parent::__construct();
    }

    // EP
    public function useFakeLdap()
    {
        return ! $this->useLdap();
    }

    public function useLdap()
    {
        $this->checkConfiguration();
        return $this->LDAP_USED;
    }

    private function buildFakeLdapUsers()
    {
        return $this->buildFakeLdapUsersFromDB();
    }

    private function buildFakeLdapUsersFromDB()
    {
        $users = TableRegistry::get('Users')->find();
        
        $ldapUsers = [];
        
        foreach ($users as $user) {
            $names = explode(" ", $user['nom']);
            if (isset($names[1])) {
                $ldapUsers[] = [
                    'sn' => [
                        $names[0]
                    ],
                    'mail' => [
                        $user['email']
                    ],
                    'givenname' => [
                        $names[1]
                    ],
                    $this->authenticationType => [
                        $user['username']
                    ],
                    'userpassword' => [
                        $user['password']
                    ]
                ];
            } else {
                $ldapUsers[] = [
                    'sn' => [
                        $names[0]
                    ],
                    'mail' => [
                        $user['email']
                    ],
                    'givenname' => " ",
                    $this->authenticationType => [
                        $user['username']
                    ],
                    'userpassword' => [
                        $user['password']
                    ]
                ];
            }
        }
        
        // EP (aout 2017)
        // ATTENTION : Utilisateur IMPORTANT.
        // Avec cet utilisateur, on simule un utilisateur qui n'est PAS dans la table utilisateurs
        // Il devrait donc se voir attribuer un role "Utilisateur" sans pour autant que ça soit écrit dans la table !!!
        // login = '_NouvelUtilisateur_username'
        // pass = '_NouvelUtilisateur_password'
        // $prefix = "_NouvelUtilisateur_";
        $ldapUsers[] = [
            'sn' => [
                'UTILISATEUR'
            ],
            'givenname' => [
                'FAKE_LDAP'
            ],
            // 'mail' => [$login.'email'],
            'mail' => [
                'fakeldapuser@domain.fr'
            ],
            // $this->authenticationType => [$prefix.'username'],
            $this->authenticationType => [
                $this->getTheFakeLdapUser()['login']
            ],
            // $this->authenticationType => ['usere'],
            'userpassword' => [
                $this->getTheFakeLdapUser()['pass']
            ]
            // 'userpassword' => ['toto'],
        ];
        
        return $ldapUsers;
    }

    private function checkConfiguration()
    {
        $config = TableRegistry::get('Configurations')->find()
            ->where([
            'id =' => 1
        ])
            ->first();
        
        //$this->LDAP_USED = $config->LDAP_USED ? TRUE : FALSE;
        $this->LDAP_USED = $config->ldap_used;
        
        if (! $this->LDAP_USED) {
            //$this->authenticationType = $config->authentificationType_ldap;
            $this->authenticationType = $config->ldap_authenticationType;
            if (empty($this->fakeLDAPUsers))
                $this->fakeLDAPUsers = $this->buildFakeLdapUsers();
            return true;
        }
        // debug($this->fakeLDAPUsers);
        
        $ldapConfig = $config->toArray();
        
        if (! empty($config->ldap_host) && ! empty($config->ldap_port) && ! empty($config->ldap_baseDn) && ! empty($config->ldap_authenticationType) && ! empty($config->ldap_filter)) {
        //if (! empty($config->host_ldap) && ! empty($config->port_ldap) && ! empty($config->baseDn_ldap) && ! empty($config->authentificationType_ldap) && ! empty($config->filter_ldap)) {
            /*
            $this->host = $config->host_ldap;
            $this->port = $config->port_ldap;
            $this->baseDn = $config->baseDn_ldap;
            $this->filter = $config->filter_ldap;
            $this->authenticationType = $config->authentificationType_ldap;
			*/
            $this->host = $config->ldap_host;
            $this->port = $config->ldap_port;
            $this->baseDn = $config->ldap_baseDn;
            $this->filter = $config->ldap_filter;
            $this->authenticationType = $config->ldap_authenticationType;
            $this->ldap_authentified = $config->ldap_authentified;
            $this->bindDn = $config->ldap_bindDn;
            $this->bindPass = $config->ldap_bindPass;
            
            return true;
        }
        
        throw new Exception('The ldap configuration is not valid : <br />
			<ul>
				<li>host = ' . @$ldapConfig['host'] . '</li>
				<li>port = ' . @$ldapConfig['port'] . '</li>
				<li>baseDn = ' . @$ldapConfig['baseDn'] . '</li>
				<li>filter = ' . @$ldapConfig['filter'] . '</li>
				<li>authenticationType = ' . @$ldapConfig['authenticationType'] . '</li>
			</ul>');
    }

    public function getAllLdapUsers()
    {
        try {
            if ($this->checkConfiguration()) {
                // REAL LDAP
                if ($this->LDAP_USED) {
                    $ldapConnection = ldap_connect($this->host, $this->port);
                    ldap_set_option($ldapConnection, LDAP_OPT_PROTOCOL_VERSION, 3);
                    
                    $results = ldap_search($ldapConnection, $this->baseDn, $this->filter);
                    
                    $res = ldap_get_entries($ldapConnection, $results);
                }                // FAKE LDAP
                else {
                    $res = $this->fakeLDAPUsers;
                }
                return $res;
            }
        } catch (Exception $e) {}
        return false;
    }

    // $userName = login
    public function getUserAttributes($userName)
    {
        try {
            
            if ($this->checkConfiguration()) {
                if ($this->LDAP_USED) {
                    $ldapConnection = ldap_connect($this->host, $this->port);
                    ldap_set_option($ldapConnection, LDAP_OPT_PROTOCOL_VERSION, 3);
                    $results = ldap_search($ldapConnection, $this->baseDn, '(' . $this->authenticationType . '=' . $userName . ')');
                    return ldap_get_entries($ldapConnection, $results);
                } else
                    return array(
                        $this->getFakeLdapUser($userName)
                    );
            }
        } catch (Exception $e) {}
        
        return false;
    }

    public function getAuthenticationType()
    {
        return $this->authenticationType;
    }

    // EP added
    public function getFakeLdapUser($login)
    {
        foreach ($this->fakeLDAPUsers as $user) {
            if ($login == $user[$this->authenticationType][0])
                return $user;
        }
        return FALSE;
    }

    /**
     * Return a list of Users with key = username & value = email
     */
    public function getUsersWithNameAndEmail() {
        $usersWithNameAndEmail = [];
        // Get all users (with ALL their attributes)
        $u = $this->getAllLdapUsers();
        // Sort users
        //sort($u);
        //debug($u);
        // (EP) Refactorisation pour éviter code redondant ci-dessous, c'était pourtant pas compliqué, poil dans la main...
        $nb_users = $this->LDAP_USED ? $u['count'] : sizeof($u)-1;
        for ($i = 0; $i < $nb_users; $i ++)
            // $utilisateurs["Pallier Etienne"] = ["email"]
            $usersWithNameAndEmail[ $u[$i]['sn'][0].' '.$u[$i]['givenname'][0] ] = $u[$i]['mail'][0];
            //debug($usersWithNameAndEmail);
            // Sort users (without modifying the keys, don't use sort() but asort() !!!!!!!!!!!!!)
            ksort($usersWithNameAndEmail);
            return $usersWithNameAndEmail;
    }
    
    /**
     * Return a list of Users with key = username & value = username
     */
    public function getListUsers()
    {
        $u = $this->getAllLdapUsers();
        $utilisateurs = [];
        
        if ($this->LDAP_USED) {
            for ($i = 0; $i < $u['count']; $i ++) {
                $utilisateurs[$u[$i]['sn'][0] . ' ' . $u[$i]['givenname'][0]] = $u[$i]['sn'][0] . ' ' . $u[$i]['givenname'][0];
            }
        } else {
            for ($i = 0; $i < sizeof($u) - 1; $i ++) {
                $utilisateurs[$u[$i]['sn'][0] . ' ' . $u[$i]['givenname'][0]] = $u[$i]['sn'][0] . ' ' . $u[$i]['givenname'][0];
            }
        }
        
        return $utilisateurs;
    }

    /**
     * Return a list of login ofUsers with key = username & value = login
     */
    public function getListLoginUsers()
    {
        $u = $this->getAllLdapUsers();
        $utilisateurs = [];
        
        if ($this->LDAP_USED) {
            for ($i = 0; $i < $u['count']; $i ++) {
                $utilisateurs[$u[$i]['sn'][0] . ' ' . $u[$i]['givenname'][0]] = $u[$i][$this->authenticationType][0];
            }
        } else {
            for ($i = 0; $i < sizeof($u) - 1; $i ++) {
                $utilisateurs[$u[$i]['sn'][0] . ' ' . $u[$i]['givenname'][0]] = $u[$i][$this->authenticationType][0];
            }
        }
        
        return $utilisateurs;
    }

    /**
     * Return a list of mail of Users with key = username & value = mail
     */
    public function getListEmailUsers()
    {
        $u = $this->getAllLdapUsers();
        $utilisateurs = [];
        
        if ($this->LDAP_USED) {
            for ($i = 0; $i < $u['count']; $i ++) {
                if (isset($u[$i]['mail'][0])) {
                    $utilisateurs[$u[$i]['sn'][0] . ' ' . $u[$i]['givenname'][0]] = $u[$i]['mail'][0];
                } else {
                    $utilisateurs[$u[$i]['sn'][0] . ' ' . $u[$i]['givenname'][0]] = 'N/A';
                }
            }
        } else {
            for ($i = 0; $i < sizeof($u) - 1; $i ++) {
                $utilisateurs[$u[$i]['sn'][0] . ' ' . $u[$i]['givenname'][0]] = $u[$i]['mail'][0];
            }
        }
        
        return $utilisateurs;
    }

    /**
     * Return size of list users
     */
    public function getNbUsers()
    {
        $u = $this->getAllLdapUsers();
        
        if ($this->LDAP_USED) {
            $nbUsers = $u['count'];
        } else {
            $nbUsers = sizeof($u) - 1;
        }
        return $nbUsers;
    }

    // Utilisateur du ldap qui n'est pas dans la table utilisateurs
    // => il a donc le role "Utilisateur" PAR DEFAUT
    private function getTheFakeLdapUser()
    {
        return [
            'login' => '_fake_ldap_user_',
            'pass' => '_fake_ldap_user_pass'
        ];
    }

    public function ldapAuthentication($login, $password)
    {
        try {
            if ($this->checkConfiguration()) {
                
                if ($this->LDAP_USED) {
                    if (strlen(trim($password)) == 0)
                        return FALSE;
                    $ldapConnection = ldap_connect($this->host, $this->port);
                    ldap_set_option($ldapConnection, LDAP_OPT_PROTOCOL_VERSION, 3);
                    if (@ldap_bind($ldapConnection, $this->authenticationType . '=' . $login . ',' . $this->baseDn, $password)) {
                        return $this->getUserAttributes($login)[0];
                        /*
                         * } else {
                         * return false;
                         */
                    }
                } else {
                    $user = $this->getFakeLdapUser($login);
                    // debug($user);
                    if ($user === false)
                        return FALSE;
                    // $this->authenticationType peut valoir "uid" ou "cn"... (par défaut "uid" pour le fake ldap, à confirmer...)
                    // if ($user['uid'][0] == "_NouvelUtilisateur_username" && $user['userpassword'][0] == "_NouvelUtilisateur_password") return $user;
                    // if ($user[$this->authenticationType][0] == "_NouvelUtilisateur_username" && $user['userpassword'][0] == "_NouvelUtilisateur_password") return $user;
                    if ($user[$this->authenticationType][0] == $this->getTheFakeLdapUser()['login'] && $user['userpassword'][0] == $this->getTheFakeLdapUser()['pass'])
                        return $user;
                    if ((new DefaultPasswordHasher())->check($password, $user['userpassword'][0]))
                        return $user;
                    // if ($user != false && $user['userpassword'][0] == $password) {
                }
            }
        } catch (Exception $e) {}
        return FALSE;
    }
}
?>