users.js 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042
  1. module.controller('UserRoleMappingCtrl', function($scope, $http, $route, realm, user, client, Client, Notifications, RealmRoleMapping,
  2. ClientRoleMapping, AvailableRealmRoleMapping, AvailableClientRoleMapping,
  3. CompositeRealmRoleMapping, CompositeClientRoleMapping, $translate) {
  4. $scope.realm = realm;
  5. $scope.user = user;
  6. $scope.selectedRealmRoles = [];
  7. $scope.selectedRealmMappings = [];
  8. $scope.realmMappings = [];
  9. $scope.client = client;
  10. $scope.clientRoles = [];
  11. $scope.clientComposite = [];
  12. $scope.selectedClientRoles = [];
  13. $scope.selectedClientMappings = [];
  14. $scope.clientMappings = [];
  15. $scope.dummymodel = [];
  16. $scope.selectedClient = null;
  17. $scope.realmMappings = RealmRoleMapping.query({realm : realm.realm, userId : user.id});
  18. $scope.realmRoles = AvailableRealmRoleMapping.query({realm : realm.realm, userId : user.id});
  19. $scope.realmComposite = CompositeRealmRoleMapping.query({realm : realm.realm, userId : user.id});
  20. $scope.addRealmRole = function() {
  21. $scope.realmRolesToAdd = JSON.parse('[' + $scope.selectedRealmRoles + ']');
  22. $scope.selectedRealmRoles = [];
  23. $http.post(authUrl + '/admin/realms/' + realm.realm + '/users/' + user.id + '/role-mappings/realm',
  24. $scope.realmRolesToAdd).then(function() {
  25. $scope.realmMappings = RealmRoleMapping.query({realm : realm.realm, userId : user.id});
  26. $scope.realmRoles = AvailableRealmRoleMapping.query({realm : realm.realm, userId : user.id});
  27. $scope.realmComposite = CompositeRealmRoleMapping.query({realm : realm.realm, userId : user.id});
  28. $scope.selectedRealmMappings = [];
  29. $scope.selectRealmRoles = [];
  30. if ($scope.selectedClient) {
  31. console.log('load available');
  32. $scope.clientComposite = CompositeClientRoleMapping.query({realm : realm.realm, userId : user.id, client : $scope.selectedClient.id});
  33. $scope.clientRoles = AvailableClientRoleMapping.query({realm : realm.realm, userId : user.id, client : $scope.selectedClient.id});
  34. $scope.clientMappings = ClientRoleMapping.query({realm : realm.realm, userId : user.id, client : $scope.selectedClient.id});
  35. $scope.selectedClientRoles = [];
  36. $scope.selectedClientMappings = [];
  37. }
  38. Notifications.success($translate.instant('user.roles.add.success'));
  39. });
  40. };
  41. $scope.deleteRealmRole = function() {
  42. $scope.realmRolesToRemove = JSON.parse('[' + $scope.selectedRealmMappings + ']');
  43. $http.delete(authUrl + '/admin/realms/' + realm.realm + '/users/' + user.id + '/role-mappings/realm',
  44. {data : $scope.realmRolesToRemove, headers : {"content-type" : "application/json"}}).then(function() {
  45. $scope.realmMappings = RealmRoleMapping.query({realm : realm.realm, userId : user.id});
  46. $scope.realmRoles = AvailableRealmRoleMapping.query({realm : realm.realm, userId : user.id});
  47. $scope.realmComposite = CompositeRealmRoleMapping.query({realm : realm.realm, userId : user.id});
  48. $scope.selectedRealmMappings = [];
  49. $scope.selectRealmRoles = [];
  50. if ($scope.selectedClient) {
  51. console.log('load available');
  52. $scope.clientComposite = CompositeClientRoleMapping.query({realm : realm.realm, userId : user.id, client : $scope.selectedClient.id});
  53. $scope.clientRoles = AvailableClientRoleMapping.query({realm : realm.realm, userId : user.id, client : $scope.selectedClient.id});
  54. $scope.clientMappings = ClientRoleMapping.query({realm : realm.realm, userId : user.id, client : $scope.selectedClient.id});
  55. $scope.selectedClientRoles = [];
  56. $scope.selectedClientMappings = [];
  57. }
  58. Notifications.success($translate.instant('user.roles.remove.success'));
  59. });
  60. };
  61. $scope.addClientRole = function() {
  62. $scope.clientRolesToAdd = JSON.parse('[' + $scope.selectedClientRoles + ']');
  63. $http.post(authUrl + '/admin/realms/' + realm.realm + '/users/' + user.id + '/role-mappings/clients/' + $scope.selectedClient.id,
  64. $scope.clientRolesToAdd).then(function() {
  65. $scope.clientMappings = ClientRoleMapping.query({realm : realm.realm, userId : user.id, client : $scope.selectedClient.id});
  66. $scope.clientRoles = AvailableClientRoleMapping.query({realm : realm.realm, userId : user.id, client : $scope.selectedClient.id});
  67. $scope.clientComposite = CompositeClientRoleMapping.query({realm : realm.realm, userId : user.id, client : $scope.selectedClient.id});
  68. $scope.selectedClientRoles = [];
  69. $scope.selectedClientMappings = [];
  70. $scope.realmComposite = CompositeRealmRoleMapping.query({realm : realm.realm, userId : user.id});
  71. $scope.realmRoles = AvailableRealmRoleMapping.query({realm : realm.realm, userId : user.id});
  72. Notifications.success($translate.instant('user.roles.add.success'));
  73. });
  74. };
  75. $scope.deleteClientRole = function() {
  76. $scope.clientRolesToRemove = JSON.parse('[' + $scope.selectedClientMappings + ']');
  77. $http.delete(authUrl + '/admin/realms/' + realm.realm + '/users/' + user.id + '/role-mappings/clients/' + $scope.selectedClient.id,
  78. {data : $scope.clientRolesToRemove, headers : {"content-type" : "application/json"}}).then(function() {
  79. $scope.clientMappings = ClientRoleMapping.query({realm : realm.realm, userId : user.id, client : $scope.selectedClient.id});
  80. $scope.clientRoles = AvailableClientRoleMapping.query({realm : realm.realm, userId : user.id, client : $scope.selectedClient.id});
  81. $scope.clientComposite = CompositeClientRoleMapping.query({realm : realm.realm, userId : user.id, client : $scope.selectedClient.id});
  82. $scope.selectedClientRoles = [];
  83. $scope.selectedClientMappings = [];
  84. $scope.realmComposite = CompositeRealmRoleMapping.query({realm : realm.realm, userId : user.id});
  85. $scope.realmRoles = AvailableRealmRoleMapping.query({realm : realm.realm, userId : user.id});
  86. Notifications.success($translate.instant('user.roles.remove.success'));
  87. });
  88. };
  89. $scope.changeClient = function(client) {
  90. console.log("selected client: ", client);
  91. if (!client || !client.id) {
  92. $scope.selectedClient = null;
  93. return;
  94. } else {
  95. $scope.selectedClient = client;
  96. }
  97. if ($scope.selectedClient) {
  98. console.log('load available');
  99. $scope.clientComposite = CompositeClientRoleMapping.query({realm : realm.realm, userId : user.id, client : $scope.selectedClient.id});
  100. $scope.clientRoles = AvailableClientRoleMapping.query({realm : realm.realm, userId : user.id, client : $scope.selectedClient.id});
  101. $scope.clientMappings = ClientRoleMapping.query({realm : realm.realm, userId : user.id, client : $scope.selectedClient.id});
  102. } else {
  103. $scope.clientRoles = null;
  104. $scope.clientMappings = null;
  105. $scope.clientComposite = null;
  106. }
  107. $scope.selectedClientRoles = [];
  108. $scope.selectedClientMappings = [];
  109. };
  110. clientSelectControl($scope, $route.current.params.realm, Client);
  111. });
  112. module.controller('UserSessionsCtrl', function($scope, realm, user, sessions, UserSessions, UserLogout, UserSessionLogout, Notifications, $translate) {
  113. $scope.realm = realm;
  114. $scope.user = user;
  115. $scope.sessions = sessions;
  116. $scope.logoutAll = function() {
  117. UserLogout.save({realm : realm.realm, user: user.id}, function () {
  118. Notifications.success($translate.instant('user.logout.all.success'));
  119. UserSessions.query({realm: realm.realm, user: user.id}, function(updated) {
  120. $scope.sessions = updated;
  121. })
  122. });
  123. };
  124. $scope.logoutSession = function(sessionId) {
  125. console.log('here in logoutSession');
  126. UserSessionLogout.delete({realm : realm.realm, session: sessionId}, function() {
  127. UserSessions.query({realm: realm.realm, user: user.id}, function(updated) {
  128. $scope.sessions = updated;
  129. Notifications.success($translate.instant('user.logout.session.success'));
  130. })
  131. });
  132. }
  133. });
  134. module.controller('UserFederatedIdentityCtrl', function($scope, $location, realm, user, federatedIdentities, UserFederatedIdentity, Notifications, Dialog, $translate) {
  135. $scope.realm = realm;
  136. $scope.user = user;
  137. $scope.federatedIdentities = federatedIdentities;
  138. $scope.hasAnyProvidersToCreate = function() {
  139. return realm.identityProviders.length - $scope.federatedIdentities.length > 0;
  140. }
  141. $scope.removeProviderLink = function(providerLink) {
  142. console.log("Removing provider link: " + providerLink.identityProvider);
  143. Dialog.confirmWithButtonText(
  144. $translate.instant('user.fedid.link.remove.confirm.title', {name: providerLink.identityProvider}),
  145. $translate.instant('user.fedid.link.remove.confirm.message', {name: providerLink.identityProvider}),
  146. $translate.instant('dialogs.delete.confirm'),
  147. function() {
  148. UserFederatedIdentity.remove({ realm: realm.realm, user: user.id, provider: providerLink.identityProvider }, function() {
  149. Notifications.success($translate.instant('user.fedid.link.remove.success'));
  150. var indexToRemove = $scope.federatedIdentities.indexOf(providerLink);
  151. $scope.federatedIdentities.splice(indexToRemove, 1);
  152. });
  153. }
  154. );
  155. }
  156. });
  157. module.controller('UserFederatedIdentityAddCtrl', function($scope, $location, realm, user, federatedIdentities, UserFederatedIdentity, Notifications, $translate) {
  158. $scope.realm = realm;
  159. $scope.user = user;
  160. $scope.federatedIdentity = {};
  161. var getAvailableProvidersToCreate = function() {
  162. var realmProviders = [];
  163. for (var i=0 ; i<realm.identityProviders.length ; i++) {
  164. var providerAlias = realm.identityProviders[i].alias;
  165. realmProviders.push(providerAlias);
  166. };
  167. for (var i=0 ; i<federatedIdentities.length ; i++) {
  168. var providerAlias = federatedIdentities[i].identityProvider;
  169. var index = realmProviders.indexOf(providerAlias);
  170. realmProviders.splice(index, 1);
  171. }
  172. return realmProviders;
  173. }
  174. $scope.availableProvidersToCreate = getAvailableProvidersToCreate();
  175. $scope.save = function() {
  176. UserFederatedIdentity.save({
  177. realm : realm.realm,
  178. user: user.id,
  179. provider: $scope.federatedIdentity.identityProvider
  180. }, $scope.federatedIdentity, function(data, headers) {
  181. $location.url("/realms/" + realm.realm + '/users/' + $scope.user.id + '/federated-identity');
  182. Notifications.success($translate.instant('user.fedid.link.add.success'));
  183. });
  184. };
  185. $scope.cancel = function() {
  186. $location.url("/realms/" + realm.realm + '/users/' + $scope.user.id + '/federated-identity');
  187. };
  188. });
  189. module.controller('UserConsentsCtrl', function($scope, realm, user, userConsents, UserConsents, Notifications, $translate) {
  190. $scope.realm = realm;
  191. $scope.user = user;
  192. $scope.userConsents = userConsents;
  193. $scope.revokeConsent = function(clientId) {
  194. UserConsents.delete({realm : realm.realm, user: user.id, client: clientId }, function () {
  195. UserConsents.query({realm: realm.realm, user: user.id}, function(updated) {
  196. $scope.userConsents = updated;
  197. })
  198. Notifications.success($translate.instant('user.consent.revoke.success'));
  199. }, function() {
  200. Notifications.error($translate.instant('user.consent.revoke.error'));
  201. });
  202. console.log("Revoke consent " + clientId);
  203. }
  204. });
  205. module.controller('UserOfflineSessionsCtrl', function($scope, $location, realm, user, client, offlineSessions) {
  206. $scope.realm = realm;
  207. $scope.user = user;
  208. $scope.client = client;
  209. $scope.offlineSessions = offlineSessions;
  210. $scope.cancel = function() {
  211. $location.url("/realms/" + realm.realm + '/users/' + user.id + '/consents');
  212. };
  213. });
  214. module.controller('UserListCtrl', function($scope, realm, User, UserSearchState, UserImpersonation, BruteForce, Notifications, $route, Dialog, $translate) {
  215. $scope.init = function() {
  216. $scope.realm = realm;
  217. UserSearchState.query.realm = realm.realm;
  218. $scope.query = UserSearchState.query;
  219. $scope.query.briefRepresentation = 'true';
  220. if (!UserSearchState.isFirstSearch) $scope.searchQuery();
  221. };
  222. $scope.impersonate = function(userId) {
  223. UserImpersonation.save({realm : realm.realm, user: userId}, function (data) {
  224. if (data.sameRealm) {
  225. window.location = data.redirect;
  226. } else {
  227. window.open(data.redirect, "_blank");
  228. }
  229. });
  230. };
  231. $scope.unlockUsers = function() {
  232. BruteForce.delete({realm: realm.realm}, function(data) {
  233. Notifications.success($translate.instant('user.unlock.success'));
  234. });
  235. }
  236. $scope.firstPage = function() {
  237. $scope.query.first = 0;
  238. $scope.searchQuery();
  239. }
  240. $scope.previousPage = function() {
  241. $scope.query.first -= parseInt($scope.query.max);
  242. if ($scope.query.first < 0) {
  243. $scope.query.first = 0;
  244. }
  245. $scope.searchQuery();
  246. }
  247. $scope.nextPage = function() {
  248. $scope.query.first += parseInt($scope.query.max);
  249. $scope.searchQuery();
  250. }
  251. $scope.searchQuery = function() {
  252. console.log("query.search: " + $scope.query.search);
  253. $scope.searchLoaded = false;
  254. $scope.users = User.query($scope.query, function() {
  255. $scope.searchLoaded = true;
  256. $scope.lastSearch = $scope.query.search;
  257. UserSearchState.isFirstSearch = false;
  258. });
  259. };
  260. $scope.removeUser = function(user) {
  261. Dialog.confirmWithButtonText(
  262. $translate.instant('user.remove.confirm.title', {name: user.id}),
  263. $translate.instant('user.remove.confirm.message', {name: user.id}),
  264. $translate.instant('dialogs.delete.confirm'),
  265. function() {
  266. user.$remove({
  267. realm : realm.realm,
  268. userId : user.id
  269. }, function() {
  270. $route.reload();
  271. if ($scope.users.length === 1 && $scope.query.first > 0) {
  272. $scope.previousPage();
  273. }
  274. Notifications.success($translate.instant('user.remove.success'));
  275. }, function() {
  276. Notifications.error($translate.instant('user.remove.error'));
  277. });
  278. }
  279. );
  280. };
  281. });
  282. module.controller('UserTabCtrl', function($scope, $location, Dialog, Notifications, Current) {
  283. $scope.removeUser = function() {
  284. Dialog.confirmDelete($scope.user.id, 'user', function() {
  285. $scope.user.$remove({
  286. realm : Current.realm.realm,
  287. userId : $scope.user.id
  288. }, function() {
  289. $location.url("/realms/" + Current.realm.realm + "/users");
  290. Notifications.success($translate.instant('user.remove.success'));
  291. }, function() {
  292. Notifications.error($translate.instant('user.remove.error'));
  293. });
  294. });
  295. };
  296. });
  297. function loadUserStorageLink(realm, user, console, Components, UserStorageOperations, $scope, $location) {
  298. if(user.federationLink) {
  299. console.log("federationLink is not null. It is " + user.federationLink);
  300. if ($scope.access.viewRealm) {
  301. Components.get({realm: realm.realm, componentId: user.federationLink}, function (link) {
  302. $scope.federationLinkName = link.name;
  303. $scope.federationLink = "#/realms/" + realm.realm + "/user-storage/providers/" + link.providerId + "/" + link.id;
  304. });
  305. } else {
  306. // KEYCLOAK-4328
  307. UserStorageOperations.simpleName.get({realm: realm.realm, componentId: user.federationLink}, function (link) {
  308. $scope.federationLinkName = link.name;
  309. $scope.federationLink = $location.absUrl();
  310. })
  311. }
  312. } else {
  313. console.log("federationLink is null");
  314. }
  315. if(user.origin) {
  316. if ($scope.access.viewRealm) {
  317. Components.get({realm: realm.realm, componentId: user.origin}, function (link) {
  318. $scope.originName = link.name;
  319. $scope.originLink = "#/realms/" + realm.realm + "/user-storage/providers/" + link.providerId + "/" + link.id;
  320. })
  321. }
  322. else {
  323. // KEYCLOAK-4328
  324. UserStorageOperations.simpleName.get({realm: realm.realm, componentId: user.origin}, function (link) {
  325. $scope.originName = link.name;
  326. $scope.originLink = $location.absUrl();
  327. })
  328. }
  329. } else {
  330. console.log("origin is null");
  331. }
  332. };
  333. module.controller('UserDetailCtrl', function($scope, realm, user, BruteForceUser, User,
  334. Components,
  335. UserImpersonation, RequiredActions,
  336. UserStorageOperations,
  337. $location, $http, Dialog, Notifications, $translate, $route, Groups) {
  338. $scope.realm = realm;
  339. $scope.create = !user.id;
  340. $scope.editUsername = $scope.create || $scope.realm.editUsernameAllowed;
  341. $scope.emailAsUsername = $scope.realm.registrationEmailAsUsername;
  342. $scope.groupSearch = { selectedGroup : null };
  343. if ($scope.create) {
  344. $scope.user = { enabled: true, attributes: {}, groups: [] }
  345. } else {
  346. if (!user.attributes) {
  347. user.attributes = {}
  348. }
  349. convertAttributeValuesToString(user);
  350. $scope.user = angular.copy(user);
  351. $scope.impersonate = function() {
  352. UserImpersonation.save({realm : realm.realm, user: $scope.user.id}, function (data) {
  353. if (data.sameRealm) {
  354. window.location = data.redirect;
  355. } else {
  356. window.open(data.redirect, "_blank");
  357. }
  358. });
  359. };
  360. loadUserStorageLink(realm, user, console, Components, UserStorageOperations, $scope, $location);
  361. console.log('realm brute force? ' + realm.bruteForceProtected)
  362. $scope.temporarilyDisabled = false;
  363. var isDisabled = function () {
  364. BruteForceUser.get({realm: realm.realm, userId: user.id}, function(data) {
  365. console.log('here in isDisabled ' + data.disabled);
  366. $scope.temporarilyDisabled = data.disabled;
  367. });
  368. };
  369. console.log("check if disabled");
  370. isDisabled();
  371. $scope.unlockUser = function() {
  372. BruteForceUser.delete({realm: realm.realm, userId: user.id}, function(data) {
  373. isDisabled();
  374. });
  375. }
  376. }
  377. $scope.changed = false; // $scope.create;
  378. if (user.requiredActions) {
  379. for (var i = 0; i < user.requiredActions.length; i++) {
  380. console.log("user require action: " + user.requiredActions[i]);
  381. }
  382. }
  383. // ID - Name map for required actions. IDs are enum names.
  384. RequiredActions.query({realm: realm.realm}, function(data) {
  385. $scope.userReqActionList = [];
  386. for (var i = 0; i < data.length; i++) {
  387. console.log("listed required action: " + data[i].name);
  388. if (data[i].enabled) {
  389. var item = data[i];
  390. $scope.userReqActionList.push(item);
  391. }
  392. }
  393. console.log("---------------------");
  394. console.log("ng-model: user.requiredActions=" + JSON.stringify($scope.user.requiredActions));
  395. console.log("---------------------");
  396. console.log("ng-repeat: userReqActionList=" + JSON.stringify($scope.userReqActionList));
  397. console.log("---------------------");
  398. });
  399. $scope.$watch('user', function() {
  400. if (!angular.equals($scope.user, user)) {
  401. $scope.changed = true;
  402. }
  403. }, true);
  404. $scope.save = function() {
  405. convertAttributeValuesToLists();
  406. if ($scope.create) {
  407. pushSelectedGroupsToUser();
  408. User.save({
  409. realm: realm.realm
  410. }, $scope.user, function (data, headers) {
  411. $scope.changed = false;
  412. convertAttributeValuesToString($scope.user);
  413. user = angular.copy($scope.user);
  414. var l = headers().location;
  415. console.debug("Location == " + l);
  416. var id = l.substring(l.lastIndexOf("/") + 1);
  417. $location.url("/realms/" + realm.realm + "/users/" + id);
  418. Notifications.success($translate.instant('user.create.success'));
  419. });
  420. } else {
  421. User.update({
  422. realm: realm.realm,
  423. userId: $scope.user.id
  424. }, $scope.user, function () {
  425. Notifications.success($translate.instant('user.edit.success'));
  426. $route.reload();
  427. });
  428. }
  429. };
  430. function convertAttributeValuesToLists() {
  431. var attrs = $scope.user.attributes;
  432. for (var attribute in attrs) {
  433. if (typeof attrs[attribute] === "string") {
  434. var attrVals = attrs[attribute].split("##");
  435. attrs[attribute] = attrVals;
  436. }
  437. }
  438. }
  439. function convertAttributeValuesToString(user) {
  440. var attrs = user.attributes;
  441. for (var attribute in attrs) {
  442. if (typeof attrs[attribute] === "object") {
  443. var attrVals = attrs[attribute].join("##");
  444. attrs[attribute] = attrVals;
  445. }
  446. }
  447. }
  448. function pushSelectedGroupsToUser() {
  449. var groups = $scope.user.groups;
  450. if ($scope.selectedGroups) {
  451. for (i = 0; i < $scope.selectedGroups.length; i++) {
  452. var groupPath = $scope.selectedGroups[i].path;
  453. if (!groups.includes(groupPath)) {
  454. groups.push(groupPath);
  455. }
  456. }
  457. }
  458. }
  459. function bfs(tree, collection) {
  460. if (!tree["subGroups"] || tree["subGroups"].length === 0) return;
  461. for (var i=0; i < tree["subGroups"].length; i++) {
  462. var child = tree["subGroups"][i]
  463. collection.push(child);
  464. bfs(child, collection);
  465. }
  466. return;
  467. }
  468. function flattenGroups(groups) {
  469. var flattenedGroups = [];
  470. if (!groups || groups.length === 0) return groups;
  471. for (var i=0; i < groups.length; i++) {
  472. flattenedGroups.push(groups[i]);
  473. bfs(groups[i], flattenedGroups);
  474. }
  475. return flattenedGroups;
  476. }
  477. /**
  478. * Only keep groups that :
  479. * - include the search term in their path
  480. * - are not already selected
  481. */
  482. function filterSearchedGroups(groups, term, selectedGroups) {
  483. if (!groups || groups.length === 0) return groups;
  484. if (!selectedGroups) selectedGroups = [];
  485. return groups.filter(group => group.path?.includes(term) && !selectedGroups.some(selGroup => selGroup.id === group.id));
  486. }
  487. $scope.reset = function() {
  488. $scope.user = angular.copy(user);
  489. $scope.changed = false;
  490. };
  491. $scope.cancel = function() {
  492. $location.url("/realms/" + realm.realm + "/users");
  493. };
  494. $scope.addAttribute = function() {
  495. $scope.user.attributes[$scope.newAttribute.key] = $scope.newAttribute.value;
  496. delete $scope.newAttribute;
  497. }
  498. $scope.removeAttribute = function(key) {
  499. delete $scope.user.attributes[key];
  500. }
  501. $scope.groupsUiSelect = {
  502. minimumInputLength: 1,
  503. delay: 500,
  504. allowClear: true,
  505. query: function (query) {
  506. var data = {results: []};
  507. if ('' == query.term.trim()) {
  508. query.callback(data);
  509. return;
  510. }
  511. $scope.query = {
  512. realm: realm.realm,
  513. search: query.term.trim(),
  514. max : 20,
  515. first : 0
  516. };
  517. Groups.query($scope.query, function(response) {
  518. data.results = filterSearchedGroups(flattenGroups(response), query.term.trim(), $scope.selectedGroups);
  519. query.callback(data);
  520. });
  521. },
  522. formatResult: function(object, container, query) {
  523. object.text = object.path;
  524. return object.path;
  525. }
  526. };
  527. $scope.removeGroup = function(list, group) {
  528. for (i = 0; i < angular.copy(list).length; i++) {
  529. if (group.id == list[i].id) {
  530. list.splice(i, 1);
  531. }
  532. }
  533. }
  534. $scope.selectGroup = function(group) {
  535. if (!group || !group.id) {
  536. return;
  537. }
  538. $scope.groupSearch.selectedGroup = group;
  539. if (!$scope.selectedGroups) {
  540. $scope.selectedGroups = [];
  541. }
  542. for (i = 0; i < $scope.selectedGroups.length; i++) {
  543. if ($scope.selectedGroups[i].id == group.id) {
  544. return;
  545. }
  546. }
  547. $scope.selectedGroups.push(group);
  548. $scope.groupSearch.selectedGroup = null;
  549. }
  550. $scope.clearGroupSelection = function() {
  551. $scope.groupSearch.selectedGroup = null;
  552. $('#groups').val(null).trigger('change.select2');
  553. }
  554. });
  555. module.controller('UserCredentialsCtrl', function($scope, realm, user, $route, $location, RequiredActions, User, UserExecuteActionsEmail,
  556. UserCredentials, Notifications, Dialog, TimeUnit2, Components, UserStorageOperations, $modal, $translate) {
  557. console.log('UserCredentialsCtrl');
  558. $scope.hasPassword = false;
  559. loadCredentials();
  560. loadUserStorageLink(realm, user, console, Components, UserStorageOperations, $scope, $location);
  561. $scope.getUserStorageProviderName = function() {
  562. return user.federationLink ? $scope.federationLinkName : $scope.originName;
  563. }
  564. $scope.getUserStorageProviderLink = function() {
  565. return user.federationLink ? $scope.federationLink : $scope.originLink;
  566. }
  567. $scope.updateCredentialLabel = function(credential) {
  568. UserCredentials.updateCredentialLabel({ realm: realm.realm, userId: user.id, credentialId: credential.id }, {
  569. 'id': credential.id,
  570. 'userLabel': credential.userLabel ? credential.userLabel : "",
  571. // We JSONify the credential data
  572. 'credentialData': JSON.stringify(credential.credentialData)
  573. }, function() {
  574. Notifications.success($translate.instant('user.credential.update.success'));
  575. }, function(err) {
  576. Notifications.error($translate.instant('user.credential.update.error'));
  577. console.log(err);
  578. });
  579. }
  580. $scope.deleteCredential = function(credential) {
  581. Dialog.confirmWithButtonText(
  582. $translate.instant('user.credential.remove.confirm.title', {name: credential.id}),
  583. $translate.instant('user.credential.remove.confirm.message', {name: credential.id}),
  584. $translate.instant('dialogs.delete.confirm'),
  585. function() {
  586. UserCredentials.deleteCredential({ realm: realm.realm, userId: user.id, credentialId: credential.id }, null, function() {
  587. Notifications.success($translate.instant('user.credential.remove.success'));
  588. $route.reload();
  589. }, function(err) {
  590. Notifications.error($translate.instant('user.credential.remove.error'));
  591. console.log(err);
  592. })
  593. }
  594. );
  595. }
  596. $scope.moveUp = function(credentials, index) {
  597. // Safety first
  598. if (index == 0) {
  599. return;
  600. } else if (index == 1) {
  601. UserCredentials.moveToFirst(
  602. {
  603. realm: realm.realm,
  604. userId: user.id,
  605. credentialId: credentials[index].id
  606. },
  607. function () {
  608. $route.reload();
  609. },
  610. function (err) {
  611. Notifications.error($translate.instant('user.credential.move-top.error'));
  612. console.log(err);
  613. });
  614. } else {
  615. UserCredentials.moveCredentialAfter(
  616. {
  617. realm: realm.realm,
  618. userId: user.id,
  619. credentialId: credentials[index].id,
  620. newPreviousCredentialId: credentials[index - 2].id
  621. },
  622. function () {
  623. $route.reload();
  624. },
  625. function (err) {
  626. Notifications.error($translate.instant('user.credential.move-up.error'));
  627. console.log(err);
  628. });
  629. }
  630. }
  631. $scope.moveDown = function(credentials, index) {
  632. // Safety first
  633. if (index == credentials.length - 1) {
  634. return;
  635. }
  636. UserCredentials.moveCredentialAfter(
  637. {
  638. realm: realm.realm,
  639. userId: user.id,
  640. credentialId: credentials[index].id,
  641. newPreviousCredentialId: credentials[index + 1].id
  642. },
  643. function() {
  644. $route.reload();
  645. },
  646. function(err) {
  647. Notifications.error($translate.instant('user.credential.move-down.error'));
  648. console.log(err);
  649. });
  650. }
  651. $scope.showData = function(credentialData) {
  652. $modal.open({
  653. templateUrl: resourceUrl + '/partials/modal/user-credential-data.html',
  654. controller: 'UserCredentialsDataModalCtrl',
  655. resolve: {
  656. credentialData: function () {
  657. return credentialData;
  658. }
  659. }
  660. })
  661. }
  662. $scope.realm = realm;
  663. $scope.user = angular.copy(user);
  664. $scope.temporaryPassword = true;
  665. $scope.isTotp = false;
  666. if(!!user.totp){
  667. $scope.isTotp = user.totp;
  668. }
  669. // ID - Name map for required actions. IDs are enum names.
  670. RequiredActions.query({realm: realm.realm}, function(data) {
  671. $scope.userReqActionList = [];
  672. for (var i = 0; i < data.length; i++) {
  673. console.log("listed required action: " + data[i].name);
  674. if (data[i].enabled) {
  675. var item = data[i];
  676. $scope.userReqActionList.push(item);
  677. }
  678. }
  679. });
  680. function loadCredentials() {
  681. UserCredentials.getCredentials({ realm: realm.realm, userId: user.id }, null, function(credentials) {
  682. $scope.credentials = credentials.map(function(c) {
  683. // We de-JSONify the credential data
  684. if (c.credentialData) {
  685. c.credentialData = JSON.parse(c.credentialData);
  686. }
  687. if (c.type == 'password') {
  688. $scope.hasPassword = true;
  689. }
  690. return c;
  691. });
  692. }, function(err) {
  693. Notifications.error($translate.instant('user.credential.fetch.error'));
  694. console.log(err);
  695. });
  696. UserCredentials.getConfiguredUserStorageCredentialTypes({ realm: realm.realm, userId: user.id }, null, function(userStorageCredentialTypes) {
  697. $scope.userStorageCredentialTypes = userStorageCredentialTypes;
  698. $scope.hasPassword = $scope.hasPassword || userStorageCredentialTypes.lastIndexOf("password") > -1;
  699. }, function(err) {
  700. Notifications.error($translate.instant('user.credential.storage.fetch.error'));
  701. console.log(err);
  702. });
  703. }
  704. $scope.resetPassword = function() {
  705. // hit enter without entering both fields - ignore
  706. if (!$scope.passwordAndConfirmPasswordEntered()) return;
  707. if ($scope.pwdChange) {
  708. if ($scope.password != $scope.confirmPassword) {
  709. Notifications.error($translate.instant('user.password.error.not-matching'));
  710. return;
  711. }
  712. }
  713. var msgTitle = ($scope.hasPassword ? $translate.instant('user.password.reset.confirm.title') : $translate.instant('user.password.set.confirm.title'));
  714. var msg = ($scope.hasPassword ? $translate.instant('user.password.reset.confirm.message') : $translate.instant('user.password.set.confirm.message'));
  715. var msgSuccess = ($scope.hasPassword ? $translate.instant('user.password.reset.success') : $translate.instant('user.password.set.success'));
  716. Dialog.confirm(msgTitle, msg, function() {
  717. UserCredentials.resetPassword({ realm: realm.realm, userId: user.id }, { type : "password", value : $scope.password, temporary: $scope.temporaryPassword }, function() {
  718. Notifications.success(msgSuccess);
  719. $scope.password = null;
  720. $scope.confirmPassword = null;
  721. $route.reload();
  722. });
  723. }, function() {
  724. $scope.password = null;
  725. $scope.confirmPassword = null;
  726. });
  727. };
  728. $scope.passwordAndConfirmPasswordEntered = function() {
  729. return $scope.password && $scope.confirmPassword;
  730. }
  731. $scope.disableCredentialTypes = function() {
  732. Dialog.confirm(
  733. $translate.instant('user.credential.disable.confirm.title'),
  734. $translate.instant('user.credential.disable.confirm.message'),
  735. function() {
  736. UserCredentials.disableCredentialTypes({ realm: realm.realm, userId: user.id }, $scope.disableableCredentialTypes, function() {
  737. $route.reload();
  738. Notifications.success($translate.instant('user.credential.disable.confirm.success'));
  739. }, function() {
  740. Notifications.error($translate.instant('user.credential.disable.confirm.error'));
  741. });
  742. });
  743. };
  744. $scope.emailActions = [];
  745. $scope.emailActionsTimeout = TimeUnit2.asUnit(realm.actionTokenGeneratedByAdminLifespan);
  746. $scope.disableableCredentialTypes = [];
  747. $scope.sendExecuteActionsEmail = function() {
  748. if ($scope.changed) {
  749. Dialog.message($translate.instant('user.actions-email.send.pending-changes.title'),
  750. $translate.instant('user.actions-email.send.pending-changes.message'));
  751. return;
  752. }
  753. Dialog.confirm(
  754. $translate.instant('user.actions-email.send.confirm.title'),
  755. $translate.instant('user.actions-email.send.confirm.message'),
  756. function() {
  757. UserExecuteActionsEmail.update({ realm: realm.realm, userId: user.id, lifespan: $scope.emailActionsTimeout.toSeconds() }, $scope.emailActions, function() {
  758. Notifications.success($translate.instant('user.actions-email.send.confirm.success'));
  759. }, function() {
  760. Notifications.error($translate.instant('user.actions-email.send.confirm.error'));
  761. });
  762. });
  763. };
  764. $scope.$watch('user', function() {
  765. if (!angular.equals($scope.user, user)) {
  766. $scope.userChange = true;
  767. } else {
  768. $scope.userChange = false;
  769. }
  770. }, true);
  771. $scope.$watch('password', function() {
  772. if (!!$scope.password){
  773. $scope.pwdChange = true;
  774. } else {
  775. $scope.pwdChange = false;
  776. }
  777. }, true);
  778. $scope.reset = function() {
  779. $scope.password = "";
  780. $scope.confirmPassword = "";
  781. $scope.user = angular.copy(user);
  782. $scope.isTotp = false;
  783. if(!!user.totp){
  784. $scope.isTotp = user.totp;
  785. }
  786. $scope.pwdChange = false;
  787. $scope.userChange = false;
  788. };
  789. });
  790. module.controller('UserCredentialsDataModalCtrl', function($scope, credentialData) {
  791. $scope.credentialData = credentialData;
  792. $scope.keys = function(object) {
  793. return object ? Object.keys(object) : [];
  794. }
  795. });
  796. module.controller('UserFederationCtrl', function($scope, $location, $route, realm, serverInfo, Components, Notifications, Dialog, $translate) {
  797. console.log('UserFederationCtrl ++++****');
  798. $scope.realm = realm;
  799. $scope.providers = serverInfo.componentTypes['org.keycloak.storage.UserStorageProvider'];
  800. $scope.instancesLoaded = false;
  801. if (!$scope.providers) $scope.providers = [];
  802. $scope.addProvider = function(provider) {
  803. console.log('Add provider: ' + provider.id);
  804. $location.url("/create/user-storage/" + realm.realm + "/providers/" + provider.id);
  805. };
  806. $scope.getInstanceLink = function(instance) {
  807. return "/realms/" + realm.realm + "/user-storage/providers/" + instance.providerId + "/" + instance.id;
  808. }
  809. $scope.getInstanceName = function(instance) {
  810. return instance.name;
  811. }
  812. $scope.getInstanceProvider = function(instance) {
  813. return instance.providerId;
  814. }
  815. $scope.isProviderEnabled = function(instance) {
  816. return !instance.config['enabled'] || instance.config['enabled'][0] == 'true';
  817. }
  818. $scope.getInstancePriority = function(instance) {
  819. if (!instance.config['priority']) {
  820. console.log('getInstancePriority is undefined');
  821. return -1;
  822. }
  823. return +instance.config['priority'][0];
  824. }
  825. Components.query({realm: realm.realm,
  826. parent: realm.id,
  827. type: 'org.keycloak.storage.UserStorageProvider'
  828. }, function(data) {
  829. $scope.instances = data;
  830. $scope.instancesLoaded = true;
  831. });
  832. $scope.removeInstance = function(instance) {
  833. Dialog.confirmWithButtonText(
  834. $translate.instant('user.storage.remove.confirm.title', {name: instance.name}),
  835. $translate.instant('user.storage.remove.confirm.message', {name: instance.name}),
  836. $translate.instant('dialogs.delete.confirm'),
  837. function() {
  838. Components.remove({
  839. realm : realm.realm,
  840. componentId : instance.id
  841. }, function() {
  842. $route.reload();
  843. Notifications.success($translate.instant('user.storage.remove.success'));
  844. });
  845. }
  846. );
  847. };
  848. });
  849. module.controller('GenericUserStorageCtrl', function($scope, $location, Notifications, $route, Dialog, realm,
  850. serverInfo, instance, providerId, Components, UserStorageOperations, $translate) {
  851. console.log('GenericUserStorageCtrl');
  852. console.log('providerId: ' + providerId);
  853. $scope.create = !instance.providerId;
  854. console.log('create: ' + $scope.create);
  855. var providers = serverInfo.componentTypes['org.keycloak.storage.UserStorageProvider'];
  856. console.log('providers length ' + providers.length);
  857. var providerFactory = null;
  858. for (var i = 0; i < providers.length; i++) {
  859. var p = providers[i];
  860. console.log('provider: ' + p.id);
  861. if (p.id == providerId) {
  862. $scope.providerFactory = p;
  863. providerFactory = p;
  864. break;
  865. }
  866. }
  867. $scope.showSync = false;
  868. $scope.changed = false;
  869. console.log("providerFactory: " + providerFactory.id);
  870. function initUserStorageSettings() {
  871. if ($scope.create) {
  872. $scope.changed = true;
  873. instance.name = providerFactory.id;
  874. instance.providerId = providerFactory.id;
  875. instance.providerType = 'org.keycloak.storage.UserStorageProvider';
  876. instance.parentId = realm.id;
  877. instance.config = {
  878. };
  879. instance.config['priority'] = ["0"];
  880. instance.config['enabled'] = ["true"];
  881. $scope.fullSyncEnabled = false;
  882. $scope.changedSyncEnabled = false;
  883. if (providerFactory.metadata.synchronizable) {
  884. instance.config['fullSyncPeriod'] = ['-1'];
  885. instance.config['changedSyncPeriod'] = ['-1'];
  886. }
  887. instance.config['cachePolicy'] = ['DEFAULT'];
  888. instance.config['evictionDay'] = [''];
  889. instance.config['evictionHour'] = [''];
  890. instance.config['evictionMinute'] = [''];
  891. instance.config['maxLifespan'] = [''];
  892. if (providerFactory.properties) {
  893. for (var i = 0; i < providerFactory.properties.length; i++) {
  894. var configProperty = providerFactory.properties[i];
  895. if (configProperty.defaultValue) {
  896. instance.config[configProperty.name] = [configProperty.defaultValue];
  897. } else {
  898. instance.config[configProperty.name] = [''];
  899. }
  900. }
  901. }
  902. } else {
  903. $scope.changed = false;
  904. $scope.fullSyncEnabled = (instance.config['fullSyncPeriod'] && instance.config['fullSyncPeriod'][0] > 0);
  905. $scope.changedSyncEnabled = (instance.config['changedSyncPeriod'] && instance.config['changedSyncPeriod'][0]> 0);
  906. if (providerFactory.metadata.synchronizable) {
  907. if (!instance.config['fullSyncPeriod']) {
  908. console.log('setting to -1');
  909. instance.config['fullSyncPeriod'] = ['-1'];
  910. }
  911. if (!instance.config['changedSyncPeriod']) {
  912. console.log('setting to -1');
  913. instance.config['changedSyncPeriod'] = ['-1'];
  914. }
  915. }
  916. if (!instance.config['enabled']) {
  917. instance.config['enabled'] = ['true'];
  918. }
  919. if (!instance.config['cachePolicy']) {
  920. instance.config['cachePolicy'] = ['DEFAULT'];
  921. }
  922. if (!instance.config['evictionDay']) {
  923. instance.config['evictionDay'] = [''];
  924. }
  925. if (!instance.config['evictionHour']) {
  926. instance.config['evictionHour'] = [''];
  927. }
  928. if (!instance.config['evictionMinute']) {
  929. instance.config['evictionMinute'] = [''];
  930. }
  931. if (!instance.config['maxLifespan']) {
  932. instance.config['maxLifespan'] = [''];
  933. }
  934. if (!instance.config['priority']) {
  935. instance.config['priority'] = ['0'];
  936. }
  937. if (providerFactory.properties) {
  938. for (var i = 0; i < providerFactory.properties.length; i++) {
  939. var configProperty = providerFactory.properties[i];
  940. if (!instance.config[configProperty.name]) {
  941. instance.config[configProperty.name] = [''];
  942. }
  943. }
  944. }
  945. }
  946. if (providerFactory.metadata.synchronizable) {
  947. if (instance.config && instance.config['importEnabled']) {
  948. $scope.showSync = instance.config['importEnabled'][0] == 'true';
  949. } else {
  950. $scope.showSync = true;
  951. }
  952. }
  953. }
  954. initUserStorageSettings();
  955. $scope.instance = angular.copy(instance);
  956. $scope.realm = realm;
  957. $scope.$watch('instance', function() {
  958. if (!angular.equals($scope.instance, instance)) {
  959. $scope.changed = true;
  960. }
  961. }, true);
  962. $scope.$watch('fullSyncEnabled', function(newVal, oldVal) {
  963. if (oldVal == newVal) {
  964. return;
  965. }
  966. $scope.instance.config['fullSyncPeriod'][0] = $scope.fullSyncEnabled ? "604800" : "-1";
  967. $scope.changed = true;
  968. });
  969. $scope.$watch('changedSyncEnabled', function(newVal, oldVal) {
  970. if (oldVal == newVal) {
  971. return;
  972. }
  973. $scope.instance.config['changedSyncPeriod'][0] = $scope.changedSyncEnabled ? "86400" : "-1";
  974. $scope.changed = true;
  975. });
  976. $scope.save = function() {
  977. console.log('save provider');
  978. $scope.changed = false;
  979. if ($scope.create) {
  980. console.log('saving new provider');
  981. Components.save({realm: realm.realm}, $scope.instance, function (data, headers) {
  982. var l = headers().location;
  983. var id = l.substring(l.lastIndexOf("/") + 1);
  984. $location.url("/realms/" + realm.realm + "/user-storage/providers/" + $scope.instance.providerId + "/" + id);
  985. Notifications.success($translate.instant('user.storage.create.success'));
  986. });
  987. } else {
  988. console.log('update existing provider');
  989. Components.update({realm: realm.realm,
  990. componentId: instance.id
  991. },
  992. $scope.instance, function () {
  993. $route.reload();
  994. Notifications.success($translate.instant('user.storage.edit.success'));
  995. });
  996. }
  997. };
  998. $scope.reset = function() {
  999. //initUserStorageSettings();
  1000. //$scope.instance = angular.copy(instance);
  1001. $route.reload();
  1002. };
  1003. $scope.cancel = function() {
  1004. console.log('cancel');
  1005. if ($scope.create) {
  1006. $location.url("/realms/" + realm.realm + "/user-federation");
  1007. } else {
  1008. $route.reload();
  1009. }
  1010. };
  1011. $scope.triggerFullSync = function() {
  1012. console.log('GenericCtrl: triggerFullSync');
  1013. triggerSync('triggerFullSync');
  1014. }
  1015. $scope.triggerChangedUsersSync = function() {
  1016. console.log('GenericCtrl: triggerChangedUsersSync');
  1017. triggerSync('triggerChangedUsersSync');
  1018. }
  1019. function triggerSync(action) {
  1020. UserStorageOperations.sync.save({ action: action, realm: $scope.realm.realm, componentId: $scope.instance.id }, {}, function(syncResult) {
  1021. $route.reload();
  1022. Notifications.success($translate.instant('user.storage.sync.success',{status: syncResult.status}));
  1023. }, function() {
  1024. $route.reload();
  1025. Notifications.error($translate.instant('user.storage.sync.error'));
  1026. });
  1027. }
  1028. $scope.removeImportedUsers = function() {
  1029. UserStorageOperations.removeImportedUsers.save({ realm: $scope.realm.realm, componentId: $scope.instance.id }, {}, function(syncResult) {
  1030. $route.reload();
  1031. Notifications.success($translate.instant('user.storage.remove-users.success'));
  1032. }, function() {
  1033. $route.reload();
  1034. Notifications.error($translate.instant('user.storage.remove-users.error'));
  1035. });
  1036. };
  1037. $scope.unlinkUsers = function() {
  1038. UserStorageOperations.unlinkUsers.save({ realm: $scope.realm.realm, componentId: $scope.instance.id }, {}, function(syncResult) {
  1039. $route.reload();
  1040. Notifications.success($translate.instant('user.storage.unlink.success'));
  1041. }, function() {
  1042. $route.reload();
  1043. Notifications.error($translate.instant('user.storage.unlink.error'));
  1044. });
  1045. };
  1046. });
  1047. function removeGroupMember(groups, member) {
  1048. for (var j = 0; j < groups.length; j++) {
  1049. //console.log('checking: ' + groups[j].path);
  1050. if (member.path == groups[j].path) {
  1051. groups.splice(j, 1);
  1052. break;
  1053. }
  1054. if (groups[j].subGroups && groups[j].subGroups.length > 0) {
  1055. //console.log('going into subgroups');
  1056. removeGroupMember(groups[j].subGroups, member);
  1057. }
  1058. }
  1059. }
  1060. module.controller('UserGroupMembershipCtrl', function($scope, $q, realm, user, UserGroupMembership, UserGroupMembershipCount, UserGroupMapping, Notifications, Groups, GroupsCount, ComponentUtils, $translate) {
  1061. $scope.realm = realm;
  1062. $scope.user = user;
  1063. $scope.groupList = [];
  1064. $scope.allGroupMemberships = [];
  1065. $scope.groupMemberships = [];
  1066. $scope.tree = [];
  1067. $scope.membershipTree = [];
  1068. $scope.searchCriteria = '';
  1069. $scope.searchCriteriaMembership = '';
  1070. $scope.currentPage = 1;
  1071. $scope.currentMembershipPage = 1;
  1072. $scope.currentPageInput = $scope.currentPage;
  1073. $scope.currentMembershipPageInput = $scope.currentMembershipPage;
  1074. $scope.pageSize = 20;
  1075. $scope.numberOfPages = 1;
  1076. $scope.numberOfMembershipPages = 1;
  1077. var refreshCompleteUserGroupMembership = function() {
  1078. var queryParams = {
  1079. realm : realm.realm,
  1080. userId: user.id
  1081. };
  1082. var promiseGetCompleteUserGroupMembership = $q.defer();
  1083. UserGroupMembership.query(queryParams, function(entry) {
  1084. promiseGetCompleteUserGroupMembership.resolve(entry);
  1085. }, function() {
  1086. promiseGetCompleteUserGroupMembership.reject($translate.instant('user.groups.fetch.all.error', {params: queryParams}));
  1087. });
  1088. promiseGetCompleteUserGroupMembership.promise.then(function(groups) {
  1089. for (var i = 0; i < groups.length; i++) {
  1090. $scope.allGroupMemberships.push(groups[i]);
  1091. $scope.getGroupClass(groups[i]);
  1092. }
  1093. }, function (failed) {
  1094. Notifications.error(failed);
  1095. });
  1096. return promiseGetCompleteUserGroupMembership.promise;
  1097. };
  1098. var refreshUserGroupMembership = function (search) {
  1099. $scope.currentMembershipPageInput = $scope.currentMembershipPage;
  1100. var first = ($scope.currentMembershipPage * $scope.pageSize) - $scope.pageSize;
  1101. var queryParams = {
  1102. realm : realm.realm,
  1103. userId: user.id,
  1104. first : first,
  1105. max : $scope.pageSize
  1106. };
  1107. var countParams = {
  1108. realm : realm.realm,
  1109. userId: user.id
  1110. };
  1111. var isSearch = function() {
  1112. return angular.isDefined(search) && search !== '';
  1113. };
  1114. if (isSearch()) {
  1115. queryParams.search = search;
  1116. countParams.search = search;
  1117. }
  1118. var promiseGetUserGroupMembership = $q.defer();
  1119. UserGroupMembership.query(queryParams, function(entry) {
  1120. promiseGetUserGroupMembership.resolve(entry);
  1121. }, function() {
  1122. promiseGetUserGroupMembership.reject($translate.instant('user.groups.fetch.error', {params: queryParams}));
  1123. });
  1124. var promiseMembershipCount = $q.defer();
  1125. promiseGetUserGroupMembership.promise.then(function(groups) {
  1126. $scope.groupMemberships = groups;
  1127. UserGroupMembershipCount.query(countParams, function(entry) {
  1128. promiseMembershipCount.resolve(entry);
  1129. }, function() {
  1130. promiseMembershipCount.reject($translate.instant('user.groups.fetch.error', {params: countParams}));
  1131. });
  1132. promiseMembershipCount.promise.then(function(membershipEntry) {
  1133. if(angular.isDefined(membershipEntry.count) && membershipEntry.count > $scope.pageSize) {
  1134. $scope.numberOfMembershipPages = Math.ceil(membershipEntry.count/$scope.pageSize);
  1135. } else {
  1136. $scope.numberOfMembershipPages = 1;
  1137. }
  1138. if (parseInt($scope.currentMembershipPage, 10) > $scope.numberOfMembershipPages) {
  1139. $scope.currentMembershipPage = $scope.numberOfMembershipPages;
  1140. }
  1141. }, function (failed) {
  1142. Notifications.error(failed);
  1143. });
  1144. }, function (failed) {
  1145. Notifications.error(failed);
  1146. });
  1147. return promiseMembershipCount.promise;
  1148. };
  1149. var refreshAvailableGroups = function (search) {
  1150. $scope.currentPageInput = $scope.currentPage;
  1151. var first = ($scope.currentPage * $scope.pageSize) - $scope.pageSize;
  1152. var queryParams = {
  1153. realm : realm.realm,
  1154. first : first,
  1155. max : $scope.pageSize
  1156. };
  1157. var countParams = {
  1158. realm : realm.realm,
  1159. top : 'true'
  1160. };
  1161. if(angular.isDefined(search) && search !== '') {
  1162. queryParams.search = search;
  1163. countParams.search = search;
  1164. }
  1165. var promiseGetGroups = $q.defer();
  1166. Groups.query(queryParams, function(entry) {
  1167. promiseGetGroups.resolve(entry);
  1168. }, function() {
  1169. promiseGetGroups.reject($translate.instant('user.groups.fetch.error', {params: queryParams}));
  1170. });
  1171. var promiseCount = $q.defer();
  1172. promiseGetGroups.promise.then(function(groups) {
  1173. $scope.groupList = ComponentUtils.sortGroups('name', groups);
  1174. GroupsCount.query(countParams, function(entry) {
  1175. promiseCount.resolve(entry);
  1176. }, function() {
  1177. promiseCount.reject($translate.instant('user.groups.fetch.error', {params: countParams}));
  1178. });
  1179. promiseCount.promise.then(function(entry) {
  1180. if(angular.isDefined(entry.count) && entry.count > $scope.pageSize) {
  1181. $scope.numberOfPages = Math.ceil(entry.count/$scope.pageSize);
  1182. } else {
  1183. $scope.numberOfPages = 1;
  1184. }
  1185. }, function (failed) {
  1186. Notifications.error(failed);
  1187. });
  1188. }, function (failed) {
  1189. Notifications.error(failed);
  1190. });
  1191. return promiseCount.promise;
  1192. };
  1193. $scope.clearSearchMembership = function() {
  1194. $scope.searchCriteriaMembership = '';
  1195. if (parseInt($scope.currentMembershipPage, 10) === 1) {
  1196. refreshUserGroupMembership();
  1197. } else {
  1198. $scope.currentMembershipPage = 1;
  1199. }
  1200. };
  1201. $scope.searchGroupMembership = function() {
  1202. if (parseInt($scope.currentMembershipPage, 10) === 1) {
  1203. refreshUserGroupMembership($scope.searchCriteriaMembership);
  1204. } else {
  1205. $scope.currentMembershipPage = 1;
  1206. }
  1207. };
  1208. refreshUserGroupMembership().then(function() {
  1209. refreshAvailableGroups();
  1210. refreshCompleteUserGroupMembership();
  1211. });
  1212. $scope.$watch('currentPage', function(newValue, oldValue) {
  1213. if(parseInt(newValue, 10) !== parseInt(oldValue, 10)) {
  1214. refreshAvailableGroups($scope.searchCriteria);
  1215. }
  1216. });
  1217. $scope.$watch('currentMembershipPage', function(newValue, oldValue) {
  1218. if(parseInt(newValue, 10) !== parseInt(oldValue, 10)) {
  1219. refreshUserGroupMembership($scope.searchCriteriaMembership);
  1220. }
  1221. });
  1222. $scope.clearSearch = function() {
  1223. $scope.searchCriteria = '';
  1224. if (parseInt($scope.currentPage, 10) === 1) {
  1225. refreshAvailableGroups();
  1226. } else {
  1227. $scope.currentPage = 1;
  1228. }
  1229. };
  1230. $scope.searchGroup = function() {
  1231. if (parseInt($scope.currentPage, 10) === 1) {
  1232. refreshAvailableGroups($scope.searchCriteria);
  1233. } else {
  1234. $scope.currentPage = 1;
  1235. }
  1236. };
  1237. $scope.joinGroup = function() {
  1238. if (!$scope.tree.currentNode) {
  1239. Notifications.error($translate.instant('user.groups.join.error.no-group-selected'));
  1240. return;
  1241. }
  1242. if (isMember($scope.tree.currentNode)) {
  1243. Notifications.error($translate.instant('user.groups.join.error.already-added'));
  1244. return;
  1245. }
  1246. UserGroupMapping.update({realm: realm.realm, userId: user.id, groupId: $scope.tree.currentNode.id}, function() {
  1247. $scope.allGroupMemberships.push($scope.tree.currentNode);
  1248. refreshUserGroupMembership($scope.searchCriteriaMembership);
  1249. Notifications.success($translate.instant('user.groups.join.success'));
  1250. });
  1251. };
  1252. $scope.leaveGroup = function() {
  1253. if (!$scope.membershipTree.currentNode) {
  1254. Notifications.error($translate.instant('user.groups.leave.error.no-group-selected'));
  1255. return;
  1256. }
  1257. UserGroupMapping.remove({realm: realm.realm, userId: user.id, groupId: $scope.membershipTree.currentNode.id}, function () {
  1258. removeGroupMember($scope.allGroupMemberships, $scope.membershipTree.currentNode);
  1259. refreshUserGroupMembership($scope.searchCriteriaMembership);
  1260. Notifications.success($translate.instant('user.groups.leave.success'));
  1261. });
  1262. };
  1263. var isLeaf = function(node) {
  1264. return node.id !== 'realm' && (!node.subGroups || node.subGroups.length === 0);
  1265. };
  1266. var isMember = function(node) {
  1267. for (var i = 0; i < $scope.allGroupMemberships.length; i++) {
  1268. var member = $scope.allGroupMemberships[i];
  1269. if (node.id === member.id) {
  1270. return true;
  1271. }
  1272. }
  1273. return false;
  1274. };
  1275. $scope.getGroupClass = function(node) {
  1276. if (node.id == "realm") {
  1277. return 'pficon pficon-users';
  1278. }
  1279. if (isMember(node)) {
  1280. return 'normal deactivate';
  1281. }
  1282. if (isLeaf(node)) {
  1283. return 'normal';
  1284. }
  1285. if (node.subGroups.length && node.collapsed) return 'collapsed';
  1286. if (node.subGroups.length && !node.collapsed) return 'expanded';
  1287. return 'collapsed';
  1288. }
  1289. $scope.getSelectedClass = function(node) {
  1290. if (node.selected) {
  1291. if (isMember(node)) {
  1292. return "deactivate_selected";
  1293. } else {
  1294. return 'selected';
  1295. }
  1296. } else if ($scope.cutNode && $scope.cutNode.id === node.id) {
  1297. return 'cut';
  1298. }
  1299. return undefined;
  1300. }
  1301. });
  1302. module.controller('LDAPUserStorageCtrl', function($scope, $location, Notifications, $route, Dialog, realm,
  1303. serverInfo, instance, Components, UserStorageOperations,
  1304. RealmLDAPConnectionTester, $http) {
  1305. console.log('LDAPUserStorageCtrl');
  1306. var providerId = 'ldap';
  1307. console.log('providerId: ' + providerId);
  1308. $scope.create = !instance.providerId;
  1309. console.log('create: ' + $scope.create);
  1310. var providers = serverInfo.componentTypes['org.keycloak.storage.UserStorageProvider'];
  1311. console.log('providers length ' + providers.length);
  1312. var providerFactory = null;
  1313. for (var i = 0; i < providers.length; i++) {
  1314. var p = providers[i];
  1315. console.log('provider: ' + p.id);
  1316. if (p.id == providerId) {
  1317. $scope.providerFactory = p;
  1318. providerFactory = p;
  1319. break;
  1320. }
  1321. }
  1322. $scope.provider = instance;
  1323. $scope.showSync = false;
  1324. if (serverInfo.profileInfo.name == 'community') {
  1325. $scope.ldapVendors = [
  1326. {"id": "ad", "name": "Active Directory"},
  1327. {"id": "rhds", "name": "Red Hat Directory Server"},
  1328. {"id": "tivoli", "name": "Tivoli"},
  1329. {"id": "edirectory", "name": "Novell eDirectory"},
  1330. {"id": "other", "name": "Other"}
  1331. ];
  1332. } else {
  1333. $scope.ldapVendors = [
  1334. {"id": "ad", "name": "Active Directory"},
  1335. {"id": "rhds", "name": "Red Hat Directory Server"}
  1336. ];
  1337. }
  1338. $scope.authTypes = [
  1339. { "id": "none", "name": "none" },
  1340. { "id": "simple", "name": "simple" }
  1341. ];
  1342. $scope.searchScopes = [
  1343. { "id": "1", "name": "One Level" },
  1344. { "id": "2", "name": "Subtree" }
  1345. ];
  1346. $scope.useTruststoreOptions = [
  1347. { "id": "always", "name": "Always" },
  1348. { "id": "ldapsOnly", "name": "Only for ldaps" },
  1349. { "id": "never", "name": "Never" }
  1350. ];
  1351. var DEFAULT_BATCH_SIZE = "1000";
  1352. console.log("providerFactory: " + providerFactory.id);
  1353. $scope.changed = false;
  1354. function initUserStorageSettings() {
  1355. if ($scope.create) {
  1356. $scope.changed = true;
  1357. instance.name = 'ldap';
  1358. instance.providerId = 'ldap';
  1359. instance.providerType = 'org.keycloak.storage.UserStorageProvider';
  1360. instance.parentId = realm.id;
  1361. instance.config = {
  1362. };
  1363. instance.config['enabled'] = ["true"];
  1364. instance.config['priority'] = ["0"];
  1365. $scope.fullSyncEnabled = false;
  1366. $scope.changedSyncEnabled = false;
  1367. instance.config['fullSyncPeriod'] = ['-1'];
  1368. instance.config['changedSyncPeriod'] = ['-1'];
  1369. instance.config['cachePolicy'] = ['DEFAULT'];
  1370. instance.config['evictionDay'] = [''];
  1371. instance.config['evictionHour'] = [''];
  1372. instance.config['evictionMinute'] = [''];
  1373. instance.config['maxLifespan'] = [''];
  1374. instance.config['batchSizeForSync'] = [DEFAULT_BATCH_SIZE];
  1375. //instance.config['importEnabled'] = ['true'];
  1376. if (providerFactory.properties) {
  1377. for (var i = 0; i < providerFactory.properties.length; i++) {
  1378. var configProperty = providerFactory.properties[i];
  1379. if (configProperty.defaultValue) {
  1380. instance.config[configProperty.name] = [configProperty.defaultValue];
  1381. } else {
  1382. instance.config[configProperty.name] = [''];
  1383. }
  1384. }
  1385. }
  1386. } else {
  1387. $scope.changed = false;
  1388. $scope.fullSyncEnabled = (instance.config['fullSyncPeriod'] && instance.config['fullSyncPeriod'][0] > 0);
  1389. $scope.changedSyncEnabled = (instance.config['changedSyncPeriod'] && instance.config['changedSyncPeriod'][0]> 0);
  1390. if (!instance.config['fullSyncPeriod']) {
  1391. console.log('setting to -1');
  1392. instance.config['fullSyncPeriod'] = ['-1'];
  1393. }
  1394. if (!instance.config['enabled']) {
  1395. instance.config['enabled'] = ['true'];
  1396. }
  1397. if (!instance.config['changedSyncPeriod']) {
  1398. console.log('setting to -1');
  1399. instance.config['changedSyncPeriod'] = ['-1'];
  1400. }
  1401. if (!instance.config['cachePolicy']) {
  1402. instance.config['cachePolicy'] = ['DEFAULT'];
  1403. }
  1404. if (!instance.config['evictionDay']) {
  1405. instance.config['evictionDay'] = [''];
  1406. }
  1407. if (!instance.config['evictionHour']) {
  1408. instance.config['evictionHour'] = [''];
  1409. }
  1410. if (!instance.config['evictionMinute']) {
  1411. instance.config['evictionMinute'] = [''];
  1412. }
  1413. if (!instance.config['maxLifespan']) {
  1414. instance.config['maxLifespan'] = [''];
  1415. }
  1416. if (!instance.config['priority']) {
  1417. instance.config['priority'] = ['0'];
  1418. }
  1419. if (!instance.config['importEnabled']) {
  1420. instance.config['importEnabled'] = ['true'];
  1421. }
  1422. if (providerFactory.properties) {
  1423. for (var i = 0; i < providerFactory.properties.length; i++) {
  1424. var configProperty = providerFactory.properties[i];
  1425. if (!instance.config[configProperty.name]) {
  1426. if (configProperty.defaultValue) {
  1427. instance.config[configProperty.name] = [configProperty.defaultValue];
  1428. } else {
  1429. instance.config[configProperty.name] = [''];
  1430. }
  1431. }
  1432. }
  1433. }
  1434. for (var i=0 ; i<$scope.ldapVendors.length ; i++) {
  1435. if ($scope.ldapVendors[i].id === instance.config['vendor'][0]) {
  1436. $scope.vendorName = $scope.ldapVendors[i].name;
  1437. }
  1438. };
  1439. }
  1440. if (instance.config && instance.config['importEnabled']) {
  1441. $scope.showSync = instance.config['importEnabled'][0] == 'true';
  1442. } else {
  1443. $scope.showSync = true;
  1444. }
  1445. $scope.lastVendor = instance.config['vendor'][0];
  1446. }
  1447. initUserStorageSettings();
  1448. $scope.instance = angular.copy(instance);
  1449. $scope.realm = realm;
  1450. $scope.$watch('instance', function() {
  1451. if (!angular.equals($scope.instance, instance)) {
  1452. $scope.changed = true;
  1453. }
  1454. if (!angular.equals($scope.instance.config['vendor'][0], $scope.lastVendor)) {
  1455. console.log("LDAP vendor changed. Previous=" + $scope.lastVendor + " New=" + $scope.instance.config['vendor'][0]);
  1456. $scope.lastVendor = $scope.instance.config['vendor'][0];
  1457. if ($scope.lastVendor === "ad") {
  1458. $scope.instance.config['usernameLDAPAttribute'][0] = "cn";
  1459. $scope.instance.config['userObjectClasses'][0] = "person, organizationalPerson, user";
  1460. } else {
  1461. $scope.instance.config['usernameLDAPAttribute'][0] = "uid";
  1462. $scope.instance.config['userObjectClasses'][0] = "inetOrgPerson, organizationalPerson";
  1463. }
  1464. $scope.instance.config['rdnLDAPAttribute'][0] = $scope.instance.config['usernameLDAPAttribute'][0];
  1465. var vendorToUUID = {
  1466. rhds: "nsuniqueid",
  1467. tivoli: "uniqueidentifier",
  1468. edirectory: "guid",
  1469. ad: "objectGUID",
  1470. other: "entryUUID"
  1471. };
  1472. $scope.instance.config['uuidLDAPAttribute'][0] = vendorToUUID[$scope.lastVendor];
  1473. }
  1474. }, true);
  1475. $scope.$watch('fullSyncEnabled', function(newVal, oldVal) {
  1476. if (oldVal == newVal) {
  1477. return;
  1478. }
  1479. $scope.instance.config['fullSyncPeriod'][0] = $scope.fullSyncEnabled ? "604800" : "-1";
  1480. $scope.changed = true;
  1481. });
  1482. $scope.$watch('changedSyncEnabled', function(newVal, oldVal) {
  1483. if (oldVal == newVal) {
  1484. return;
  1485. }
  1486. $scope.instance.config['changedSyncPeriod'][0] = $scope.changedSyncEnabled ? "86400" : "-1";
  1487. $scope.changed = true;
  1488. });
  1489. $scope.save = function() {
  1490. $scope.changed = false;
  1491. if (!$scope.instance.config['batchSizeForSync'] || !parseInt($scope.instance.config['batchSizeForSync'][0])) {
  1492. $scope.instance.config['batchSizeForSync'] = [ DEFAULT_BATCH_SIZE ];
  1493. } else {
  1494. $scope.instance.config['batchSizeForSync'][0] = parseInt($scope.instance.config.batchSizeForSync).toString();
  1495. }
  1496. if ($scope.create) {
  1497. Components.save({realm: realm.realm}, $scope.instance, function (data, headers) {
  1498. var l = headers().location;
  1499. var id = l.substring(l.lastIndexOf("/") + 1);
  1500. $location.url("/realms/" + realm.realm + "/user-storage/providers/" + $scope.instance.providerId + "/" + id);
  1501. Notifications.success("The provider has been created.");
  1502. });
  1503. } else {
  1504. Components.update({realm: realm.realm,
  1505. componentId: instance.id
  1506. },
  1507. $scope.instance, function () {
  1508. $route.reload();
  1509. Notifications.success("The provider has been updated.");
  1510. });
  1511. }
  1512. };
  1513. $scope.reset = function() {
  1514. $route.reload();
  1515. };
  1516. $scope.cancel = function() {
  1517. if ($scope.create) {
  1518. $location.url("/realms/" + realm.realm + "/user-federation");
  1519. } else {
  1520. $route.reload();
  1521. }
  1522. };
  1523. $scope.triggerFullSync = function() {
  1524. console.log('GenericCtrl: triggerFullSync');
  1525. triggerSync('triggerFullSync');
  1526. }
  1527. $scope.triggerChangedUsersSync = function() {
  1528. console.log('GenericCtrl: triggerChangedUsersSync');
  1529. triggerSync('triggerChangedUsersSync');
  1530. }
  1531. function triggerSync(action) {
  1532. UserStorageOperations.sync.save({ action: action, realm: $scope.realm.realm, componentId: $scope.instance.id }, {}, function(syncResult) {
  1533. $route.reload();
  1534. Notifications.success("Sync of users finished successfully. " + syncResult.status);
  1535. }, function() {
  1536. $route.reload();
  1537. Notifications.error("Error during sync of users");
  1538. });
  1539. }
  1540. $scope.removeImportedUsers = function() {
  1541. UserStorageOperations.removeImportedUsers.save({ realm: $scope.realm.realm, componentId: $scope.instance.id }, {}, function(syncResult) {
  1542. $route.reload();
  1543. Notifications.success("Remove imported users finished successfully. ");
  1544. }, function() {
  1545. $route.reload();
  1546. Notifications.error("Error during remove");
  1547. });
  1548. };
  1549. $scope.unlinkUsers = function() {
  1550. UserStorageOperations.unlinkUsers.save({ realm: $scope.realm.realm, componentId: $scope.instance.id }, {}, function(syncResult) {
  1551. $route.reload();
  1552. Notifications.success("Unlink of users finished successfully. ");
  1553. }, function() {
  1554. $route.reload();
  1555. Notifications.error("Error during unlink");
  1556. });
  1557. };
  1558. var initConnectionTest = function(testAction, ldapConfig) {
  1559. return {
  1560. action: testAction,
  1561. connectionUrl: ldapConfig.connectionUrl && ldapConfig.connectionUrl[0],
  1562. authType: ldapConfig.authType && ldapConfig.authType[0],
  1563. bindDn: ldapConfig.bindDn && ldapConfig.bindDn[0],
  1564. bindCredential: ldapConfig.bindCredential && ldapConfig.bindCredential[0],
  1565. useTruststoreSpi: ldapConfig.useTruststoreSpi && ldapConfig.useTruststoreSpi[0],
  1566. connectionTimeout: ldapConfig.connectionTimeout && ldapConfig.connectionTimeout[0],
  1567. startTls: ldapConfig.startTls && ldapConfig.startTls[0],
  1568. componentId: instance.id
  1569. };
  1570. };
  1571. $scope.testConnection = function() {
  1572. console.log('LDAPCtrl: testConnection');
  1573. RealmLDAPConnectionTester.save({realm: realm.realm}, initConnectionTest("testConnection", $scope.instance.config), function() {
  1574. Notifications.success("LDAP connection successful.");
  1575. }, function() {
  1576. Notifications.error("Error when trying to connect to LDAP. See server.log for details.");
  1577. });
  1578. }
  1579. $scope.testAuthentication = function() {
  1580. console.log('LDAPCtrl: testAuthentication');
  1581. RealmLDAPConnectionTester.save({realm: realm.realm}, initConnectionTest("testAuthentication", $scope.instance.config), function() {
  1582. Notifications.success("LDAP authentication successful.");
  1583. }, function() {
  1584. Notifications.error("LDAP authentication failed. See server.log for details");
  1585. });
  1586. }
  1587. $scope.queryAndSetLdapSupportedExtensions = function() {
  1588. console.log('LDAPCtrl: getLdapSupportedExtensions');
  1589. const PASSWORD_MODIFY_OID = '1.3.6.1.4.1.4203.1.11.1';
  1590. $http.post(
  1591. authUrl + '/admin/realms/' + realm.realm + '/ldap-server-capabilities',
  1592. initConnectionTest("queryServerCapabilities", $scope.instance.config)).then(
  1593. function(response) {
  1594. Notifications.success("LDAP supported extensions successfully requested.");
  1595. const ldapOids = response.data;
  1596. if (angular.isArray(ldapOids)) {
  1597. const passwordModifyOid = ldapOids.filter(function(ldapOid) { return ldapOid.oid === PASSWORD_MODIFY_OID; });
  1598. $scope.instance.config['usePasswordModifyExtendedOp'][0] = (passwordModifyOid.length > 0).toString();
  1599. }
  1600. },
  1601. function() {
  1602. Notifications.error("Error when trying to request supported extensions of LDAP. See server.log for details.");
  1603. });
  1604. }
  1605. });
  1606. module.controller('LDAPTabCtrl', function(Dialog, $scope, Current, Notifications, $location) {
  1607. $scope.removeUserFederation = function() {
  1608. Dialog.confirmDelete($scope.instance.name, 'ldap provider', function() {
  1609. $scope.instance.$remove({
  1610. realm : Current.realm.realm,
  1611. componentId : $scope.instance.id
  1612. }, function() {
  1613. $location.url("/realms/" + Current.realm.realm + "/user-federation");
  1614. Notifications.success("The provider has been deleted.");
  1615. });
  1616. });
  1617. };
  1618. });
  1619. module.controller('LDAPMapperListCtrl', function($scope, $location, Notifications, $route, Dialog, realm, provider, mappers) {
  1620. console.log('LDAPMapperListCtrl');
  1621. $scope.realm = realm;
  1622. $scope.provider = provider;
  1623. $scope.instance = provider;
  1624. $scope.mappers = mappers;
  1625. });
  1626. module.controller('LDAPMapperCtrl', function($scope, $route, realm, provider, mapperTypes, mapper, clients, Components, LDAPMapperSync, Notifications, Dialog, $location) {
  1627. console.log('LDAPMapperCtrl');
  1628. $scope.realm = realm;
  1629. $scope.provider = provider;
  1630. $scope.clients = clients;
  1631. $scope.create = false;
  1632. $scope.changed = false;
  1633. for (var i = 0; i < mapperTypes.length; i++) {
  1634. console.log('mapper.providerId: ' + mapper.providerId);
  1635. console.log('mapperTypes[i].id ' + mapperTypes[i].id);
  1636. if (mapperTypes[i].id == mapper.providerId) {
  1637. $scope.mapperType = mapperTypes[i];
  1638. break;
  1639. }
  1640. }
  1641. if ($scope.mapperType.properties) {
  1642. for (var i = 0; i < $scope.mapperType.properties.length; i++) {
  1643. var configProperty = $scope.mapperType.properties[i];
  1644. if (!mapper.config[configProperty.name]) {
  1645. if (configProperty.defaultValue) {
  1646. mapper.config[configProperty.name] = [configProperty.defaultValue];
  1647. } else {
  1648. mapper.config[configProperty.name] = [''];
  1649. }
  1650. }
  1651. }
  1652. }
  1653. $scope.mapper = angular.copy(mapper);
  1654. $scope.$watch('mapper', function() {
  1655. if (!angular.equals($scope.mapper, mapper)) {
  1656. $scope.changed = true;
  1657. }
  1658. }, true);
  1659. $scope.save = function() {
  1660. Components.update({realm: realm.realm,
  1661. componentId: mapper.id
  1662. },
  1663. $scope.mapper, function () {
  1664. $route.reload();
  1665. Notifications.success("The mapper has been updated.");
  1666. });
  1667. };
  1668. $scope.reset = function() {
  1669. $scope.mapper = angular.copy(mapper);
  1670. $scope.changed = false;
  1671. };
  1672. $scope.remove = function() {
  1673. Dialog.confirmDelete($scope.mapper.name, 'ldap mapper', function() {
  1674. Components.remove({
  1675. realm : realm.realm,
  1676. componentId : mapper.id
  1677. }, function() {
  1678. $location.url("/realms/" + realm.realm + '/ldap-mappers/' + provider.id);
  1679. Notifications.success("The provider has been deleted.");
  1680. });
  1681. });
  1682. };
  1683. $scope.triggerFedToKeycloakSync = function() {
  1684. triggerMapperSync("fedToKeycloak")
  1685. }
  1686. $scope.triggerKeycloakToFedSync = function() {
  1687. triggerMapperSync("keycloakToFed");
  1688. }
  1689. function triggerMapperSync(direction) {
  1690. LDAPMapperSync.save({ direction: direction, realm: realm.realm, parentId: provider.id, mapperId : $scope.mapper.id }, {}, function(syncResult) {
  1691. Notifications.success("Data synced successfully. " + syncResult.status);
  1692. }, function(error) {
  1693. Notifications.error(error.data.errorMessage);
  1694. });
  1695. }
  1696. });
  1697. module.controller('LDAPMapperCreateCtrl', function($scope, realm, provider, mapperTypes, clients, Components, Notifications, Dialog, $location) {
  1698. console.log('LDAPMapperCreateCtrl');
  1699. $scope.realm = realm;
  1700. $scope.provider = provider;
  1701. $scope.clients = clients;
  1702. $scope.create = true;
  1703. $scope.mapper = { config: {}};
  1704. $scope.mapperTypes = mapperTypes;
  1705. $scope.mapperType = null;
  1706. $scope.changed = true;
  1707. $scope.$watch('mapperType', function() {
  1708. if ($scope.mapperType != null) {
  1709. $scope.mapper.config = {};
  1710. if ($scope.mapperType.properties) {
  1711. for (var i = 0; i < $scope.mapperType.properties.length; i++) {
  1712. var configProperty = $scope.mapperType.properties[i];
  1713. if (!$scope.mapper.config[configProperty.name]) {
  1714. if (configProperty.defaultValue) {
  1715. $scope.mapper.config[configProperty.name] = [configProperty.defaultValue];
  1716. } else {
  1717. $scope.mapper.config[configProperty.name] = [''];
  1718. }
  1719. }
  1720. }
  1721. }
  1722. }
  1723. }, true);
  1724. $scope.save = function() {
  1725. if ($scope.mapperType == null) {
  1726. Notifications.error("You need to select mapper type!");
  1727. return;
  1728. }
  1729. $scope.mapper.providerId = $scope.mapperType.id;
  1730. $scope.mapper.providerType = 'org.keycloak.storage.ldap.mappers.LDAPStorageMapper';
  1731. $scope.mapper.parentId = provider.id;
  1732. if ($scope.mapper.config && $scope.mapper.config["role"] && !Array.isArray($scope.mapper.config["role"])) {
  1733. $scope.mapper.config["role"] = [$scope.mapper.config["role"]];
  1734. }
  1735. Components.save({realm: realm.realm}, $scope.mapper, function (data, headers) {
  1736. var l = headers().location;
  1737. var id = l.substring(l.lastIndexOf("/") + 1);
  1738. $location.url("/realms/" + realm.realm + "/ldap-mappers/" + $scope.mapper.parentId + "/mappers/" + id);
  1739. Notifications.success("The mapper has been created.");
  1740. });
  1741. };
  1742. $scope.reset = function() {
  1743. $location.url("/realms/" + realm.realm + '/ldap-mappers/' + provider.id);
  1744. };
  1745. });