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

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

class LdapConnectionsTable extends AppTable {

	public $useTable = false;

	private $host;
	private $port;
	private $baseDn;
	private $authenticationType;
	private $filter;
	
	private $USE_LDAP = TRUE;
	private $fakeLDAPUsers = [];

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

	//EP
	public function useFakeLdap() {
		return ! $this->useLdap();
	}
	public function useLdap() {
		$this->checkConfiguration();
		return $this->USE_LDAP;
	}
	
	
	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']],
				'uid' => [$user['username']],
				'givenname' => [$names[1]],
				$this->authenticationType => [$user['username']],
				'userpassword' => [$user['password']],
				];
			}
			else {
				$ldapUsers[] = [
				'sn' => [$names[0]],
				'mail' => [$user['email']],
				'uid' => [$user['username']],
				'givenname' => " ",
				$this->authenticationType => [$user['username']],
				'userpassword' => [$user['password']],
				];
			}
		}

		$prefix = "_NouvelUtilisateur_";
		$ldapUsers[] = [
				'sn' => ['NOUVEL'],
				'givenname' => ['UTILISATEUR'],
				'mail' => [$prefix.'email'],
				'uid' => [$prefix.'login'],
				$this->authenticationType => [$prefix.'username'],
				'userpassword' => [$prefix.'password'],
		];
		
		
		return $ldapUsers;
	}
	
	private function checkConfiguration() {

		$config = TableRegistry::get('Configurations')->find()->where(['id =' => 1])->first();
		
		$this->USE_LDAP = $config->use_ldap ? TRUE : FALSE;

		if (!$this->USE_LDAP) {
			$this->authenticationType = $config->authentificationType_ldap;
			if (empty($this->fakeLDAPUsers)) $this->fakeLDAPUsers = $this->buildFakeLdapUsers();
			return true;
		}
		
		$ldapConfig = $config->toArray();
		
		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;

			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->USE_LDAP) {
					$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->USE_LDAP) {
					$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['uid'][0]) return $user;
		}
		return FALSE;
	}
	
	/**
	 * Return a list of Users with key = login & value = username
	 */
	public function getListUsers() {
		$u = $this->getAllLdapUsers();
		$utilisateurs= [];
		
		if($this->USE_LDAP) {
			for($i = 0; $i < $u['count']; $i++) {
				$utilisateurs[$u[$i][$this->authenticationType][0]] = $u[$i]['givenname'][0].' '.$u[$i]['sn'][0];
			}
		}
		else {
			for($i = 0; $i < sizeof($u)-1; $i++) {
				$utilisateurs[$u[$i][$this->authenticationType][0]] = $u[$i]['givenname'][0].' '.$u[$i]['sn'][0];
			}
		}
		
		return $utilisateurs;
	}
	
	/**
	 * Return size of list users
	 */
	public function getNbUsers() {
		$u = $this->getAllLdapUsers();

		if($this->USE_LDAP) {
			$nbUsers = $u['count'];
		}
		else {
			$nbUsers = sizeof($u)-1;
		}
		return $nbUsers;
	}
	
	public function ldapAuthentication($login, $password) {

		try {
			if($this->checkConfiguration()) {
				
				if ($this->USE_LDAP) {
					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);
					if ($user != false && (new DefaultPasswordHasher)->check($password, $user['userpassword'][0])) {
					//if ($user != false && $user['userpassword'][0] == $password) {
						return $user;
					}
				}
			}
		}
		catch (Exception $e) { }
		return false;
	}
	
}
?>