userrights.class.inc.php 46 KB

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