userrights.class.inc.php 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540
  1. <?php
  2. // Copyright (C) 2010-2013 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. /**
  19. * User rights management API
  20. *
  21. * @copyright Copyright (C) 2010-2012 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. */
  24. class UserRightException extends CoreException
  25. {
  26. }
  27. define('UR_ALLOWED_NO', 0);
  28. define('UR_ALLOWED_YES', 1);
  29. define('UR_ALLOWED_DEPENDS', 2);
  30. define('UR_ACTION_READ', 1); // View an object
  31. define('UR_ACTION_MODIFY', 2); // Create/modify an object/attribute
  32. define('UR_ACTION_DELETE', 3); // Delete an object
  33. define('UR_ACTION_BULK_READ', 4); // Export multiple objects
  34. define('UR_ACTION_BULK_MODIFY', 5); // Create/modify multiple objects
  35. define('UR_ACTION_BULK_DELETE', 6); // Delete multiple objects
  36. define('UR_ACTION_CREATE', 7); // Instantiate an object
  37. define('UR_ACTION_APPLICATION_DEFINED', 10000); // Application specific actions (CSV import, View schema...)
  38. /**
  39. * User management module API
  40. *
  41. * @package iTopORM
  42. */
  43. abstract class UserRightsAddOnAPI
  44. {
  45. abstract public function CreateAdministrator($sAdminUser, $sAdminPwd, $sLanguage = 'EN US'); // could be used during initial installation
  46. abstract public function Init(); // loads data (possible optimizations)
  47. // Used to build select queries showing only objects visible for the given user
  48. abstract public function GetSelectFilter($sLogin, $sClass, $aSettings = array()); // returns a filter object
  49. abstract public function IsActionAllowed($oUser, $sClass, $iActionCode, /*dbObjectSet*/ $oInstanceSet = null);
  50. abstract public function IsStimulusAllowed($oUser, $sClass, $sStimulusCode, /*dbObjectSet*/ $oInstanceSet = null);
  51. abstract public function IsActionAllowedOnAttribute($oUser, $sClass, $sAttCode, $iActionCode, /*dbObjectSet*/ $oInstanceSet = null);
  52. abstract public function IsAdministrator($oUser);
  53. abstract public function IsPortalUser($oUser);
  54. abstract public function FlushPrivileges();
  55. /**
  56. * ...
  57. */
  58. public function MakeSelectFilter($sClass, $aAllowedOrgs, $aSettings = array(), $sAttCode = null)
  59. {
  60. if ($sAttCode == null)
  61. {
  62. $sAttCode = $this->GetOwnerOrganizationAttCode($sClass);
  63. }
  64. if (empty($sAttCode))
  65. {
  66. return $oFilter = new DBObjectSearch($sClass);
  67. }
  68. $oExpression = new FieldExpression($sAttCode, $sClass);
  69. $oFilter = new DBObjectSearch($sClass);
  70. $oListExpr = ListExpression::FromScalars($aAllowedOrgs);
  71. $oCondition = new BinaryExpression($oExpression, 'IN', $oListExpr);
  72. $oFilter->AddConditionExpression($oCondition);
  73. if ($this->HasSharing())
  74. {
  75. if (($sAttCode == 'id') && isset($aSettings['bSearchMode']) && $aSettings['bSearchMode'])
  76. {
  77. // Querying organizations (or derived)
  78. // and the expected list of organizations will be used as a search criteria
  79. // Therefore the query can also return organization having objects shared with the allowed organizations
  80. //
  81. // 1) build the list of organizations sharing something with the allowed organizations
  82. // Organization <== sharing_org_id == SharedObject having org_id IN {user orgs}
  83. $oShareSearch = new DBObjectSearch('SharedObject');
  84. $oOrgField = new FieldExpression('org_id', 'SharedObject');
  85. $oShareSearch->AddConditionExpression(new BinaryExpression($oOrgField, 'IN', $oListExpr));
  86. $oSearchSharers = new DBObjectSearch('Organization');
  87. $oSearchSharers->AllowAllData();
  88. $oSearchSharers->AddCondition_ReferencedBy($oShareSearch, 'sharing_org_id');
  89. $aSharers = array();
  90. foreach($oSearchSharers->ToDataArray(array('id')) as $aRow)
  91. {
  92. $aSharers[] = $aRow['id'];
  93. }
  94. // 2) Enlarge the overall results: ... OR id IN(id1, id2, id3)
  95. if (count($aSharers) > 0)
  96. {
  97. $oSharersList = ListExpression::FromScalars($aSharers);
  98. $oFilter->MergeConditionExpression(new BinaryExpression($oExpression, 'IN', $oSharersList));
  99. }
  100. }
  101. $aShareProperties = SharedObject::GetSharedClassProperties($sClass);
  102. if ($aShareProperties)
  103. {
  104. $sShareClass = $aShareProperties['share_class'];
  105. $sShareAttCode = $aShareProperties['attcode'];
  106. $oSearchShares = new DBObjectSearch($sShareClass);
  107. $oSearchShares->AllowAllData();
  108. $sHierarchicalKeyCode = MetaModel::IsHierarchicalClass('Organization');
  109. $oOrgField = new FieldExpression('org_id', $sShareClass);
  110. $oSearchShares->AddConditionExpression(new BinaryExpression($oOrgField, 'IN', $oListExpr));
  111. $aShared = array();
  112. foreach($oSearchShares->ToDataArray(array($sShareAttCode)) as $aRow)
  113. {
  114. $aShared[] = $aRow[$sShareAttCode];
  115. }
  116. if (count($aShared) > 0)
  117. {
  118. $oObjId = new FieldExpression('id', $sClass);
  119. $oSharedIdList = ListExpression::FromScalars($aShared);
  120. $oFilter->MergeConditionExpression(new BinaryExpression($oObjId, 'IN', $oSharedIdList));
  121. }
  122. }
  123. } // if HasSharing
  124. return $oFilter;
  125. }
  126. }
  127. abstract class User extends cmdbAbstractObject
  128. {
  129. public static function Init()
  130. {
  131. $aParams = array
  132. (
  133. "category" => "core",
  134. "key_type" => "autoincrement",
  135. "name_attcode" => "login",
  136. "state_attcode" => "",
  137. "reconc_keys" => array(),
  138. "db_table" => "priv_user",
  139. "db_key_field" => "id",
  140. "db_finalclass_field" => "",
  141. "display_template" => "",
  142. );
  143. MetaModel::Init_Params($aParams);
  144. //MetaModel::Init_InheritAttributes();
  145. MetaModel::Init_AddAttribute(new AttributeExternalKey("contactid", array("targetclass"=>"Person", "allowed_values"=>null, "sql"=>"contactid", "is_null_allowed"=>true, "on_target_delete"=>DEL_MANUAL, "depends_on"=>array())));
  146. MetaModel::Init_AddAttribute(new AttributeExternalField("last_name", array("allowed_values"=>null, "extkey_attcode"=> 'contactid', "target_attcode"=>"name")));
  147. MetaModel::Init_AddAttribute(new AttributeExternalField("first_name", array("allowed_values"=>null, "extkey_attcode"=> 'contactid', "target_attcode"=>"first_name")));
  148. MetaModel::Init_AddAttribute(new AttributeExternalField("email", array("allowed_values"=>null, "extkey_attcode"=> 'contactid', "target_attcode"=>"email")));
  149. MetaModel::Init_AddAttribute(new AttributeString("login", array("allowed_values"=>null, "sql"=>"login", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  150. MetaModel::Init_AddAttribute(new AttributeApplicationLanguage("language", array("sql"=>"language", "default_value"=>"EN US", "is_null_allowed"=>false, "depends_on"=>array())));
  151. MetaModel::Init_AddAttribute(new AttributeLinkedSetIndirect("profile_list", array("linked_class"=>"URP_UserProfile", "ext_key_to_me"=>"userid", "ext_key_to_remote"=>"profileid", "allowed_values"=>null, "count_min"=>1, "count_max"=>0, "depends_on"=>array())));
  152. MetaModel::Init_AddAttribute(new AttributeLinkedSetIndirect("allowed_org_list", array("linked_class"=>"URP_UserOrg", "ext_key_to_me"=>"userid", "ext_key_to_remote"=>"allowed_org_id", "allowed_values"=>null, "count_min"=>1, "count_max"=>0, "depends_on"=>array())));
  153. // Display lists
  154. MetaModel::Init_SetZListItems('details', array('contactid', 'first_name', 'email', 'login', 'language', 'profile_list', 'allowed_org_list')); // Attributes to be displayed for the complete details
  155. MetaModel::Init_SetZListItems('list', array('finalclass', 'first_name', 'last_name', 'login')); // Attributes to be displayed for a list
  156. // Search criteria
  157. MetaModel::Init_SetZListItems('standard_search', array('login', 'contactid')); // Criteria of the std search form
  158. MetaModel::Init_SetZListItems('advanced_search', array('login', 'contactid')); // Criteria of the advanced search form
  159. }
  160. abstract public function CheckCredentials($sPassword);
  161. abstract public function TrustWebServerContext();
  162. abstract public function CanChangePassword();
  163. abstract public function ChangePassword($sOldPassword, $sNewPassword);
  164. /*
  165. * Compute a name in best effort mode
  166. */
  167. public function GetFriendlyName()
  168. {
  169. if (!MetaModel::IsValidAttCode(get_class($this), 'contactid'))
  170. {
  171. return $this->Get('login');
  172. }
  173. if ($this->Get('contactid') != 0)
  174. {
  175. $sFirstName = $this->Get('first_name');
  176. $sLastName = $this->Get('last_name');
  177. $sEmail = $this->Get('email');
  178. if (strlen($sFirstName) > 0)
  179. {
  180. return "$sFirstName $sLastName";
  181. }
  182. elseif (strlen($sEmail) > 0)
  183. {
  184. return "$sLastName <$sEmail>";
  185. }
  186. else
  187. {
  188. return $sLastName;
  189. }
  190. }
  191. return $this->Get('login');
  192. }
  193. /*
  194. * Overload the standard behavior
  195. */
  196. public function DoCheckToWrite()
  197. {
  198. parent::DoCheckToWrite();
  199. // Note: This MUST be factorized later: declare unique keys (set of columns) in the data model
  200. $aChanges = $this->ListChanges();
  201. if (array_key_exists('login', $aChanges))
  202. {
  203. if (strcasecmp($this->Get('login'), $this->GetOriginal('login')) !== 0)
  204. {
  205. $sNewLogin = $aChanges['login'];
  206. $oSearch = DBObjectSearch::FromOQL_AllData("SELECT User WHERE login = :newlogin");
  207. if (!$this->IsNew())
  208. {
  209. $oSearch->AddCondition('id', $this->GetKey(), '!=');
  210. }
  211. $oSet = new DBObjectSet($oSearch, array(), array('newlogin' => $sNewLogin));
  212. if ($oSet->Count() > 0)
  213. {
  214. $this->m_aCheckIssues[] = Dict::Format('Class:User/Error:LoginMustBeUnique', $sNewLogin);
  215. }
  216. }
  217. }
  218. // Check that this user has at least one profile assigned
  219. $oSet = $this->Get('profile_list');
  220. if ($oSet->Count() == 0)
  221. {
  222. $this->m_aCheckIssues[] = Dict::Format('Class:User/Error:AtLeastOneProfileIsNeeded');
  223. }
  224. }
  225. function GetGrantAsHtml($sClass, $iAction)
  226. {
  227. if (UserRights::IsActionAllowed($sClass, $iAction, null, $this))
  228. {
  229. return '<span style="background-color: #ddffdd;">'.Dict::S('UI:UserManagement:ActionAllowed:Yes').'</span>';
  230. }
  231. else
  232. {
  233. return '<span style="background-color: #ffdddd;">'.Dict::S('UI:UserManagement:ActionAllowed:No').'</span>';
  234. }
  235. }
  236. function DoShowGrantSumary($oPage, $sClassCategory)
  237. {
  238. if (UserRights::IsAdministrator($this))
  239. {
  240. // Looks dirty, but ok that's THE ONE
  241. $oPage->p(Dict::S('UI:UserManagement:AdminProfile+'));
  242. return;
  243. }
  244. $oKPI = new ExecutionKPI();
  245. $aDisplayData = array();
  246. foreach (MetaModel::GetClasses($sClassCategory) as $sClass)
  247. {
  248. $aClassStimuli = MetaModel::EnumStimuli($sClass);
  249. if (count($aClassStimuli) > 0)
  250. {
  251. $aStimuli = array();
  252. foreach ($aClassStimuli as $sStimulusCode => $oStimulus)
  253. {
  254. if (UserRights::IsStimulusAllowed($sClass, $sStimulusCode, null, $this))
  255. {
  256. $aStimuli[] = '<span title="'.$sStimulusCode.': '.htmlentities($oStimulus->GetDescription(), ENT_QUOTES, 'UTF-8').'">'.htmlentities($oStimulus->GetLabel(), ENT_QUOTES, 'UTF-8').'</span>';
  257. }
  258. }
  259. $sStimuli = implode(', ', $aStimuli);
  260. }
  261. else
  262. {
  263. $sStimuli = '<em title="'.Dict::S('UI:UserManagement:NoLifeCycleApplicable+').'">'.Dict::S('UI:UserManagement:NoLifeCycleApplicable').'</em>';
  264. }
  265. $aDisplayData[] = array(
  266. 'class' => MetaModel::GetName($sClass),
  267. 'read' => $this->GetGrantAsHtml($sClass, UR_ACTION_READ),
  268. 'bulkread' => $this->GetGrantAsHtml($sClass, UR_ACTION_BULK_READ),
  269. 'write' => $this->GetGrantAsHtml($sClass, UR_ACTION_MODIFY),
  270. 'bulkwrite' => $this->GetGrantAsHtml($sClass, UR_ACTION_BULK_MODIFY),
  271. 'stimuli' => $sStimuli,
  272. );
  273. }
  274. $oKPI->ComputeAndReport('Computation of user rights');
  275. $aDisplayConfig = array();
  276. $aDisplayConfig['class'] = array('label' => Dict::S('UI:UserManagement:Class'), 'description' => Dict::S('UI:UserManagement:Class+'));
  277. $aDisplayConfig['read'] = array('label' => Dict::S('UI:UserManagement:Action:Read'), 'description' => Dict::S('UI:UserManagement:Action:Read+'));
  278. $aDisplayConfig['bulkread'] = array('label' => Dict::S('UI:UserManagement:Action:BulkRead'), 'description' => Dict::S('UI:UserManagement:Action:BulkRead+'));
  279. $aDisplayConfig['write'] = array('label' => Dict::S('UI:UserManagement:Action:Modify'), 'description' => Dict::S('UI:UserManagement:Action:Modify+'));
  280. $aDisplayConfig['bulkwrite'] = array('label' => Dict::S('UI:UserManagement:Action:BulkModify'), 'description' => Dict::S('UI:UserManagement:Action:BulkModify+'));
  281. $aDisplayConfig['stimuli'] = array('label' => Dict::S('UI:UserManagement:Action:Stimuli'), 'description' => Dict::S('UI:UserManagement:Action:Stimuli+'));
  282. $oPage->table($aDisplayConfig, $aDisplayData);
  283. }
  284. function DisplayBareRelations(WebPage $oPage, $bEditMode = false)
  285. {
  286. parent::DisplayBareRelations($oPage, $bEditMode);
  287. if (!$bEditMode)
  288. {
  289. $oPage->SetCurrentTab(Dict::S('UI:UserManagement:GrantMatrix'));
  290. $this->DoShowGrantSumary($oPage, 'bizmodel');
  291. // debug
  292. if (false)
  293. {
  294. $oPage->SetCurrentTab('More on user rigths (dev only)');
  295. $oPage->add("<h3>User rights</h3>\n");
  296. $this->DoShowGrantSumary($oPage, 'addon/userrights');
  297. $oPage->add("<h3>Change log</h3>\n");
  298. $this->DoShowGrantSumary($oPage, 'core/cmdb');
  299. $oPage->add("<h3>Application</h3>\n");
  300. $this->DoShowGrantSumary($oPage, 'application');
  301. $oPage->add("<h3>GUI</h3>\n");
  302. $this->DoShowGrantSumary($oPage, 'gui');
  303. }
  304. }
  305. }
  306. public function CheckToDelete(&$oDeletionPlan)
  307. {
  308. if (MetaModel::GetConfig()->Get('demo_mode'))
  309. {
  310. // Users deletion is NOT allowed in demo mode
  311. $oDeletionPlan->AddToDelete($this, null);
  312. $oDeletionPlan->SetDeletionIssues($this, array('deletion not allowed in demo mode.'), true);
  313. $oDeletionPlan->ComputeResults();
  314. return false;
  315. }
  316. return parent::CheckToDelete($oDeletionPlan);
  317. }
  318. protected function DBDeleteSingleObject()
  319. {
  320. if (MetaModel::GetConfig()->Get('demo_mode'))
  321. {
  322. // Users deletion is NOT allowed in demo mode
  323. return;
  324. }
  325. parent::DBDeleteSingleObject();
  326. }
  327. }
  328. /**
  329. * Abstract class for all types of "internal" authentication i.e. users
  330. * for which the application is supplied a login and a password opposed
  331. * to "external" users for whom the authentication is performed outside
  332. * of the application (by the web server for example).
  333. * Note that "internal" users do not necessary correspond to a local authentication
  334. * they may be authenticated by a remote system, like in authent-ldap.
  335. */
  336. abstract class UserInternal extends User
  337. {
  338. // Nothing special, just a base class to categorize this type of authenticated users
  339. public static function Init()
  340. {
  341. $aParams = array
  342. (
  343. "category" => "core",
  344. "key_type" => "autoincrement",
  345. "name_attcode" => "login",
  346. "state_attcode" => "",
  347. "reconc_keys" => array('login'),
  348. "db_table" => "priv_internaluser",
  349. "db_key_field" => "id",
  350. "db_finalclass_field" => "",
  351. );
  352. MetaModel::Init_Params($aParams);
  353. MetaModel::Init_InheritAttributes();
  354. // When set, this token allows for password reset
  355. MetaModel::Init_AddAttribute(new AttributeString("reset_pwd_token", array("allowed_values"=>null, "sql"=>"reset_pwd_token", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  356. // Display lists
  357. MetaModel::Init_SetZListItems('details', array('contactid', 'first_name', 'email', 'login', 'language', 'profile_list', 'allowed_org_list')); // Attributes to be displayed for the complete details
  358. MetaModel::Init_SetZListItems('list', array('finalclass', 'first_name', 'last_name', 'login')); // Attributes to be displayed for a list
  359. // Search criteria
  360. MetaModel::Init_SetZListItems('standard_search', array('login', 'contactid')); // Criteria of the std search form
  361. MetaModel::Init_SetZListItems('advanced_search', array('login', 'contactid')); // Criteria of the advanced search form
  362. }
  363. /**
  364. * Use with care!
  365. */
  366. public function SetPassword($sNewPassword)
  367. {
  368. }
  369. /**
  370. * The email recipient is the person who is allowed to regain control when the password gets lost
  371. * Throws an exception if the feature cannot be available
  372. */
  373. public function GetResetPasswordEmail()
  374. {
  375. if (!MetaModel::IsValidAttCode(get_class($this), 'contactid'))
  376. {
  377. throw new Exception(Dict::S('UI:ResetPwd-Error-NoContact'));
  378. }
  379. $iContactId = $this->Get('contactid');
  380. if ($iContactId == 0)
  381. {
  382. throw new Exception(Dict::S('UI:ResetPwd-Error-NoContact'));
  383. }
  384. $oContact = MetaModel::GetObject('Contact', $iContactId);
  385. // Determine the email attribute (the first one will be our choice)
  386. foreach (MetaModel::ListAttributeDefs(get_class($oContact)) as $sAttCode => $oAttDef)
  387. {
  388. if ($oAttDef instanceof AttributeEmailAddress)
  389. {
  390. $sEmailAttCode = $sAttCode;
  391. // we've got one, exit the loop
  392. break;
  393. }
  394. }
  395. if (!isset($sEmailAttCode))
  396. {
  397. throw new Exception(Dict::S('UI:ResetPwd-Error-NoEmailAtt'));
  398. }
  399. $sRes = trim($oContact->Get($sEmailAttCode));
  400. return $sRes;
  401. }
  402. }
  403. /**
  404. * Self register extension
  405. *
  406. * @package iTopORM
  407. */
  408. interface iSelfRegister
  409. {
  410. /**
  411. * Called when no user is found in iTop for the corresponding 'name'. This method
  412. * can create/synchronize the User in iTop with an external source (such as AD/LDAP) on the fly
  413. * @param string $sName The typed-in user name
  414. * @param string $sPassword The typed-in password
  415. * @param string $sLoginMode The login method used (cas|form|basic|url)
  416. * @param string $sAuthentication The authentication method used (any|internal|external)
  417. * @return bool true if the user is a valid one, false otherwise
  418. */
  419. public static function CheckCredentialsAndCreateUser($sName, $sPassword, $sLoginMode, $sAuthentication);
  420. /**
  421. * Called after the user has been authenticated and found in iTop. This method can
  422. * Update the user's definition on the fly (profiles...) to keep it in sync with an external source
  423. * @param User $oUser The user to update/synchronize
  424. * @param string $sLoginMode The login mode used (cas|form|basic|url)
  425. * @param string $sAuthentication The authentication method used
  426. * @return void
  427. */
  428. public static function UpdateUser(User $oUser, $sLoginMode, $sAuthentication);
  429. }
  430. /**
  431. * User management core API
  432. *
  433. * @package iTopORM
  434. */
  435. class UserRights
  436. {
  437. protected static $m_oAddOn;
  438. protected static $m_oUser;
  439. protected static $m_oRealUser;
  440. protected static $m_sSelfRegisterAddOn = null;
  441. public static function SelectModule($sModuleName)
  442. {
  443. if (!class_exists($sModuleName))
  444. {
  445. throw new CoreException("Could not select this module, '$sModuleName' in not a valid class name");
  446. return;
  447. }
  448. if (!is_subclass_of($sModuleName, 'UserRightsAddOnAPI'))
  449. {
  450. throw new CoreException("Could not select this module, the class '$sModuleName' is not derived from UserRightsAddOnAPI");
  451. return;
  452. }
  453. self::$m_oAddOn = new $sModuleName;
  454. self::$m_oAddOn->Init();
  455. self::$m_oUser = null;
  456. self::$m_oRealUser = null;
  457. }
  458. public static function SelectSelfRegister($sModuleName)
  459. {
  460. if (!class_exists($sModuleName))
  461. {
  462. throw new CoreException("Could not select the class, '$sModuleName' for self register, is not a valid class name");
  463. }
  464. self::$m_sSelfRegisterAddOn = $sModuleName;
  465. }
  466. public static function GetModuleInstance()
  467. {
  468. return self::$m_oAddOn;
  469. }
  470. // Installation: create the very first user
  471. public static function CreateAdministrator($sAdminUser, $sAdminPwd, $sLanguage = 'EN US')
  472. {
  473. $bRes = self::$m_oAddOn->CreateAdministrator($sAdminUser, $sAdminPwd, $sLanguage);
  474. self::FlushPrivileges(true /* reset admin cache */);
  475. return $bRes;
  476. }
  477. protected static function IsLoggedIn()
  478. {
  479. if (self::$m_oUser == null)
  480. {
  481. return false;
  482. }
  483. else
  484. {
  485. return true;
  486. }
  487. }
  488. public static function Login($sName, $sAuthentication = 'any')
  489. {
  490. $oUser = self::FindUser($sName, $sAuthentication);
  491. if (is_null($oUser))
  492. {
  493. return false;
  494. }
  495. self::$m_oUser = $oUser;
  496. Dict::SetUserLanguage(self::GetUserLanguage());
  497. return true;
  498. }
  499. public static function CheckCredentials($sName, $sPassword, $sLoginMode = 'form', $sAuthentication = 'any')
  500. {
  501. $oUser = self::FindUser($sName, $sAuthentication);
  502. if (is_null($oUser))
  503. {
  504. return self::CheckCredentialsAndCreateUser($sName, $sPassword, $sLoginMode, $sAuthentication);
  505. }
  506. if (!$oUser->CheckCredentials($sPassword))
  507. {
  508. return false;
  509. }
  510. self::UpdateUser($oUser, $sLoginMode, $sAuthentication);
  511. return true;
  512. }
  513. public static function CheckCredentialsAndCreateUser($sName, $sPassword, $sLoginMode, $sAuthentication)
  514. {
  515. if (self::$m_sSelfRegisterAddOn != null)
  516. {
  517. return call_user_func(array(self::$m_sSelfRegisterAddOn, 'CheckCredentialsAndCreateUser'), $sName, $sPassword, $sLoginMode, $sAuthentication);
  518. }
  519. }
  520. public static function UpdateUser($oUser, $sLoginMode, $sAuthentication)
  521. {
  522. if (self::$m_sSelfRegisterAddOn != null)
  523. {
  524. call_user_func(array(self::$m_sSelfRegisterAddOn, 'UpdateUser'), $oUser, $sLoginMode, $sAuthentication);
  525. }
  526. }
  527. public static function TrustWebServerContext()
  528. {
  529. if (!is_null(self::$m_oUser))
  530. {
  531. return self::$m_oUser->TrustWebServerContext();
  532. }
  533. else
  534. {
  535. return false;
  536. }
  537. }
  538. public static function CanChangePassword()
  539. {
  540. if (MetaModel::DBIsReadOnly())
  541. {
  542. return false;
  543. }
  544. if (!is_null(self::$m_oUser))
  545. {
  546. return self::$m_oUser->CanChangePassword();
  547. }
  548. else
  549. {
  550. return false;
  551. }
  552. }
  553. public static function ChangePassword($sOldPassword, $sNewPassword, $sName = '')
  554. {
  555. if (empty($sName))
  556. {
  557. $oUser = self::$m_oUser;
  558. }
  559. else
  560. {
  561. // find the id out of the login string
  562. $oUser = self::FindUser($sName);
  563. }
  564. if (is_null($oUser))
  565. {
  566. return false;
  567. }
  568. else
  569. {
  570. return $oUser->ChangePassword($sOldPassword, $sNewPassword);
  571. }
  572. }
  573. public static function Impersonate($sName, $sPassword)
  574. {
  575. if (!self::CheckLogin()) return false;
  576. $oUser = self::FindUser($sName);
  577. if (is_null($oUser))
  578. {
  579. return false;
  580. }
  581. if (!$oUser->CheckCredentials($sPassword))
  582. {
  583. return false;
  584. }
  585. self::$m_oRealUser = self::$m_oUser;
  586. self::$m_oUser = $oUser;
  587. Dict::SetUserLanguage(self::GetUserLanguage());
  588. return true;
  589. }
  590. public static function GetUser()
  591. {
  592. if (is_null(self::$m_oUser))
  593. {
  594. return '';
  595. }
  596. else
  597. {
  598. return self::$m_oUser->Get('login');
  599. }
  600. }
  601. public static function GetUserObject()
  602. {
  603. if (is_null(self::$m_oUser))
  604. {
  605. return null;
  606. }
  607. else
  608. {
  609. return self::$m_oUser;
  610. }
  611. }
  612. public static function GetUserLanguage()
  613. {
  614. if (is_null(self::$m_oUser))
  615. {
  616. return 'EN US';
  617. }
  618. else
  619. {
  620. return self::$m_oUser->Get('language');
  621. }
  622. }
  623. public static function GetUserId($sName = '')
  624. {
  625. if (empty($sName))
  626. {
  627. // return current user id
  628. if (is_null(self::$m_oUser))
  629. {
  630. return null;
  631. }
  632. return self::$m_oUser->GetKey();
  633. }
  634. else
  635. {
  636. // find the id out of the login string
  637. $oUser = self::$m_oAddOn->FindUser($sName);
  638. if (is_null($oUser))
  639. {
  640. return null;
  641. }
  642. return $oUser->GetKey();
  643. }
  644. }
  645. public static function GetContactId($sName = '')
  646. {
  647. if (empty($sName))
  648. {
  649. $oUser = self::$m_oUser;
  650. }
  651. else
  652. {
  653. $oUser = FindUser($sName);
  654. }
  655. if (is_null($oUser))
  656. {
  657. return '';
  658. }
  659. if (!MetaModel::IsValidAttCode(get_class($oUser), 'contactid'))
  660. {
  661. return '';
  662. }
  663. return $oUser->Get('contactid');
  664. }
  665. // Render the user name in best effort mode
  666. public static function GetUserFriendlyName($sName = '')
  667. {
  668. if (empty($sName))
  669. {
  670. $oUser = self::$m_oUser;
  671. }
  672. else
  673. {
  674. $oUser = FindUser($sName);
  675. }
  676. if (is_null($oUser))
  677. {
  678. return '';
  679. }
  680. return $oUser->GetFriendlyName();
  681. }
  682. public static function IsImpersonated()
  683. {
  684. if (is_null(self::$m_oRealUser))
  685. {
  686. return false;
  687. }
  688. return true;
  689. }
  690. public static function GetRealUser()
  691. {
  692. if (is_null(self::$m_oRealUser))
  693. {
  694. return '';
  695. }
  696. return self::$m_oRealUser->Get('login');
  697. }
  698. public static function GetRealUserId()
  699. {
  700. if (is_null(self::$m_oRealUser))
  701. {
  702. return '';
  703. }
  704. return self::$m_oRealUser->GetKey();
  705. }
  706. public static function GetRealUserFriendlyName()
  707. {
  708. if (is_null(self::$m_oRealUser))
  709. {
  710. return '';
  711. }
  712. return self::$m_oRealUser->GetFriendlyName();
  713. }
  714. protected static function CheckLogin()
  715. {
  716. if (!self::IsLoggedIn())
  717. {
  718. //throw new UserRightException('No user logged in', array());
  719. return false;
  720. }
  721. return true;
  722. }
  723. public static function GetSelectFilter($sClass, $aSettings = array())
  724. {
  725. // When initializing, we need to let everything pass trough
  726. if (!self::CheckLogin()) return true;
  727. if (self::IsAdministrator()) return true;
  728. if (MetaModel::HasCategory($sClass, 'bizmodel'))
  729. {
  730. return self::$m_oAddOn->GetSelectFilter(self::$m_oUser, $sClass, $aSettings);
  731. }
  732. else
  733. {
  734. return true;
  735. }
  736. }
  737. public static function IsActionAllowed($sClass, $iActionCode, /*dbObjectSet*/ $oInstanceSet = null, $oUser = null)
  738. {
  739. // When initializing, we need to let everything pass trough
  740. if (!self::CheckLogin()) return true;
  741. if (MetaModel::DBIsReadOnly())
  742. {
  743. if ($iActionCode == UR_ACTION_CREATE) return false;
  744. if ($iActionCode == UR_ACTION_MODIFY) return false;
  745. if ($iActionCode == UR_ACTION_BULK_MODIFY) return false;
  746. if ($iActionCode == UR_ACTION_DELETE) return false;
  747. if ($iActionCode == UR_ACTION_BULK_DELETE) return false;
  748. }
  749. $aPredefinedObjects = call_user_func(array($sClass, 'GetPredefinedObjects'));
  750. if ($aPredefinedObjects != null)
  751. {
  752. // As opposed to the read-only DB, modifying an object is allowed
  753. // (the constant columns will be marked as read-only)
  754. //
  755. if ($iActionCode == UR_ACTION_CREATE) return false;
  756. if ($iActionCode == UR_ACTION_DELETE) return false;
  757. if ($iActionCode == UR_ACTION_BULK_DELETE) return false;
  758. }
  759. if (self::IsAdministrator($oUser)) return true;
  760. if (MetaModel::HasCategory($sClass, 'bizmodel'))
  761. {
  762. if (is_null($oUser))
  763. {
  764. $oUser = self::$m_oUser;
  765. }
  766. if ($iActionCode == UR_ACTION_CREATE)
  767. {
  768. // The addons currently DO NOT handle the case "CREATE"
  769. // Therefore it is considered to be equivalent to "MODIFY"
  770. $iActionCode = UR_ACTION_MODIFY;
  771. }
  772. return self::$m_oAddOn->IsActionAllowed($oUser, $sClass, $iActionCode, $oInstanceSet);
  773. }
  774. elseif(($iActionCode == UR_ACTION_READ) && MetaModel::HasCategory($sClass, 'view_in_gui'))
  775. {
  776. return true;
  777. }
  778. else
  779. {
  780. // Other classes could be edited/listed by the administrators
  781. return false;
  782. }
  783. }
  784. public static function IsStimulusAllowed($sClass, $sStimulusCode, /*dbObjectSet*/ $oInstanceSet = null, $oUser = null)
  785. {
  786. // When initializing, we need to let everything pass trough
  787. if (!self::CheckLogin()) return true;
  788. if (MetaModel::DBIsReadOnly())
  789. {
  790. return false;
  791. }
  792. if (self::IsAdministrator($oUser)) return true;
  793. if (MetaModel::HasCategory($sClass, 'bizmodel'))
  794. {
  795. if (is_null($oUser))
  796. {
  797. $oUser = self::$m_oUser;
  798. }
  799. return self::$m_oAddOn->IsStimulusAllowed($oUser, $sClass, $sStimulusCode, $oInstanceSet);
  800. }
  801. else
  802. {
  803. // Other classes could be edited/listed by the administrators
  804. return false;
  805. }
  806. }
  807. public static function IsActionAllowedOnAttribute($sClass, $sAttCode, $iActionCode, /*dbObjectSet*/ $oInstanceSet = null, $oUser = null)
  808. {
  809. // When initializing, we need to let everything pass trough
  810. if (!self::CheckLogin()) return true;
  811. if (MetaModel::DBIsReadOnly())
  812. {
  813. if ($iActionCode == UR_ACTION_MODIFY) return false;
  814. if ($iActionCode == UR_ACTION_DELETE) return false;
  815. if ($iActionCode == UR_ACTION_BULK_MODIFY) return false;
  816. if ($iActionCode == UR_ACTION_BULK_DELETE) return false;
  817. }
  818. if (self::IsAdministrator($oUser)) return true;
  819. // this module is forbidden for non admins
  820. if (MetaModel::HasCategory($sClass, 'addon/userrights')) return false;
  821. // the rest is allowed (#@# to be improved)
  822. if (!MetaModel::HasCategory($sClass, 'bizmodel')) return true;
  823. if (is_null($oUser))
  824. {
  825. $oUser = self::$m_oUser;
  826. }
  827. return self::$m_oAddOn->IsActionAllowedOnAttribute($oUser, $sClass, $sAttCode, $iActionCode, $oInstanceSet);
  828. }
  829. static $m_aAdmins = array();
  830. public static function IsAdministrator($oUser = null)
  831. {
  832. if (!self::CheckLogin()) return false;
  833. if (is_null($oUser))
  834. {
  835. $oUser = self::$m_oUser;
  836. }
  837. $iUser = $oUser->GetKey();
  838. if (!isset(self::$m_aAdmins[$iUser]))
  839. {
  840. self::$m_aAdmins[$iUser] = self::$m_oAddOn->IsAdministrator($oUser);
  841. }
  842. return self::$m_aAdmins[$iUser];
  843. }
  844. static $m_aPortalUsers = array();
  845. public static function IsPortalUser($oUser = null)
  846. {
  847. if (!self::CheckLogin()) return false;
  848. if (is_null($oUser))
  849. {
  850. $oUser = self::$m_oUser;
  851. }
  852. $iUser = $oUser->GetKey();
  853. if (!isset(self::$m_aPortalUsers[$iUser]))
  854. {
  855. self::$m_aPortalUsers[$iUser] = self::$m_oAddOn->IsPortalUser($oUser);
  856. }
  857. return self::$m_aPortalUsers[$iUser];
  858. }
  859. /**
  860. * Reset cached data
  861. * @param Bool Reset admin cache as well
  862. * @return void
  863. */
  864. // Reset cached data
  865. //
  866. public static function FlushPrivileges($bResetAdminCache = false)
  867. {
  868. if ($bResetAdminCache)
  869. {
  870. self::$m_aAdmins = array();
  871. }
  872. return self::$m_oAddOn->FlushPrivileges();
  873. }
  874. static $m_aCacheUsers;
  875. /**
  876. * Find a user based on its login and its type of authentication
  877. * @param string $sLogin Login/identifier of the user
  878. * @param string $sAuthentication Type of authentication used: internal|external|any
  879. * @return User The found user or null
  880. */
  881. protected static function FindUser($sLogin, $sAuthentication = 'any')
  882. {
  883. if ($sAuthentication == 'any')
  884. {
  885. $oUser = self::FindUser($sLogin, 'internal');
  886. if ($oUser == null)
  887. {
  888. $oUser = self::FindUser($sLogin, 'external');
  889. }
  890. }
  891. else
  892. {
  893. if (!isset(self::$m_aCacheUsers))
  894. {
  895. self::$m_aCacheUsers = array('internal' => array(), 'external' => array());
  896. }
  897. if (!isset(self::$m_aCacheUsers[$sAuthentication][$sLogin]))
  898. {
  899. switch($sAuthentication)
  900. {
  901. case 'external':
  902. $sBaseClass = 'UserExternal';
  903. break;
  904. case 'internal':
  905. $sBaseClass = 'UserInternal';
  906. break;
  907. default:
  908. echo "<p>sAuthentication = $sAuthentication</p>\n";
  909. assert(false); // should never happen
  910. }
  911. $oSearch = DBObjectSearch::FromOQL("SELECT $sBaseClass WHERE login = :login");
  912. $oSet = new DBObjectSet($oSearch, array(), array('login' => $sLogin));
  913. $oUser = $oSet->fetch();
  914. self::$m_aCacheUsers[$sAuthentication][$sLogin] = $oUser;
  915. }
  916. $oUser = self::$m_aCacheUsers[$sAuthentication][$sLogin];
  917. }
  918. return $oUser;
  919. }
  920. public static function MakeSelectFilter($sClass, $aAllowedOrgs, $aSettings = array(), $sAttCode = null)
  921. {
  922. return self::$m_oAddOn->MakeSelectFilter($sClass, $aAllowedOrgs, $aSettings, $sAttCode);
  923. }
  924. }
  925. /**
  926. * Helper class to get the number/list of items for which a given action is allowed/possible
  927. */
  928. class ActionChecker
  929. {
  930. var $oFilter;
  931. var $iActionCode;
  932. var $iAllowedCount = null;
  933. var $aAllowedIDs = null;
  934. public function __construct(DBObjectSearch $oFilter, $iActionCode)
  935. {
  936. $this->oFilter = $oFilter;
  937. $this->iActionCode = $iActionCode;
  938. $this->iAllowedCount = null;
  939. $this->aAllowedIDs = null;
  940. }
  941. /**
  942. * returns the number of objects for which the action is allowed
  943. * @return integer The number of "allowed" objects 0..N
  944. */
  945. public function GetAllowedCount()
  946. {
  947. if ($this->iAllowedCount == null) $this->CheckObjects();
  948. return $this->iAllowedCount;
  949. }
  950. /**
  951. * If IsAllowed returned UR_ALLOWED_DEPENDS, this methods returns
  952. * an array of ObjKey => Status (true|false)
  953. * @return array
  954. */
  955. public function GetAllowedIDs()
  956. {
  957. if ($this->aAllowedIDs == null) $this->IsAllowed();
  958. return $this->aAllowedIDs;
  959. }
  960. /**
  961. * Check if the speficied stimulus is allowed for the set of objects
  962. * @return UR_ALLOWED_YES, UR_ALLOWED_NO or UR_ALLOWED_DEPENDS
  963. */
  964. public function IsAllowed()
  965. {
  966. $sClass = $this->oFilter->GetClass();
  967. $oSet = new DBObjectSet($this->oFilter);
  968. $iActionAllowed = UserRights::IsActionAllowed($sClass, $this->iActionCode, $oSet);
  969. if ($iActionAllowed == UR_ALLOWED_DEPENDS)
  970. {
  971. // Check for each object if the action is allowed or not
  972. $this->aAllowedIDs = array();
  973. $oSet->Rewind();
  974. $this->iAllowedCount = 0;
  975. while($oObj = $oSet->Fetch())
  976. {
  977. $oObjSet = DBObjectSet::FromArray($sClass, array($oObj));
  978. if (UserRights::IsActionAllowed($sClass, $this->iActionCode, $oObjSet) == UR_ALLOWED_NO)
  979. {
  980. $this->aAllowedIDs[$oObj->GetKey()] = false;
  981. }
  982. else
  983. {
  984. // Assume UR_ALLOWED_YES, since there is just one object !
  985. $this->aAllowedIDs[$oObj->GetKey()] = true;
  986. $this->iAllowedCount++;
  987. }
  988. }
  989. }
  990. else if ($iActionAllowed == UR_ALLOWED_YES)
  991. {
  992. $this->iAllowedCount = $oSet->Count();
  993. $this->aAllowedIDs = array(); // Optimization: not filled when Ok for all objects
  994. }
  995. else // UR_ALLOWED_NO
  996. {
  997. $this->iAllowedCount = 0;
  998. $this->aAllowedIDs = array();
  999. }
  1000. return $iActionAllowed;
  1001. }
  1002. }
  1003. /**
  1004. * Helper class to get the number/list of items for which a given stimulus can be applied (allowed & possible)
  1005. */
  1006. class StimulusChecker extends ActionChecker
  1007. {
  1008. var $sState = null;
  1009. public function __construct(DBObjectSearch $oFilter, $sState, $iStimulusCode)
  1010. {
  1011. parent::__construct($oFilter, $iStimulusCode);
  1012. $this->sState = $sState;
  1013. }
  1014. /**
  1015. * Check if the speficied stimulus is allowed for the set of objects
  1016. * @return UR_ALLOWED_YES, UR_ALLOWED_NO or UR_ALLOWED_DEPENDS
  1017. */
  1018. public function IsAllowed()
  1019. {
  1020. $sClass = $this->oFilter->GetClass();
  1021. if (MetaModel::IsAbstract($sClass)) return UR_ALLOWED_NO; // Safeguard, not implemented if the base class of the set is abstract !
  1022. $oSet = new DBObjectSet($this->oFilter);
  1023. $iActionAllowed = UserRights::IsStimulusAllowed($sClass, $this->iActionCode, $oSet);
  1024. if ($iActionAllowed == UR_ALLOWED_NO)
  1025. {
  1026. $this->iAllowedCount = 0;
  1027. $this->aAllowedIDs = array();
  1028. }
  1029. else // Even if UR_ALLOWED_YES, we need to check if each object is in the appropriate state
  1030. {
  1031. // Hmmm, may not be needed right now because we limit the "multiple" action to object in
  1032. // the same state... may be useful later on if we want to extend this behavior...
  1033. // Check for each object if the action is allowed or not
  1034. $this->aAllowedIDs = array();
  1035. $oSet->Rewind();
  1036. $iAllowedCount = 0;
  1037. $iActionAllowed = UR_ALLOWED_DEPENDS;
  1038. while($oObj = $oSet->Fetch())
  1039. {
  1040. $aTransitions = $oObj->EnumTransitions();
  1041. if (array_key_exists($this->iActionCode, $aTransitions))
  1042. {
  1043. // Temporary optimization possible: since the current implementation
  1044. // of IsActionAllowed does not perform a 'per instance' check, we could
  1045. // skip this second validation phase and assume it would return UR_ALLOWED_YES
  1046. $oObjSet = DBObjectSet::FromArray($sClass, array($oObj));
  1047. if (!UserRights::IsStimulusAllowed($sClass, $this->iActionCode, $oObjSet))
  1048. {
  1049. $this->aAllowedIDs[$oObj->GetKey()] = false;
  1050. }
  1051. else
  1052. {
  1053. // Assume UR_ALLOWED_YES, since there is just one object !
  1054. $this->aAllowedIDs[$oObj->GetKey()] = true;
  1055. $this->iState = $oObj->GetState();
  1056. $this->iAllowedCount++;
  1057. }
  1058. }
  1059. else
  1060. {
  1061. $this->aAllowedIDs[$oObj->GetKey()] = false;
  1062. }
  1063. }
  1064. }
  1065. if ($this->iAllowedCount == $oSet->Count())
  1066. {
  1067. $iActionAllowed = UR_ALLOWED_YES;
  1068. }
  1069. if ($this->iAllowedCount == 0)
  1070. {
  1071. $iActionAllowed = UR_ALLOWED_NO;
  1072. }
  1073. return $iActionAllowed;
  1074. }
  1075. public function GetState()
  1076. {
  1077. return $this->iState;
  1078. }
  1079. }
  1080. /**
  1081. * Self-register extension to allow the automatic creation & update of CAS users
  1082. *
  1083. * @package iTopORM
  1084. *
  1085. */
  1086. class CAS_SelfRegister implements iSelfRegister
  1087. {
  1088. /**
  1089. * Called when no user is found in iTop for the corresponding 'name'. This method
  1090. * can create/synchronize the User in iTop with an external source (such as AD/LDAP) on the fly
  1091. * @param string $sName The CAS authenticated user name
  1092. * @param string $sPassword Ignored
  1093. * @param string $sLoginMode The login mode used (cas|form|basic|url)
  1094. * @param string $sAuthentication The authentication method used
  1095. * @return bool true if the user is a valid one, false otherwise
  1096. */
  1097. public static function CheckCredentialsAndCreateUser($sName, $sPassword, $sLoginMode, $sAuthentication)
  1098. {
  1099. $bOk = true;
  1100. if ($sLoginMode != 'cas') return false; // Must be authenticated via CAS
  1101. $sCASMemberships = MetaModel::GetConfig()->Get('cas_memberof');
  1102. $bFound = false;
  1103. if (!empty($sCASMemberships))
  1104. {
  1105. if (phpCAS::hasAttribute('memberOf'))
  1106. {
  1107. // A list of groups is specified, the user must a be member of (at least) one of them to pass
  1108. $aCASMemberships = array();
  1109. $aTmp = explode(';', $sCASMemberships);
  1110. setlocale(LC_ALL, "en_US.utf8"); // !!! WARNING: this is needed to have the iconv //TRANSLIT working fine below !!!
  1111. foreach($aTmp as $sGroupName)
  1112. {
  1113. $aCASMemberships[] = trim(iconv('UTF-8', 'ASCII//TRANSLIT', $sGroupName)); // Just in case remove accents and spaces...
  1114. }
  1115. $aMemberOf = phpCAS::getAttribute('memberOf');
  1116. if (!is_array($aMemberOf)) $aMemberOf = array($aMemberOf); // Just one entry, turn it into an array
  1117. $aFilteredGroupNames = array();
  1118. foreach($aMemberOf as $sGroupName)
  1119. {
  1120. phpCAS::log("Info: user if a member of the group: ".$sGroupName);
  1121. $sGroupName = trim(iconv('UTF-8', 'ASCII//TRANSLIT', $sGroupName)); // Remove accents and spaces as well
  1122. $aFilteredGroupNames[] = $sGroupName;
  1123. $bIsMember = false;
  1124. foreach($aCASMemberships as $sCASPattern)
  1125. {
  1126. if (self::IsPattern($sCASPattern))
  1127. {
  1128. if (preg_match($sCASPattern, $sGroupName))
  1129. {
  1130. $bIsMember = true;
  1131. break;
  1132. }
  1133. }
  1134. else if ($sPattern == $sGroupName)
  1135. {
  1136. $bIsMember = true;
  1137. break;
  1138. }
  1139. }
  1140. if ($bIsMember)
  1141. {
  1142. $bCASUserSynchro = MetaModel::GetConfig()->Get('cas_user_synchro');
  1143. if ($bCASUserSynchro)
  1144. {
  1145. // If needed create a new user for this email/profile
  1146. phpCAS::log('Info: cas_user_synchro is ON');
  1147. $bOk = self::CreateCASUser(phpCAS::getUser(), $aMemberOf);
  1148. if($bOk)
  1149. {
  1150. $bFound = true;
  1151. }
  1152. else
  1153. {
  1154. phpCAS::log("User ".phpCAS::getUser()." cannot be created in iTop. Logging off...");
  1155. }
  1156. }
  1157. else
  1158. {
  1159. phpCAS::log('Info: cas_user_synchro is OFF');
  1160. $bFound = true;
  1161. }
  1162. break;
  1163. }
  1164. }
  1165. if($bOk && !$bFound)
  1166. {
  1167. phpCAS::log("User ".phpCAS::getUser().", none of his/her groups (".implode('; ', $aFilteredGroupNames).") match any of the required groups: ".implode('; ', $aCASMemberships));
  1168. }
  1169. }
  1170. else
  1171. {
  1172. // Too bad, the user is not part of any of the group => not allowed
  1173. phpCAS::log("No 'memberOf' attribute found for user ".phpCAS::getUser().". Are you using the SAML protocol (S1) ?");
  1174. }
  1175. }
  1176. else
  1177. {
  1178. // No membership required, anybody will pass
  1179. $bFound = true;
  1180. }
  1181. if (!$bFound)
  1182. {
  1183. // The user is not part of the allowed groups, => log out
  1184. $sUrl = utils::GetAbsoluteUrlAppRoot().'pages/UI.php';
  1185. $sCASLogoutUrl = MetaModel::GetConfig()->Get('cas_logout_redirect_service');
  1186. if (empty($sCASLogoutUrl))
  1187. {
  1188. $sCASLogoutUrl = $sUrl;
  1189. }
  1190. phpCAS::logoutWithRedirectService($sCASLogoutUrl); // Redirects to the CAS logout page
  1191. // Will never return !
  1192. }
  1193. return $bFound;
  1194. }
  1195. /**
  1196. * Called after the user has been authenticated and found in iTop. This method can
  1197. * Update the user's definition (profiles...) on the fly to keep it in sync with an external source
  1198. * @param User $oUser The user to update/synchronize
  1199. * @param string $sLoginMode The login mode used (cas|form|basic|url)
  1200. * @param string $sAuthentication The authentication method used
  1201. * @return void
  1202. */
  1203. public static function UpdateUser(User $oUser, $sLoginMode, $sAuthentication)
  1204. {
  1205. $bCASUpdateProfiles = MetaModel::GetConfig()->Get('cas_update_profiles');
  1206. if (($sLoginMode == 'cas') && $bCASUpdateProfiles && (phpCAS::hasAttribute('memberOf')))
  1207. {
  1208. $aMemberOf = phpCAS::getAttribute('memberOf');
  1209. if (!is_array($aMemberOf)) $aMemberOf = array($aMemberOf); // Just one entry, turn it into an array
  1210. return self::SetProfilesFromCAS($oUser, $aMemberOf);
  1211. }
  1212. // No groups defined in CAS or not CAS at all: do nothing...
  1213. return true;
  1214. }
  1215. /**
  1216. * Helper method to create a CAS based user
  1217. * @param string $sEmail
  1218. * @param array $aGroups
  1219. * @return bool true on success, false otherwise
  1220. */
  1221. protected static function CreateCASUser($sEmail, $aGroups)
  1222. {
  1223. if (!MetaModel::IsValidClass('URP_Profiles'))
  1224. {
  1225. phpCAS::log("URP_Profiles is not a valid class. Automatic creation of Users is not supported in this context, sorry.");
  1226. return false;
  1227. }
  1228. $oUser = MetaModel::GetObjectByName('UserExternal', $sEmail, false);
  1229. if ($oUser == null)
  1230. {
  1231. // Create the user, link it to a contact
  1232. phpCAS::log("Info: the user '$sEmail' does not exist. A new UserExternal will be created.");
  1233. $oSearch = new DBObjectSearch('Person');
  1234. $oSearch->AddCondition('email', $sEmail);
  1235. $oSet = new DBObjectSet($oSearch);
  1236. $iContactId = 0;
  1237. switch($oSet->Count())
  1238. {
  1239. case 0:
  1240. phpCAS::log("Error: found no contact with the email: '$sEmail'. Cannot create the user in iTop.");
  1241. return false;
  1242. case 1:
  1243. $oContact = $oSet->Fetch();
  1244. $iContactId = $oContact->GetKey();
  1245. phpCAS::log("Info: Found 1 contact '".$oContact->GetName()."' (id=$iContactId) corresponding to the email '$sEmail'.");
  1246. break;
  1247. default:
  1248. phpCAS::log("Error: ".$oSet->Count()." contacts have the same email: '$sEmail'. Cannot create a user for this email.");
  1249. return false;
  1250. }
  1251. $oUser = new UserExternal();
  1252. $oUser->Set('login', $sEmail);
  1253. $oUser->Set('contactid', $iContactId);
  1254. $oUser->Set('language', MetaModel::GetConfig()->GetDefaultLanguage());
  1255. }
  1256. else
  1257. {
  1258. phpCAS::log("Info: the user '$sEmail' already exists (id=".$oUser->GetKey().").");
  1259. }
  1260. // Now synchronize the profiles
  1261. if (!self::SetProfilesFromCAS($oUser, $aGroups))
  1262. {
  1263. return false;
  1264. }
  1265. else
  1266. {
  1267. if ($oUser->IsNew() || $oUser->IsModified())
  1268. {
  1269. $oMyChange = MetaModel::NewObject("CMDBChange");
  1270. $oMyChange->Set("date", time());
  1271. $oMyChange->Set("userinfo", 'CAS/LDAP Synchro');
  1272. $oMyChange->DBInsert();
  1273. if ($oUser->IsNew())
  1274. {
  1275. $oUser->DBInsertTracked($oMyChange);
  1276. }
  1277. else
  1278. {
  1279. $oUser->DBUpdateTracked($oMyChange);
  1280. }
  1281. }
  1282. return true;
  1283. }
  1284. }
  1285. protected static function SetProfilesFromCAS($oUser, $aGroups)
  1286. {
  1287. if (!MetaModel::IsValidClass('URP_Profiles'))
  1288. {
  1289. phpCAS::log("URP_Profiles is not a valid class. Automatic creation of Users is not supported in this context, sorry.");
  1290. return false;
  1291. }
  1292. // read all the existing profiles
  1293. $oProfilesSearch = new DBObjectSearch('URP_Profiles');
  1294. $oProfilesSet = new DBObjectSet($oProfilesSearch);
  1295. $aAllProfiles = array();
  1296. while($oProfile = $oProfilesSet->Fetch())
  1297. {
  1298. $aAllProfiles[strtolower($oProfile->GetName())] = $oProfile->GetKey();
  1299. }
  1300. // Translate the CAS/LDAP group names into iTop profile names
  1301. $aProfiles = array();
  1302. $sPattern = MetaModel::GetConfig()->Get('cas_profile_pattern');
  1303. foreach($aGroups as $sGroupName)
  1304. {
  1305. if (preg_match($sPattern, $sGroupName, $aMatches))
  1306. {
  1307. if (array_key_exists(strtolower($aMatches[1]), $aAllProfiles))
  1308. {
  1309. $aProfiles[] = $aAllProfiles[strtolower($aMatches[1])];
  1310. phpCAS::log("Info: Adding the profile '{$aMatches[1]}' from CAS.");
  1311. }
  1312. else
  1313. {
  1314. phpCAS::log("Warning: {$aMatches[1]} is not a valid iTop profile (extracted from group name: '$sGroupName'). Ignored.");
  1315. }
  1316. }
  1317. else
  1318. {
  1319. phpCAS::log("Info: The CAS group '$sGroupName' does not seem to match an iTop pattern. Ignored.");
  1320. }
  1321. }
  1322. if (count($aProfiles) == 0)
  1323. {
  1324. phpCAS::log("Info: The user '".$oUser->GetName()."' has no profiles retrieved from CAS. Default profile(s) will be used.");
  1325. // Second attempt: check if there is/are valid default profile(s)
  1326. $sCASDefaultProfiles = MetaModel::GetConfig()->Get('cas_default_profiles');
  1327. $aCASDefaultProfiles = explode(';', $sCASDefaultProfiles);
  1328. foreach($aCASDefaultProfiles as $sDefaultProfileName)
  1329. {
  1330. if (array_key_exists(strtolower($sDefaultProfileName), $aAllProfiles))
  1331. {
  1332. $aProfiles[] = $aAllProfiles[strtolower($sDefaultProfileName)];
  1333. phpCAS::log("Info: Adding the default profile '".$aAllProfiles[strtolower($sDefaultProfileName)]."' from CAS.");
  1334. }
  1335. else
  1336. {
  1337. phpCAS::log("Warning: the default profile {$sDefaultProfileName} is not a valid iTop profile. Ignored.");
  1338. }
  1339. }
  1340. if (count($aProfiles) == 0)
  1341. {
  1342. phpCAS::log("Error: The user '".$oUser->GetName()."' has no profiles in iTop, and therefore cannot be created.");
  1343. return false;
  1344. }
  1345. }
  1346. // Now synchronize the profiles
  1347. $oProfilesSet = DBObjectSet::FromScratch('URP_UserProfile');
  1348. foreach($aProfiles as $iProfileId)
  1349. {
  1350. $oLink = new URP_UserProfile();
  1351. $oLink->Set('profileid', $iProfileId);
  1352. $oLink->Set('reason', 'CAS/LDAP Synchro');
  1353. $oProfilesSet->AddObject($oLink);
  1354. }
  1355. $oUser->Set('profile_list', $oProfilesSet);
  1356. phpCAS::log("Info: the user '".$oUser->GetName()."' (id=".$oUser->GetKey().") now has the following profiles: '".implode("', '", $aProfiles)."'.");
  1357. if ($oUser->IsModified())
  1358. {
  1359. $oMyChange = MetaModel::NewObject("CMDBChange");
  1360. $oMyChange->Set("date", time());
  1361. $oMyChange->Set("userinfo", 'CAS/LDAP Synchro');
  1362. $oMyChange->DBInsert();
  1363. if ($oUser->IsNew())
  1364. {
  1365. $oUser->DBInsertTracked($oMyChange);
  1366. }
  1367. else
  1368. {
  1369. $oUser->DBUpdateTracked($oMyChange);
  1370. }
  1371. }
  1372. return true;
  1373. }
  1374. /**
  1375. * Helper function to check if the supplied string is a litteral string or a regular expression pattern
  1376. * @param string $sCASPattern
  1377. * @return bool True if it's a regular expression pattern, false otherwise
  1378. */
  1379. protected static function IsPattern($sCASPattern)
  1380. {
  1381. if ((substr($sCASPattern, 0, 1) == '/') && (substr($sCASPattern, -1) == '/'))
  1382. {
  1383. // the string is enclosed by slashes, let's assume it's a pattern
  1384. return true;
  1385. }
  1386. else
  1387. {
  1388. return false;
  1389. }
  1390. }
  1391. }
  1392. // By default enable the 'CAS_SelfRegister' defined above
  1393. UserRights::SelectSelfRegister('CAS_SelfRegister');
  1394. ?>