activedirectory.plugin.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. <?php
  2. /*
  3. @name Connexion AD (LDAP)
  4. @author Valentin CARRUESCO <valentin.carruesco@sys1.fr>
  5. @link http://www.sys1.fr
  6. @licence Copyright Sys1
  7. @version 1.0.0
  8. @description Plugin pour l'identification sur Active Directory (LDAP)
  9. */
  10. //Recuperation d'un instance ldap avec les configuraiton serveur
  11. function ldap_instance($ssl = false){
  12. require_once(__DIR__.SLASH.'ActiveDirectory.class.php');
  13. global $conf;
  14. $ldap = new ActiveDirectory();
  15. $ldap->server = ($ssl ? 'ldaps://':'' ).$conf->get('activedirectory_server');
  16. $ldap->port = $ssl ? $conf->get('activedirectory_ssl_port'): $conf->get('activedirectory_port');
  17. $ldap->userRoot = $conf->get('activedirectory_users_root');
  18. $ldap->groupRoot = $conf->get('activedirectory_groups_root');
  19. $ldap->domain = $conf->get('activedirectory_domain');
  20. $ldap->protocolVersion = 3;
  21. return $ldap;
  22. }
  23. //Récuperation de l'ensemble des utilisateurs en LDAP (appellé par User::getAll)
  24. function ldap_plugin_all_users(&$users, $loadRights=false){
  25. require_once(__DIR__.SLASH.'ActiveDirectory.class.php');
  26. global $conf;
  27. try{
  28. $ldap = ldap_instance();
  29. $ldap->connect($conf->get('activedirectory_reader_login'),$conf->get('activedirectory_reader_password'));
  30. $attributes = ActiveDirectory::USER_SEARCH_DEFAULT_ATTRIBUTES;
  31. foreach(activedirectory_meta_data() as $data)
  32. $attributes .= ','.$data['adslug'];
  33. $infos = $ldap->search($conf->get('activedirectory_users_root'), null, $attributes);
  34. if(empty($infos)) return $ldap->disconnect();
  35. $allUsers = array();
  36. $authentificationAttribute = ActiveDirectory::authentification_attribute($conf->get('activedirectory_authentification'));
  37. foreach($infos as $info){
  38. if(isset($info[$authentificationAttribute][0]) && trim($info[$authentificationAttribute][0])!=''){
  39. $newUser = new User();
  40. ldap_user_fill($ldap,$newUser,$info,true,false);
  41. if($loadRights) user_rank_firm_by_group($newUser);
  42. $manager = new User();
  43. if(isset($info['manager'][0])){
  44. foreach($infos as $info2){
  45. if($info2['dn'] != $info['manager'][0]) continue;
  46. ldap_user_fill($ldap,$manager,$info2,false,false);
  47. }
  48. }
  49. $newUser->manager = $manager;
  50. $allUsers[] = $newUser;
  51. }
  52. }
  53. $users = $allUsers;
  54. }catch(Exception $e){
  55. $ldap->disconnect();
  56. //Décommenter la ligne qui suit pour avoir un message d'erreur si pb de connexion à l'AD
  57. //throw new Exception("Une erreur est survenue lors de la connexion à l'AD");
  58. }
  59. }
  60. //Récuperation d'un utilisateur précis en LDAP (appellé par User::check)
  61. function ldap_plugin_identification(&$user,$login,$password,$loadRight,$loadManager=true,$noPassword=false){
  62. global $_,$conf;
  63. require_once(__DIR__.SLASH.'ActiveDirectory.class.php');
  64. if($user != false) return;
  65. $ldap = ldap_instance();
  66. try{
  67. if($noPassword)
  68. $ldap->connect($conf->get('activedirectory_reader_login'), $conf->get('activedirectory_reader_password'));
  69. else
  70. $ldap->connect($login.$ldap->domain, $password);
  71. $attributes = ActiveDirectory::USER_SEARCH_DEFAULT_ATTRIBUTES;
  72. foreach(activedirectory_meta_data() as $data)
  73. $attributes .= ','.$data['adslug'];
  74. $infos = $ldap->search($conf->get('activedirectory_users_root'), $ldap->authentification_filter($login, $conf->get('activedirectory_authentification')), $attributes);
  75. if(!empty($infos)){
  76. $user = new User();
  77. ldap_user_fill($ldap,$user,$infos[0],$loadRight,$loadManager);
  78. user_rank_firm_by_group($user);
  79. foreach($user->firms as $firm){
  80. if($firm->has_plugin('fr.sys1.activedirectory')){
  81. $firmHasPlugin = true;
  82. break;
  83. }
  84. }
  85. }
  86. // if(!isset($firmHasPlugin)) throw new Exception("Ce compte n'est actif sur aucun établissement",403);
  87. $avatarPath = __ROOT__.FILE_PATH.AVATAR_PATH.$user->login.'.jpg';
  88. if(isset($user->meta['ldap_avatar'])){
  89. if(!file_exists(__ROOT__.FILE_PATH.AVATAR_PATH)) mkdir(__ROOT__.FILE_PATH.AVATAR_PATH,0755,true);
  90. file_put_contents($avatarPath,base64_decode($user->meta['ldap_avatar']));
  91. }
  92. }catch(Exception $e){
  93. switch ($e->getCode()) {
  94. case 403:
  95. // throw new Exception($e->getMessage(), 403);
  96. break;
  97. default:
  98. break;
  99. }
  100. }
  101. $ldap->disconnect();
  102. }
  103. //Remplissage d'une classe User en fonction des atttributs LDAPS
  104. function ldap_user_fill($ldap,&$user,$infos,$loadRight=false,$loadManager = false){
  105. global $conf;
  106. require_once(__DIR__.SLASH.'ActiveDirectory.class.php');
  107. //Vérifie que le compte n'est pas expiré (nb : 0 et 9223372036854775807 sont les deux valeurs possibles pour un n'expire jamais (allez comprendre la logique microsoft...))
  108. if(isset($infos['accountexpires'][0]) && $infos['accountexpires'][0]!=0 && $infos['accountexpires'][0]!=9223372036854775807){
  109. //Convertion en seconds
  110. $seconds = (float)($infos['accountexpires'][0] / 10000000);
  111. //Convertion d'un timestamp AD en timestamp UNIX
  112. $timestamp = round($seconds - (((1970-1601) * 365.242190) * 86400));
  113. if($timestamp <= time()) return;
  114. }
  115. // récupération du login en fonction de l'attribut AD que l'on va contrôler
  116. $attribute = ActiveDirectory::authentification_attribute($conf->get('activedirectory_authentification'));
  117. if(isset($infos[$attribute][0])) $user->login = $ldap->attribute_to_login(mb_strtolower($infos[$attribute][0]));
  118. if(isset($infos['sn'][0])) $user->setName($infos['sn'][0]);
  119. if(isset($infos['givenname'][0])) $user->setFirstName($infos['givenname'][0]);
  120. if(isset($infos['mail'][0])) $user->setMail($infos['mail'][0]);
  121. if(isset($infos['telephonenumber'][0])) $user->setPhone($infos['telephonenumber'][0]);
  122. if(isset($infos['mobile'][0])) $user->setMobile($infos['mobile'][0]);
  123. if(isset($infos['title'][0])) $user->setFunction($infos['title'][0]);
  124. if(isset($infos['department'][0])) $user->service = $infos['department'][0];
  125. if(isset($infos['thumbnailphoto'][0])) $user->meta['ldap_avatar'] = base64_encode($infos['thumbnailphoto'][0]);
  126. if(isset($infos['jpegphoto'][0])) $user->meta['ldap_avatar'] = base64_encode($infos['jpegphoto'][0]);
  127. foreach(activedirectory_meta_data() as $data)
  128. if(isset($infos[$data['adslug']][0])) $user->meta[$data['slug']] = $infos[$data['adslug']][0];
  129. if(isset($infos['whencreated'][0]) && strlen($infos['whencreated'][0])>=12 ){
  130. $created = substr($infos['whencreated'][0],0,8).' '.substr($infos['whencreated'][0],8,2).':'.substr($infos['whencreated'][0],10,2);
  131. $user->created = strtotime($created);
  132. }
  133. if(isset($infos['manager'][0])){
  134. $user->manager = $infos['manager'][0];
  135. if($loadManager){
  136. $managerEntry = $ldap->userFromCn($infos['manager'][0]);
  137. if(isset($managerEntry) && !empty($managerEntry)){
  138. $manager = new User();
  139. ldap_user_fill($ldap,$manager,$managerEntry[0],$loadRight,false);
  140. if(isset($managerEntry['sn'][0])) $manager->setName($managerEntry[0]['sn'][0]);
  141. if(isset($managerEntry['givenname'][0])) $manager->setFirstName($managerEntry[0]['givenname'][0]);
  142. if(isset($managerEntry['mail'][0])) $manager->setMail($managerEntry[0]['mail'][0]);
  143. if(isset($managerEntry['telephonenumber'][0])) $manager->setPhone($managerEntry[0]['telephonenumber'][0]);
  144. if(isset($managerEntry['mobile'][0])) $manager->setMobile($managerEntry[0]['mobile'][0]);
  145. if(isset($managerEntry['title'][0])) $manager->function = $managerEntry[0]['title'][0];
  146. if(isset($managerEntry[$attribute][0])) $manager->login = $ldap->attribute_to_login(mb_strtolower($managerEntry[0][$attribute][0]));
  147. $user->manager = $manager;
  148. }
  149. }
  150. }
  151. $user->origin = 'active_directory';
  152. if($loadRight){
  153. $groups = array();
  154. if(isset($infos['memberof'])){
  155. for($i=0; $i<count($infos['memberof'])-1; ++$i){
  156. $groupCN = $infos['memberof'][$i];
  157. list($group,$root) = explode(',',$groupCN);
  158. list($entity,$group) = explode('=',$group);
  159. //TODO decommenter une fois les pb de perf résolus
  160. //$ldap->recursiveGroups($groups,$groupCN);
  161. $groups[] = $group;
  162. }
  163. }
  164. $user->groups = $groups;
  165. }
  166. }
  167. function activedirectory_user_save(&$user,$userForm,&$response){
  168. if($user->origin != 'active_directory') return;
  169. if($user->login != $userForm->login) throw new Exception("L'identifiant n'est pas modifiable");
  170. global $_,$conf;
  171. require_once(__DIR__.SLASH.'ActiveDirectory.class.php');
  172. //Régles de définition de mot de passe
  173. if(!empty($userForm->password)){
  174. if(strlen($userForm->password)<7) throw new Exception("Le mot de passe doit être supérieur à 7 caractères");
  175. if(!preg_match('|[0-9]|i', $userForm->password)) throw new Exception("Le mot de passe doit contenir au moins un chiffre");
  176. if(!preg_match('|[a-z]|i', $userForm->password)) throw new Exception("Le mot de passe doit contenir au moins une lettre");
  177. if(!preg_match('|[a-z]|', $userForm->password)) throw new Exception("Le mot de passe doit contenir au moins une lettre Minuscule");
  178. if(!preg_match('|[A-Z]|', $userForm->password)) throw new Exception("Le mot de passe doit contenir au moins une lettre Majuscule");
  179. }
  180. $ldap = ldap_instance(true);
  181. if($conf->get('activedirectory_admin_login')=='') throw new Exception("Le compte AD admin n'est pas configuré, veuillez contacter un administrateur");
  182. $ldap->connect($conf->get('activedirectory_admin_login'),$conf->get('activedirectory_admin_password'));
  183. $cn = $ldap->cnFromLogin($user->login, $conf->get('activedirectory_authentification'));
  184. if(!$cn) throw new Exception("Impossible de trouver l'utilisateur dans la base active directory");
  185. $user->phone = $userForm->phone;
  186. $user->mobile = $userForm->mobile;
  187. $infos = $ldap->search($conf->get('activedirectory_users_root'),$ldap->authentification_filter($user->login, $conf->get('activedirectory_authentification')));
  188. $ldap->set($cn,'telephonenumber',$userForm->phone);
  189. $ldap->set($cn,'mobile',$userForm->mobile);
  190. $avatarPath = glob(__ROOT__.FILE_PATH.AVATAR_PATH.$user->login.'.*');
  191. if(!empty($avatarPath)){
  192. $avatarPath = $avatarPath[0];
  193. $temp = File::temp().rand(0,10000).basename($avatarPath);
  194. copy($avatarPath,$temp);
  195. Image::toJpg($temp);
  196. $temp = explode('.', $temp);
  197. array_pop($temp);
  198. $temp = implode('.',$temp).'.jpg';
  199. $ldap->set($cn,'jpegphoto',file_get_contents($temp));
  200. unlink($temp);
  201. }
  202. if(!empty($userForm->password)){
  203. $ldap->change_password($cn,$userForm->password);
  204. $user->preference('passwordTime',time());
  205. }
  206. $response['warning'] = 'Vous êtes sur un compte de société, seules les informations suivantes ont été modifiées :<br/>
  207. - Téléphone<br/>
  208. - Mobile<br/>
  209. - Mot de passe (7 caracteres minimum : Majuscules, minucules et chiffres)<br/>
  210. - Avatar (JPG uniquement)<br/>';
  211. $ldap->disconnect();
  212. }
  213. function user_rank_firm_by_group(&$user){
  214. require_once(__DIR__.SLASH.'ActiveDirectoryGroup.class.php');
  215. global $conf, $myFirm;
  216. $firms = array();
  217. $ranks = array();
  218. if(!isset($user->groups)) $user->groups = array();
  219. foreach(ActiveDirectoryGroup::loadAll(array(), null, null, array('*'),1) as $group){
  220. if(!in_array($group->adgroup,$user->groups)) continue;
  221. $firm = $group->join('firm');
  222. $rank = $group->join('rank');
  223. if(is_null($firm->id)) continue;
  224. $firms[$firm->id] = $firm;
  225. if(!isset($ranks[$firm->id])) $ranks[$firm->id] = array();
  226. $ranks[$firm->id][$rank->id] = $rank;
  227. }
  228. if(empty($ranks) && $conf->get('activedirectory_default_rank')!=''){
  229. foreach(Firm::loadAll() as $firm){
  230. if(!$firm->has_plugin('fr.sys1.activedirectory')) continue;
  231. $firms[$firm->id] = $firm;
  232. $ranks[$firm->id][$conf->get('activedirectory_default_rank')] = Rank::getById($conf->get('activedirectory_default_rank'));
  233. }
  234. }
  235. if(!empty($ranks)) {
  236. $user->setFirms($firms);
  237. $defaultFirm = !empty($user->preference('default_firm')) ? $user->preferences['default_firm'] : key($firms);
  238. $myFirm = $firms[$defaultFirm];
  239. }
  240. $user->ranks = $ranks;
  241. $user->loadRights();
  242. }
  243. function activedirectory_action(){
  244. global $_;
  245. require_once(__DIR__.SLASH.'action.php');
  246. }
  247. function activedirectory_plugin_menu(&$settingMenu){
  248. global $_, $myUser;
  249. if($myUser->can('activedirectory','configure'))
  250. $settingMenu[]= array(
  251. 'sort' =>1,
  252. 'url' => 'setting.php?section=activedirectory',
  253. 'icon' => 'fas fa-angle-right',
  254. 'label' => 'Active Directory'
  255. );
  256. }
  257. function activedirectory_plugin_page(){
  258. global $_;
  259. if(in_array($_['section'],array('activedirectory')) && file_exists(__DIR__.SLASH.'setting.'.$_['section'].'.php'))
  260. require_once(__DIR__.SLASH.'setting.'.$_['section'].'.php');
  261. }
  262. function activedirectory_plugin_section(&$sections){
  263. $sections['activedirectory'] = 'Gestion des droits sur les échanges avec l\'AD';
  264. }
  265. function activedirectory_plugin_install($id){
  266. if($id != 'fr.sys1.activedirectory') return;
  267. Entity::install(__DIR__);
  268. }
  269. function activedirectory_plugin_uninstall($id){
  270. if($id != 'fr.sys1.activedirectory') return;
  271. Entity::uninstall(__DIR__);
  272. }
  273. function activedirectory_directory_list(&$usermapping){
  274. foreach ($usermapping as $login => $infos) {
  275. $user = $infos['object'];
  276. //todo à dynamiser en fct de plugin_activedirectory_metafields
  277. if(isset($user->meta['personalPhone'])) $usermapping[$login]['values']['Portable (perso)'] = '<a href="tel: '.$user->meta['personalPhone'].'">'.$user->meta['personalPhone'].'</a>';
  278. // if(isset($user->meta['jobstart'])) $usermapping[$login]['values']['Date début contrat'] = $user->meta['jobstart'];
  279. }
  280. }
  281. function activedirectory_account_global(){
  282. global $myUser; ?>
  283. <div class="row">
  284. <?php foreach(activedirectory_meta_data() as $data): ?>
  285. <div class="col-md-6">
  286. <label for="<?php echo $data['slug']; ?>"><?php echo $data['label'] ?> :</label>
  287. <input id="<?php echo $data['slug']; ?>" name="<?php echo $data['slug']; ?>" class="form-control-plaintext" readonly="readonly" type="text" value="<?php echo isset($myUser->meta[$data['slug']])?$myUser->meta[$data['slug']]:''; ?>">
  288. </div>
  289. <?php endforeach; ?>
  290. </div>
  291. <?php
  292. }
  293. function activedirectory_meta_data(){
  294. global $conf;
  295. $data = array();
  296. $metaFields = preg_split('/('.PHP_EOL.'|\n|\r)/',$conf->get('activedirectory_metafields'),-1, PREG_SPLIT_NO_EMPTY);
  297. $metas = array('label','type','adslug','slug');
  298. foreach($metaFields as $line){
  299. $metaInfos = explode(':',$line);
  300. if(count($metaInfos)<4) continue;
  301. $lineData = array_combine($metas,$metaInfos);
  302. $data[] = $lineData;
  303. }
  304. return $data;
  305. }
  306. //Déclaration des settings de base
  307. //Types possibles : text,select ( + "values"=> array('1'=>'Val 1'),password,checkbox. Un simple string définit une catégorie.
  308. Configuration::setting('activedirectory',array(
  309. "Configuration de l'AD",
  310. 'activedirectory_server' => array("label"=>"Serveur","type"=>"text","legend"=>"L'adresse IP du serveur AD","placeholder"=>"192.168.XXX.XXX"),
  311. 'activedirectory_port' => array("label"=>"Port","type"=>"number","legend"=>"Le port sur lequel attaquer le serveur AD","placeholder"=>"389"),
  312. 'activedirectory_ssl_port' => array("label"=>"Port SSL","type"=>"number","legend"=>"Le port SSL sur lequel attaquer le serveur AD","placeholder"=>"636"),
  313. 'activedirectory_domain' => array("label"=>"Domaine","type"=>"text","legend"=>"Le domaine sur lequel se base l'AD","placeholder"=>"@EXAMPLE.LOCAL"),
  314. 'activedirectory_users_root' => array("label"=>'Racine des utilisateurs <small title="Cliquez pour ajouter une racine utilisateur supplémentaire" class="text-primary no-select right pointer" onclick="activedirectory_activedirectory_add_roots(this);"><i class="fas fa-plus"></i> Ajouter une racine supplémentaire</small>',"type"=>"text","legend"=>"La racine où chercher les users","placeholder"=>"OU=SYS1,OU=UTILISATEURS,OU=sys1.fr,DC=SYS1,DC=LOCAL","parameters"=>array("data-root"=>"users")),
  315. 'activedirectory_groups_root' => array("label"=>'Racine des groupes <small title="Cliquez pour ajouter une racine groupe supplémentaire" class="text-primary no-select right pointer" onclick="activedirectory_activedirectory_add_roots(this);"><i class="fas fa-plus"></i> Ajouter une racine supplémentaire</small>',"type"=>"text","legend"=>"La racine où chercher les groupes","placeholder"=>"OU=SYS1,OU=UTILISATEURS,OU=sys1.fr,DC=SYS1,DC=LOCAL","parameters"=>array("data-root"=>"groups")),
  316. "Compte Lecture seule",
  317. 'activedirectory_reader_login' => array("label"=>"CN","type"=>"text","legend"=>"Le Common Name du compte de lecture seule","placeholder"=>"CN=reader_account,OU=EXAMPLE,OU=APPLICATIONS,OU=example.fr,..."),
  318. 'activedirectory_reader_password' => array("label"=>"Mot de passe","type"=>"password","legend"=>"Le mot de passe du compte de lecture seule","placeholder"=>""),
  319. "Compte Administrateur",
  320. 'activedirectory_admin_login' => array("label"=>"CN","type"=>"text","legend"=>"Le Common Name du compte administrateur","placeholder"=>"CN=administrator_account,OU=EXAMPLE,OU=APPLICATIONS,OU=example.fr,..."),
  321. 'activedirectory_admin_password' => array("label"=>"Mot de passe","type"=>"password","legend"=>"Le mot de passe du compte administrateur","placeholder"=>""),
  322. "Champs de méta informations",
  323. 'activedirectory_metafields' => array("label"=>"Méta informations","type"=>"textarea","legend"=>"Vous pouvez remplir des méta champs pour les utilisateurs (un champ par ligne).<br>
  324. Ces métas champs sont requis par certains plugins et peuvent être renseignés depuis l'AD via la syntaxe : <code>Libellé:Type:nom-champ-ad:nom-meta</code>","placeholder"=>"Date début contrat:date:description:jobstart","parameters"=>array("cols"=>"100")),
  325. "Authentification",
  326. 'activedirectory_authentification' => array("label"=>"Authentification via l'attribut","type"=>"select","values"=>array("userprincipalname"=>"userPrincipalName","samaccountname"=>"sAMAccountName"),"default"=>"userprincipalname"),
  327. "Utilisateurs de l'AD",
  328. 'activedirectory_default_rank' => array("label"=>"Rang par défaut","legend"=>"Utilisé si aucun groupe AD n'a été défini pour le rang \"Utilisateur\" standard","type"=>"rank")
  329. ));
  330. Plugin::addJs('/js/main.js');
  331. Plugin::addCss('/css/main.css');
  332. Plugin::addHook('directory_list',"activedirectory_directory_list");
  333. Plugin::addHook("account_global", "activedirectory_account_global");
  334. Plugin::addHook("install", "activedirectory_plugin_install");
  335. Plugin::addHook("uninstall", "activedirectory_plugin_uninstall");
  336. Plugin::addHook("user_login", "ldap_plugin_identification");
  337. Plugin::addHook("user_load", "ldap_plugin_all_users");
  338. Plugin::addHook("user_save","activedirectory_user_save");
  339. Plugin::addHook("user_rank_firm", "user_rank_firm_by_group");
  340. Plugin::addHook("section", "activedirectory_plugin_section");
  341. Plugin::addHook("action", "activedirectory_action");
  342. Plugin::addHook("menu_setting", "activedirectory_plugin_menu");
  343. Plugin::addHook("content_setting", "activedirectory_plugin_page");
  344. ?>