userrights.class.inc.php 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517
  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. }
  307. /**
  308. * Abstract class for all types of "internal" authentication i.e. users
  309. * for which the application is supplied a login and a password opposed
  310. * to "external" users for whom the authentication is performed outside
  311. * of the application (by the web server for example).
  312. * Note that "internal" users do not necessary correspond to a local authentication
  313. * they may be authenticated by a remote system, like in authent-ldap.
  314. */
  315. abstract class UserInternal extends User
  316. {
  317. // Nothing special, just a base class to categorize this type of authenticated users
  318. public static function Init()
  319. {
  320. $aParams = array
  321. (
  322. "category" => "core",
  323. "key_type" => "autoincrement",
  324. "name_attcode" => "login",
  325. "state_attcode" => "",
  326. "reconc_keys" => array('login'),
  327. "db_table" => "priv_internaluser",
  328. "db_key_field" => "id",
  329. "db_finalclass_field" => "",
  330. );
  331. MetaModel::Init_Params($aParams);
  332. MetaModel::Init_InheritAttributes();
  333. // When set, this token allows for password reset
  334. 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())));
  335. // Display lists
  336. MetaModel::Init_SetZListItems('details', array('contactid', 'first_name', 'email', 'login', 'language', 'profile_list', 'allowed_org_list')); // Attributes to be displayed for the complete details
  337. MetaModel::Init_SetZListItems('list', array('finalclass', 'first_name', 'last_name', 'login')); // Attributes to be displayed for a list
  338. // Search criteria
  339. MetaModel::Init_SetZListItems('standard_search', array('login', 'contactid')); // Criteria of the std search form
  340. MetaModel::Init_SetZListItems('advanced_search', array('login', 'contactid')); // Criteria of the advanced search form
  341. }
  342. /**
  343. * Use with care!
  344. */
  345. public function SetPassword($sNewPassword)
  346. {
  347. }
  348. /**
  349. * The email recipient is the person who is allowed to regain control when the password gets lost
  350. * Throws an exception if the feature cannot be available
  351. */
  352. public function GetResetPasswordEmail()
  353. {
  354. if (!MetaModel::IsValidAttCode(get_class($this), 'contactid'))
  355. {
  356. throw new Exception(Dict::S('UI:ResetPwd-Error-NoContact'));
  357. }
  358. $iContactId = $this->Get('contactid');
  359. if ($iContactId == 0)
  360. {
  361. throw new Exception(Dict::S('UI:ResetPwd-Error-NoContact'));
  362. }
  363. $oContact = MetaModel::GetObject('Contact', $iContactId);
  364. // Determine the email attribute (the first one will be our choice)
  365. foreach (MetaModel::ListAttributeDefs(get_class($oContact)) as $sAttCode => $oAttDef)
  366. {
  367. if ($oAttDef instanceof AttributeEmailAddress)
  368. {
  369. $sEmailAttCode = $sAttCode;
  370. // we've got one, exit the loop
  371. break;
  372. }
  373. }
  374. if (!isset($sEmailAttCode))
  375. {
  376. throw new Exception(Dict::S('UI:ResetPwd-Error-NoEmailAtt'));
  377. }
  378. $sRes = trim($oContact->Get($sEmailAttCode));
  379. return $sRes;
  380. }
  381. }
  382. /**
  383. * Self register extension
  384. *
  385. * @package iTopORM
  386. */
  387. interface iSelfRegister
  388. {
  389. /**
  390. * Called when no user is found in iTop for the corresponding 'name'. This method
  391. * can create/synchronize the User in iTop with an external source (such as AD/LDAP) on the fly
  392. * @param string $sName The typed-in user name
  393. * @param string $sPassword The typed-in password
  394. * @param string $sLoginMode The login method used (cas|form|basic|url)
  395. * @param string $sAuthentication The authentication method used (any|internal|external)
  396. * @return bool true if the user is a valid one, false otherwise
  397. */
  398. public static function CheckCredentialsAndCreateUser($sName, $sPassword, $sLoginMode, $sAuthentication);
  399. /**
  400. * Called after the user has been authenticated and found in iTop. This method can
  401. * Update the user's definition on the fly (profiles...) to keep it in sync with an external source
  402. * @param User $oUser The user to update/synchronize
  403. * @param string $sLoginMode The login mode used (cas|form|basic|url)
  404. * @param string $sAuthentication The authentication method used
  405. * @return void
  406. */
  407. public static function UpdateUser(User $oUser, $sLoginMode, $sAuthentication);
  408. }
  409. /**
  410. * User management core API
  411. *
  412. * @package iTopORM
  413. */
  414. class UserRights
  415. {
  416. protected static $m_oAddOn;
  417. protected static $m_oUser;
  418. protected static $m_oRealUser;
  419. protected static $m_sSelfRegisterAddOn = null;
  420. public static function SelectModule($sModuleName)
  421. {
  422. if (!class_exists($sModuleName))
  423. {
  424. throw new CoreException("Could not select this module, '$sModuleName' in not a valid class name");
  425. return;
  426. }
  427. if (!is_subclass_of($sModuleName, 'UserRightsAddOnAPI'))
  428. {
  429. throw new CoreException("Could not select this module, the class '$sModuleName' is not derived from UserRightsAddOnAPI");
  430. return;
  431. }
  432. self::$m_oAddOn = new $sModuleName;
  433. self::$m_oAddOn->Init();
  434. self::$m_oUser = null;
  435. self::$m_oRealUser = null;
  436. }
  437. public static function SelectSelfRegister($sModuleName)
  438. {
  439. if (!class_exists($sModuleName))
  440. {
  441. throw new CoreException("Could not select the class, '$sModuleName' for self register, is not a valid class name");
  442. }
  443. self::$m_sSelfRegisterAddOn = $sModuleName;
  444. }
  445. public static function GetModuleInstance()
  446. {
  447. return self::$m_oAddOn;
  448. }
  449. // Installation: create the very first user
  450. public static function CreateAdministrator($sAdminUser, $sAdminPwd, $sLanguage = 'EN US')
  451. {
  452. $bRes = self::$m_oAddOn->CreateAdministrator($sAdminUser, $sAdminPwd, $sLanguage);
  453. self::FlushPrivileges(true /* reset admin cache */);
  454. return $bRes;
  455. }
  456. protected static function IsLoggedIn()
  457. {
  458. if (self::$m_oUser == null)
  459. {
  460. return false;
  461. }
  462. else
  463. {
  464. return true;
  465. }
  466. }
  467. public static function Login($sName, $sAuthentication = 'any')
  468. {
  469. $oUser = self::FindUser($sName, $sAuthentication);
  470. if (is_null($oUser))
  471. {
  472. return false;
  473. }
  474. self::$m_oUser = $oUser;
  475. Dict::SetUserLanguage(self::GetUserLanguage());
  476. return true;
  477. }
  478. public static function CheckCredentials($sName, $sPassword, $sLoginMode = 'form', $sAuthentication = 'any')
  479. {
  480. $oUser = self::FindUser($sName, $sAuthentication);
  481. if (is_null($oUser))
  482. {
  483. return self::CheckCredentialsAndCreateUser($sName, $sPassword, $sLoginMode, $sAuthentication);
  484. }
  485. if (!$oUser->CheckCredentials($sPassword))
  486. {
  487. return false;
  488. }
  489. self::UpdateUser($oUser, $sLoginMode, $sAuthentication);
  490. return true;
  491. }
  492. public static function CheckCredentialsAndCreateUser($sName, $sPassword, $sLoginMode, $sAuthentication)
  493. {
  494. if (self::$m_sSelfRegisterAddOn != null)
  495. {
  496. return call_user_func(array(self::$m_sSelfRegisterAddOn, 'CheckCredentialsAndCreateUser'), $sName, $sPassword, $sLoginMode, $sAuthentication);
  497. }
  498. }
  499. public static function UpdateUser($oUser, $sLoginMode, $sAuthentication)
  500. {
  501. if (self::$m_sSelfRegisterAddOn != null)
  502. {
  503. call_user_func(array(self::$m_sSelfRegisterAddOn, 'UpdateUser'), $oUser, $sLoginMode, $sAuthentication);
  504. }
  505. }
  506. public static function TrustWebServerContext()
  507. {
  508. if (!is_null(self::$m_oUser))
  509. {
  510. return self::$m_oUser->TrustWebServerContext();
  511. }
  512. else
  513. {
  514. return false;
  515. }
  516. }
  517. public static function CanChangePassword()
  518. {
  519. if (MetaModel::DBIsReadOnly())
  520. {
  521. return false;
  522. }
  523. if (!is_null(self::$m_oUser))
  524. {
  525. return self::$m_oUser->CanChangePassword();
  526. }
  527. else
  528. {
  529. return false;
  530. }
  531. }
  532. public static function ChangePassword($sOldPassword, $sNewPassword, $sName = '')
  533. {
  534. if (empty($sName))
  535. {
  536. $oUser = self::$m_oUser;
  537. }
  538. else
  539. {
  540. // find the id out of the login string
  541. $oUser = self::FindUser($sName);
  542. }
  543. if (is_null($oUser))
  544. {
  545. return false;
  546. }
  547. else
  548. {
  549. return $oUser->ChangePassword($sOldPassword, $sNewPassword);
  550. }
  551. }
  552. public static function Impersonate($sName, $sPassword)
  553. {
  554. if (!self::CheckLogin()) return false;
  555. $oUser = self::FindUser($sName);
  556. if (is_null($oUser))
  557. {
  558. return false;
  559. }
  560. if (!$oUser->CheckCredentials($sPassword))
  561. {
  562. return false;
  563. }
  564. self::$m_oRealUser = self::$m_oUser;
  565. self::$m_oUser = $oUser;
  566. Dict::SetUserLanguage(self::GetUserLanguage());
  567. return true;
  568. }
  569. public static function GetUser()
  570. {
  571. if (is_null(self::$m_oUser))
  572. {
  573. return '';
  574. }
  575. else
  576. {
  577. return self::$m_oUser->Get('login');
  578. }
  579. }
  580. public static function GetUserObject()
  581. {
  582. if (is_null(self::$m_oUser))
  583. {
  584. return null;
  585. }
  586. else
  587. {
  588. return self::$m_oUser;
  589. }
  590. }
  591. public static function GetUserLanguage()
  592. {
  593. if (is_null(self::$m_oUser))
  594. {
  595. return 'EN US';
  596. }
  597. else
  598. {
  599. return self::$m_oUser->Get('language');
  600. }
  601. }
  602. public static function GetUserId($sName = '')
  603. {
  604. if (empty($sName))
  605. {
  606. // return current user id
  607. if (is_null(self::$m_oUser))
  608. {
  609. return null;
  610. }
  611. return self::$m_oUser->GetKey();
  612. }
  613. else
  614. {
  615. // find the id out of the login string
  616. $oUser = self::$m_oAddOn->FindUser($sName);
  617. if (is_null($oUser))
  618. {
  619. return null;
  620. }
  621. return $oUser->GetKey();
  622. }
  623. }
  624. public static function GetContactId($sName = '')
  625. {
  626. if (empty($sName))
  627. {
  628. $oUser = self::$m_oUser;
  629. }
  630. else
  631. {
  632. $oUser = FindUser($sName);
  633. }
  634. if (is_null($oUser))
  635. {
  636. return '';
  637. }
  638. if (!MetaModel::IsValidAttCode(get_class($oUser), 'contactid'))
  639. {
  640. return '';
  641. }
  642. return $oUser->Get('contactid');
  643. }
  644. // Render the user name in best effort mode
  645. public static function GetUserFriendlyName($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. return $oUser->GetFriendlyName();
  660. }
  661. public static function IsImpersonated()
  662. {
  663. if (is_null(self::$m_oRealUser))
  664. {
  665. return false;
  666. }
  667. return true;
  668. }
  669. public static function GetRealUser()
  670. {
  671. if (is_null(self::$m_oRealUser))
  672. {
  673. return '';
  674. }
  675. return self::$m_oRealUser->Get('login');
  676. }
  677. public static function GetRealUserId()
  678. {
  679. if (is_null(self::$m_oRealUser))
  680. {
  681. return '';
  682. }
  683. return self::$m_oRealUser->GetKey();
  684. }
  685. public static function GetRealUserFriendlyName()
  686. {
  687. if (is_null(self::$m_oRealUser))
  688. {
  689. return '';
  690. }
  691. return self::$m_oRealUser->GetFriendlyName();
  692. }
  693. protected static function CheckLogin()
  694. {
  695. if (!self::IsLoggedIn())
  696. {
  697. //throw new UserRightException('No user logged in', array());
  698. return false;
  699. }
  700. return true;
  701. }
  702. public static function GetSelectFilter($sClass, $aSettings = array())
  703. {
  704. // When initializing, we need to let everything pass trough
  705. if (!self::CheckLogin()) return true;
  706. if (self::IsAdministrator()) return true;
  707. if (MetaModel::HasCategory($sClass, 'bizmodel'))
  708. {
  709. return self::$m_oAddOn->GetSelectFilter(self::$m_oUser, $sClass, $aSettings);
  710. }
  711. else
  712. {
  713. return true;
  714. }
  715. }
  716. public static function IsActionAllowed($sClass, $iActionCode, /*dbObjectSet*/ $oInstanceSet = null, $oUser = null)
  717. {
  718. // When initializing, we need to let everything pass trough
  719. if (!self::CheckLogin()) return true;
  720. if (MetaModel::DBIsReadOnly())
  721. {
  722. if ($iActionCode == UR_ACTION_CREATE) return false;
  723. if ($iActionCode == UR_ACTION_MODIFY) return false;
  724. if ($iActionCode == UR_ACTION_BULK_MODIFY) return false;
  725. if ($iActionCode == UR_ACTION_DELETE) return false;
  726. if ($iActionCode == UR_ACTION_BULK_DELETE) return false;
  727. }
  728. $aPredefinedObjects = call_user_func(array($sClass, 'GetPredefinedObjects'));
  729. if ($aPredefinedObjects != null)
  730. {
  731. // As opposed to the read-only DB, modifying an object is allowed
  732. // (the constant columns will be marked as read-only)
  733. //
  734. if ($iActionCode == UR_ACTION_CREATE) return false;
  735. if ($iActionCode == UR_ACTION_DELETE) return false;
  736. if ($iActionCode == UR_ACTION_BULK_DELETE) return false;
  737. }
  738. if (self::IsAdministrator($oUser)) return true;
  739. if (MetaModel::HasCategory($sClass, 'bizmodel'))
  740. {
  741. if (is_null($oUser))
  742. {
  743. $oUser = self::$m_oUser;
  744. }
  745. if ($iActionCode == UR_ACTION_CREATE)
  746. {
  747. // The addons currently DO NOT handle the case "CREATE"
  748. // Therefore it is considered to be equivalent to "MODIFY"
  749. $iActionCode = UR_ACTION_MODIFY;
  750. }
  751. return self::$m_oAddOn->IsActionAllowed($oUser, $sClass, $iActionCode, $oInstanceSet);
  752. }
  753. elseif(($iActionCode == UR_ACTION_READ) && MetaModel::HasCategory($sClass, 'view_in_gui'))
  754. {
  755. return true;
  756. }
  757. else
  758. {
  759. // Other classes could be edited/listed by the administrators
  760. return false;
  761. }
  762. }
  763. public static function IsStimulusAllowed($sClass, $sStimulusCode, /*dbObjectSet*/ $oInstanceSet = null, $oUser = null)
  764. {
  765. // When initializing, we need to let everything pass trough
  766. if (!self::CheckLogin()) return true;
  767. if (MetaModel::DBIsReadOnly())
  768. {
  769. return false;
  770. }
  771. if (self::IsAdministrator($oUser)) return true;
  772. if (MetaModel::HasCategory($sClass, 'bizmodel'))
  773. {
  774. if (is_null($oUser))
  775. {
  776. $oUser = self::$m_oUser;
  777. }
  778. return self::$m_oAddOn->IsStimulusAllowed($oUser, $sClass, $sStimulusCode, $oInstanceSet);
  779. }
  780. else
  781. {
  782. // Other classes could be edited/listed by the administrators
  783. return false;
  784. }
  785. }
  786. public static function IsActionAllowedOnAttribute($sClass, $sAttCode, $iActionCode, /*dbObjectSet*/ $oInstanceSet = null, $oUser = null)
  787. {
  788. // When initializing, we need to let everything pass trough
  789. if (!self::CheckLogin()) return true;
  790. if (MetaModel::DBIsReadOnly())
  791. {
  792. if ($iActionCode == UR_ACTION_MODIFY) return false;
  793. if ($iActionCode == UR_ACTION_DELETE) return false;
  794. if ($iActionCode == UR_ACTION_BULK_MODIFY) return false;
  795. if ($iActionCode == UR_ACTION_BULK_DELETE) return false;
  796. }
  797. if (self::IsAdministrator($oUser)) return true;
  798. // this module is forbidden for non admins
  799. if (MetaModel::HasCategory($sClass, 'addon/userrights')) return false;
  800. // the rest is allowed (#@# to be improved)
  801. if (!MetaModel::HasCategory($sClass, 'bizmodel')) return true;
  802. if (is_null($oUser))
  803. {
  804. $oUser = self::$m_oUser;
  805. }
  806. return self::$m_oAddOn->IsActionAllowedOnAttribute($oUser, $sClass, $sAttCode, $iActionCode, $oInstanceSet);
  807. }
  808. static $m_aAdmins = array();
  809. public static function IsAdministrator($oUser = null)
  810. {
  811. if (!self::CheckLogin()) return false;
  812. if (is_null($oUser))
  813. {
  814. $oUser = self::$m_oUser;
  815. }
  816. $iUser = $oUser->GetKey();
  817. if (!isset(self::$m_aAdmins[$iUser]))
  818. {
  819. self::$m_aAdmins[$iUser] = self::$m_oAddOn->IsAdministrator($oUser);
  820. }
  821. return self::$m_aAdmins[$iUser];
  822. }
  823. static $m_aPortalUsers = array();
  824. public static function IsPortalUser($oUser = null)
  825. {
  826. if (!self::CheckLogin()) return false;
  827. if (is_null($oUser))
  828. {
  829. $oUser = self::$m_oUser;
  830. }
  831. $iUser = $oUser->GetKey();
  832. if (!isset(self::$m_aPortalUsers[$iUser]))
  833. {
  834. self::$m_aPortalUsers[$iUser] = self::$m_oAddOn->IsPortalUser($oUser);
  835. }
  836. return self::$m_aPortalUsers[$iUser];
  837. }
  838. /**
  839. * Reset cached data
  840. * @param Bool Reset admin cache as well
  841. * @return void
  842. */
  843. // Reset cached data
  844. //
  845. public static function FlushPrivileges($bResetAdminCache = false)
  846. {
  847. if ($bResetAdminCache)
  848. {
  849. self::$m_aAdmins = array();
  850. }
  851. return self::$m_oAddOn->FlushPrivileges();
  852. }
  853. static $m_aCacheUsers;
  854. /**
  855. * Find a user based on its login and its type of authentication
  856. * @param string $sLogin Login/identifier of the user
  857. * @param string $sAuthentication Type of authentication used: internal|external|any
  858. * @return User The found user or null
  859. */
  860. protected static function FindUser($sLogin, $sAuthentication = 'any')
  861. {
  862. if ($sAuthentication == 'any')
  863. {
  864. $oUser = self::FindUser($sLogin, 'internal');
  865. if ($oUser == null)
  866. {
  867. $oUser = self::FindUser($sLogin, 'external');
  868. }
  869. }
  870. else
  871. {
  872. if (!isset(self::$m_aCacheUsers))
  873. {
  874. self::$m_aCacheUsers = array('internal' => array(), 'external' => array());
  875. }
  876. if (!isset(self::$m_aCacheUsers[$sAuthentication][$sLogin]))
  877. {
  878. switch($sAuthentication)
  879. {
  880. case 'external':
  881. $sBaseClass = 'UserExternal';
  882. break;
  883. case 'internal':
  884. $sBaseClass = 'UserInternal';
  885. break;
  886. default:
  887. echo "<p>sAuthentication = $sAuthentication</p>\n";
  888. assert(false); // should never happen
  889. }
  890. $oSearch = DBObjectSearch::FromOQL("SELECT $sBaseClass WHERE login = :login");
  891. $oSet = new DBObjectSet($oSearch, array(), array('login' => $sLogin));
  892. $oUser = $oSet->fetch();
  893. self::$m_aCacheUsers[$sAuthentication][$sLogin] = $oUser;
  894. }
  895. $oUser = self::$m_aCacheUsers[$sAuthentication][$sLogin];
  896. }
  897. return $oUser;
  898. }
  899. public static function MakeSelectFilter($sClass, $aAllowedOrgs, $aSettings = array(), $sAttCode = null)
  900. {
  901. return self::$m_oAddOn->MakeSelectFilter($sClass, $aAllowedOrgs, $aSettings, $sAttCode);
  902. }
  903. }
  904. /**
  905. * Helper class to get the number/list of items for which a given action is allowed/possible
  906. */
  907. class ActionChecker
  908. {
  909. var $oFilter;
  910. var $iActionCode;
  911. var $iAllowedCount = null;
  912. var $aAllowedIDs = null;
  913. public function __construct(DBObjectSearch $oFilter, $iActionCode)
  914. {
  915. $this->oFilter = $oFilter;
  916. $this->iActionCode = $iActionCode;
  917. $this->iAllowedCount = null;
  918. $this->aAllowedIDs = null;
  919. }
  920. /**
  921. * returns the number of objects for which the action is allowed
  922. * @return integer The number of "allowed" objects 0..N
  923. */
  924. public function GetAllowedCount()
  925. {
  926. if ($this->iAllowedCount == null) $this->CheckObjects();
  927. return $this->iAllowedCount;
  928. }
  929. /**
  930. * If IsAllowed returned UR_ALLOWED_DEPENDS, this methods returns
  931. * an array of ObjKey => Status (true|false)
  932. * @return array
  933. */
  934. public function GetAllowedIDs()
  935. {
  936. if ($this->aAllowedIDs == null) $this->IsAllowed();
  937. return $this->aAllowedIDs;
  938. }
  939. /**
  940. * Check if the speficied stimulus is allowed for the set of objects
  941. * @return UR_ALLOWED_YES, UR_ALLOWED_NO or UR_ALLOWED_DEPENDS
  942. */
  943. public function IsAllowed()
  944. {
  945. $sClass = $this->oFilter->GetClass();
  946. $oSet = new DBObjectSet($this->oFilter);
  947. $iActionAllowed = UserRights::IsActionAllowed($sClass, $this->iActionCode, $oSet);
  948. if ($iActionAllowed == UR_ALLOWED_DEPENDS)
  949. {
  950. // Check for each object if the action is allowed or not
  951. $this->aAllowedIDs = array();
  952. $oSet->Rewind();
  953. $this->iAllowedCount = 0;
  954. while($oObj = $oSet->Fetch())
  955. {
  956. $oObjSet = DBObjectSet::FromArray($sClass, array($oObj));
  957. if (UserRights::IsActionAllowed($sClass, $this->iActionCode, $oObjSet) == UR_ALLOWED_NO)
  958. {
  959. $this->aAllowedIDs[$oObj->GetKey()] = false;
  960. }
  961. else
  962. {
  963. // Assume UR_ALLOWED_YES, since there is just one object !
  964. $this->aAllowedIDs[$oObj->GetKey()] = true;
  965. $this->iAllowedCount++;
  966. }
  967. }
  968. }
  969. else if ($iActionAllowed == UR_ALLOWED_YES)
  970. {
  971. $this->iAllowedCount = $oSet->Count();
  972. $this->aAllowedIDs = array(); // Optimization: not filled when Ok for all objects
  973. }
  974. else // UR_ALLOWED_NO
  975. {
  976. $this->iAllowedCount = 0;
  977. $this->aAllowedIDs = array();
  978. }
  979. return $iActionAllowed;
  980. }
  981. }
  982. /**
  983. * Helper class to get the number/list of items for which a given stimulus can be applied (allowed & possible)
  984. */
  985. class StimulusChecker extends ActionChecker
  986. {
  987. var $sState = null;
  988. public function __construct(DBObjectSearch $oFilter, $sState, $iStimulusCode)
  989. {
  990. parent::__construct($oFilter, $iStimulusCode);
  991. $this->sState = $sState;
  992. }
  993. /**
  994. * Check if the speficied stimulus is allowed for the set of objects
  995. * @return UR_ALLOWED_YES, UR_ALLOWED_NO or UR_ALLOWED_DEPENDS
  996. */
  997. public function IsAllowed()
  998. {
  999. $sClass = $this->oFilter->GetClass();
  1000. if (MetaModel::IsAbstract($sClass)) return UR_ALLOWED_NO; // Safeguard, not implemented if the base class of the set is abstract !
  1001. $oSet = new DBObjectSet($this->oFilter);
  1002. $iActionAllowed = UserRights::IsStimulusAllowed($sClass, $this->iActionCode, $oSet);
  1003. if ($iActionAllowed == UR_ALLOWED_NO)
  1004. {
  1005. $this->iAllowedCount = 0;
  1006. $this->aAllowedIDs = array();
  1007. }
  1008. else // Even if UR_ALLOWED_YES, we need to check if each object is in the appropriate state
  1009. {
  1010. // Hmmm, may not be needed right now because we limit the "multiple" action to object in
  1011. // the same state... may be useful later on if we want to extend this behavior...
  1012. // Check for each object if the action is allowed or not
  1013. $this->aAllowedIDs = array();
  1014. $oSet->Rewind();
  1015. $iAllowedCount = 0;
  1016. $iActionAllowed = UR_ALLOWED_DEPENDS;
  1017. while($oObj = $oSet->Fetch())
  1018. {
  1019. $aTransitions = $oObj->EnumTransitions();
  1020. if (array_key_exists($this->iActionCode, $aTransitions))
  1021. {
  1022. // Temporary optimization possible: since the current implementation
  1023. // of IsActionAllowed does not perform a 'per instance' check, we could
  1024. // skip this second validation phase and assume it would return UR_ALLOWED_YES
  1025. $oObjSet = DBObjectSet::FromArray($sClass, array($oObj));
  1026. if (!UserRights::IsStimulusAllowed($sClass, $this->iActionCode, $oObjSet))
  1027. {
  1028. $this->aAllowedIDs[$oObj->GetKey()] = false;
  1029. }
  1030. else
  1031. {
  1032. // Assume UR_ALLOWED_YES, since there is just one object !
  1033. $this->aAllowedIDs[$oObj->GetKey()] = true;
  1034. $this->iState = $oObj->GetState();
  1035. $this->iAllowedCount++;
  1036. }
  1037. }
  1038. else
  1039. {
  1040. $this->aAllowedIDs[$oObj->GetKey()] = false;
  1041. }
  1042. }
  1043. }
  1044. if ($this->iAllowedCount == $oSet->Count())
  1045. {
  1046. $iActionAllowed = UR_ALLOWED_YES;
  1047. }
  1048. if ($this->iAllowedCount == 0)
  1049. {
  1050. $iActionAllowed = UR_ALLOWED_NO;
  1051. }
  1052. return $iActionAllowed;
  1053. }
  1054. public function GetState()
  1055. {
  1056. return $this->iState;
  1057. }
  1058. }
  1059. /**
  1060. * Self-register extension to allow the automatic creation & update of CAS users
  1061. *
  1062. * @package iTopORM
  1063. *
  1064. */
  1065. class CAS_SelfRegister implements iSelfRegister
  1066. {
  1067. /**
  1068. * Called when no user is found in iTop for the corresponding 'name'. This method
  1069. * can create/synchronize the User in iTop with an external source (such as AD/LDAP) on the fly
  1070. * @param string $sName The CAS authenticated user name
  1071. * @param string $sPassword Ignored
  1072. * @param string $sLoginMode The login mode used (cas|form|basic|url)
  1073. * @param string $sAuthentication The authentication method used
  1074. * @return bool true if the user is a valid one, false otherwise
  1075. */
  1076. public static function CheckCredentialsAndCreateUser($sName, $sPassword, $sLoginMode, $sAuthentication)
  1077. {
  1078. $bOk = true;
  1079. if ($sLoginMode != 'cas') return false; // Must be authenticated via CAS
  1080. $sCASMemberships = MetaModel::GetConfig()->Get('cas_memberof');
  1081. $bFound = false;
  1082. if (!empty($sCASMemberships))
  1083. {
  1084. if (phpCAS::hasAttribute('memberOf'))
  1085. {
  1086. // A list of groups is specified, the user must a be member of (at least) one of them to pass
  1087. $aCASMemberships = array();
  1088. $aTmp = explode(';', $sCASMemberships);
  1089. setlocale(LC_ALL, "en_US.utf8"); // !!! WARNING: this is needed to have the iconv //TRANSLIT working fine below !!!
  1090. foreach($aTmp as $sGroupName)
  1091. {
  1092. $aCASMemberships[] = trim(iconv('UTF-8', 'ASCII//TRANSLIT', $sGroupName)); // Just in case remove accents and spaces...
  1093. }
  1094. $aMemberOf = phpCAS::getAttribute('memberOf');
  1095. if (!is_array($aMemberOf)) $aMemberOf = array($aMemberOf); // Just one entry, turn it into an array
  1096. $aFilteredGroupNames = array();
  1097. foreach($aMemberOf as $sGroupName)
  1098. {
  1099. phpCAS::log("Info: user if a member of the group: ".$sGroupName);
  1100. $sGroupName = trim(iconv('UTF-8', 'ASCII//TRANSLIT', $sGroupName)); // Remove accents and spaces as well
  1101. $aFilteredGroupNames[] = $sGroupName;
  1102. $bIsMember = false;
  1103. foreach($aCASMemberships as $sCASPattern)
  1104. {
  1105. if (self::IsPattern($sCASPattern))
  1106. {
  1107. if (preg_match($sCASPattern, $sGroupName))
  1108. {
  1109. $bIsMember = true;
  1110. break;
  1111. }
  1112. }
  1113. else if ($sPattern == $sGroupName)
  1114. {
  1115. $bIsMember = true;
  1116. break;
  1117. }
  1118. }
  1119. if ($bIsMember)
  1120. {
  1121. $bCASUserSynchro = MetaModel::GetConfig()->Get('cas_user_synchro');
  1122. if ($bCASUserSynchro)
  1123. {
  1124. // If needed create a new user for this email/profile
  1125. phpCAS::log('Info: cas_user_synchro is ON');
  1126. $bOk = self::CreateCASUser(phpCAS::getUser(), $aMemberOf);
  1127. if($bOk)
  1128. {
  1129. $bFound = true;
  1130. }
  1131. else
  1132. {
  1133. phpCAS::log("User ".phpCAS::getUser()." cannot be created in iTop. Logging off...");
  1134. }
  1135. }
  1136. else
  1137. {
  1138. phpCAS::log('Info: cas_user_synchro is OFF');
  1139. $bFound = true;
  1140. }
  1141. break;
  1142. }
  1143. }
  1144. if($bOk && !$bFound)
  1145. {
  1146. phpCAS::log("User ".phpCAS::getUser().", none of his/her groups (".implode('; ', $aFilteredGroupNames).") match any of the required groups: ".implode('; ', $aCASMemberships));
  1147. }
  1148. }
  1149. else
  1150. {
  1151. // Too bad, the user is not part of any of the group => not allowed
  1152. phpCAS::log("No 'memberOf' attribute found for user ".phpCAS::getUser().". Are you using the SAML protocol (S1) ?");
  1153. }
  1154. }
  1155. else
  1156. {
  1157. // No membership required, anybody will pass
  1158. $bFound = true;
  1159. }
  1160. if (!$bFound)
  1161. {
  1162. // The user is not part of the allowed groups, => log out
  1163. $sUrl = utils::GetAbsoluteUrlAppRoot().'pages/UI.php';
  1164. $sCASLogoutUrl = MetaModel::GetConfig()->Get('cas_logout_redirect_service');
  1165. if (empty($sCASLogoutUrl))
  1166. {
  1167. $sCASLogoutUrl = $sUrl;
  1168. }
  1169. phpCAS::logoutWithRedirectService($sCASLogoutUrl); // Redirects to the CAS logout page
  1170. // Will never return !
  1171. }
  1172. return $bFound;
  1173. }
  1174. /**
  1175. * Called after the user has been authenticated and found in iTop. This method can
  1176. * Update the user's definition (profiles...) on the fly to keep it in sync with an external source
  1177. * @param User $oUser The user to update/synchronize
  1178. * @param string $sLoginMode The login mode used (cas|form|basic|url)
  1179. * @param string $sAuthentication The authentication method used
  1180. * @return void
  1181. */
  1182. public static function UpdateUser(User $oUser, $sLoginMode, $sAuthentication)
  1183. {
  1184. $bCASUpdateProfiles = MetaModel::GetConfig()->Get('cas_update_profiles');
  1185. if (($sLoginMode == 'cas') && $bCASUpdateProfiles && (phpCAS::hasAttribute('memberOf')))
  1186. {
  1187. $aMemberOf = phpCAS::getAttribute('memberOf');
  1188. if (!is_array($aMemberOf)) $aMemberOf = array($aMemberOf); // Just one entry, turn it into an array
  1189. return self::SetProfilesFromCAS($oUser, $aMemberOf);
  1190. }
  1191. // No groups defined in CAS or not CAS at all: do nothing...
  1192. return true;
  1193. }
  1194. /**
  1195. * Helper method to create a CAS based user
  1196. * @param string $sEmail
  1197. * @param array $aGroups
  1198. * @return bool true on success, false otherwise
  1199. */
  1200. protected static function CreateCASUser($sEmail, $aGroups)
  1201. {
  1202. if (!MetaModel::IsValidClass('URP_Profiles'))
  1203. {
  1204. phpCAS::log("URP_Profiles is not a valid class. Automatic creation of Users is not supported in this context, sorry.");
  1205. return false;
  1206. }
  1207. $oUser = MetaModel::GetObjectByName('UserExternal', $sEmail, false);
  1208. if ($oUser == null)
  1209. {
  1210. // Create the user, link it to a contact
  1211. phpCAS::log("Info: the user '$sEmail' does not exist. A new UserExternal will be created.");
  1212. $oSearch = new DBObjectSearch('Person');
  1213. $oSearch->AddCondition('email', $sEmail);
  1214. $oSet = new DBObjectSet($oSearch);
  1215. $iContactId = 0;
  1216. switch($oSet->Count())
  1217. {
  1218. case 0:
  1219. phpCAS::log("Error: found no contact with the email: '$sEmail'. Cannot create the user in iTop.");
  1220. return false;
  1221. case 1:
  1222. $oContact = $oSet->Fetch();
  1223. $iContactId = $oContact->GetKey();
  1224. phpCAS::log("Info: Found 1 contact '".$oContact->GetName()."' (id=$iContactId) corresponding to the email '$sEmail'.");
  1225. break;
  1226. default:
  1227. phpCAS::log("Error: ".$oSet->Count()." contacts have the same email: '$sEmail'. Cannot create a user for this email.");
  1228. return false;
  1229. }
  1230. $oUser = new UserExternal();
  1231. $oUser->Set('login', $sEmail);
  1232. $oUser->Set('contactid', $iContactId);
  1233. $oUser->Set('language', MetaModel::GetConfig()->GetDefaultLanguage());
  1234. }
  1235. else
  1236. {
  1237. phpCAS::log("Info: the user '$sEmail' already exists (id=".$oUser->GetKey().").");
  1238. }
  1239. // Now synchronize the profiles
  1240. if (!self::SetProfilesFromCAS($oUser, $aGroups))
  1241. {
  1242. return false;
  1243. }
  1244. else
  1245. {
  1246. if ($oUser->IsNew() || $oUser->IsModified())
  1247. {
  1248. $oMyChange = MetaModel::NewObject("CMDBChange");
  1249. $oMyChange->Set("date", time());
  1250. $oMyChange->Set("userinfo", 'CAS/LDAP Synchro');
  1251. $oMyChange->DBInsert();
  1252. if ($oUser->IsNew())
  1253. {
  1254. $oUser->DBInsertTracked($oMyChange);
  1255. }
  1256. else
  1257. {
  1258. $oUser->DBUpdateTracked($oMyChange);
  1259. }
  1260. }
  1261. return true;
  1262. }
  1263. }
  1264. protected static function SetProfilesFromCAS($oUser, $aGroups)
  1265. {
  1266. if (!MetaModel::IsValidClass('URP_Profiles'))
  1267. {
  1268. phpCAS::log("URP_Profiles is not a valid class. Automatic creation of Users is not supported in this context, sorry.");
  1269. return false;
  1270. }
  1271. // read all the existing profiles
  1272. $oProfilesSearch = new DBObjectSearch('URP_Profiles');
  1273. $oProfilesSet = new DBObjectSet($oProfilesSearch);
  1274. $aAllProfiles = array();
  1275. while($oProfile = $oProfilesSet->Fetch())
  1276. {
  1277. $aAllProfiles[strtolower($oProfile->GetName())] = $oProfile->GetKey();
  1278. }
  1279. // Translate the CAS/LDAP group names into iTop profile names
  1280. $aProfiles = array();
  1281. $sPattern = MetaModel::GetConfig()->Get('cas_profile_pattern');
  1282. foreach($aGroups as $sGroupName)
  1283. {
  1284. if (preg_match($sPattern, $sGroupName, $aMatches))
  1285. {
  1286. if (array_key_exists(strtolower($aMatches[1]), $aAllProfiles))
  1287. {
  1288. $aProfiles[] = $aAllProfiles[strtolower($aMatches[1])];
  1289. phpCAS::log("Info: Adding the profile '{$aMatches[1]}' from CAS.");
  1290. }
  1291. else
  1292. {
  1293. phpCAS::log("Warning: {$aMatches[1]} is not a valid iTop profile (extracted from group name: '$sGroupName'). Ignored.");
  1294. }
  1295. }
  1296. else
  1297. {
  1298. phpCAS::log("Info: The CAS group '$sGroupName' does not seem to match an iTop pattern. Ignored.");
  1299. }
  1300. }
  1301. if (count($aProfiles) == 0)
  1302. {
  1303. phpCAS::log("Info: The user '".$oUser->GetName()."' has no profiles retrieved from CAS. Default profile(s) will be used.");
  1304. // Second attempt: check if there is/are valid default profile(s)
  1305. $sCASDefaultProfiles = MetaModel::GetConfig()->Get('cas_default_profiles');
  1306. $aCASDefaultProfiles = explode(';', $sCASDefaultProfiles);
  1307. foreach($aCASDefaultProfiles as $sDefaultProfileName)
  1308. {
  1309. if (array_key_exists(strtolower($sDefaultProfileName), $aAllProfiles))
  1310. {
  1311. $aProfiles[] = $aAllProfiles[strtolower($sDefaultProfileName)];
  1312. phpCAS::log("Info: Adding the default profile '".$aAllProfiles[strtolower($sDefaultProfileName)]."' from CAS.");
  1313. }
  1314. else
  1315. {
  1316. phpCAS::log("Warning: the default profile {$sDefaultProfileName} is not a valid iTop profile. Ignored.");
  1317. }
  1318. }
  1319. if (count($aProfiles) == 0)
  1320. {
  1321. phpCAS::log("Error: The user '".$oUser->GetName()."' has no profiles in iTop, and therefore cannot be created.");
  1322. return false;
  1323. }
  1324. }
  1325. // Now synchronize the profiles
  1326. $oProfilesSet = DBObjectSet::FromScratch('URP_UserProfile');
  1327. foreach($aProfiles as $iProfileId)
  1328. {
  1329. $oLink = new URP_UserProfile();
  1330. $oLink->Set('profileid', $iProfileId);
  1331. $oLink->Set('reason', 'CAS/LDAP Synchro');
  1332. $oProfilesSet->AddObject($oLink);
  1333. }
  1334. $oUser->Set('profile_list', $oProfilesSet);
  1335. phpCAS::log("Info: the user '".$oUser->GetName()."' (id=".$oUser->GetKey().") now has the following profiles: '".implode("', '", $aProfiles)."'.");
  1336. if ($oUser->IsModified())
  1337. {
  1338. $oMyChange = MetaModel::NewObject("CMDBChange");
  1339. $oMyChange->Set("date", time());
  1340. $oMyChange->Set("userinfo", 'CAS/LDAP Synchro');
  1341. $oMyChange->DBInsert();
  1342. if ($oUser->IsNew())
  1343. {
  1344. $oUser->DBInsertTracked($oMyChange);
  1345. }
  1346. else
  1347. {
  1348. $oUser->DBUpdateTracked($oMyChange);
  1349. }
  1350. }
  1351. return true;
  1352. }
  1353. /**
  1354. * Helper function to check if the supplied string is a litteral string or a regular expression pattern
  1355. * @param string $sCASPattern
  1356. * @return bool True if it's a regular expression pattern, false otherwise
  1357. */
  1358. protected static function IsPattern($sCASPattern)
  1359. {
  1360. if ((substr($sCASPattern, 0, 1) == '/') && (substr($sCASPattern, -1) == '/'))
  1361. {
  1362. // the string is enclosed by slashes, let's assume it's a pattern
  1363. return true;
  1364. }
  1365. else
  1366. {
  1367. return false;
  1368. }
  1369. }
  1370. }
  1371. // By default enable the 'CAS_SelfRegister' defined above
  1372. UserRights::SelectSelfRegister('CAS_SelfRegister');
  1373. ?>