router.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984
  1. /**
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. var misc = require('utils/misc');
  19. var App = require('app');
  20. App.WizardRoute = Em.Route.extend({
  21. gotoStep0: Em.Router.transitionTo('step0'),
  22. gotoStep1: Em.Router.transitionTo('step1'),
  23. gotoStep2: Em.Router.transitionTo('step2'),
  24. gotoStep3: Em.Router.transitionTo('step3'),
  25. gotoStep4: Em.Router.transitionTo('step4'),
  26. gotoStep5: Em.Router.transitionTo('step5'),
  27. gotoStep6: Em.Router.transitionTo('step6'),
  28. gotoStep7: Em.Router.transitionTo('step7'),
  29. gotoStep8: Em.Router.transitionTo('step8'),
  30. gotoStep9: Em.Router.transitionTo('step9'),
  31. gotoStep10: Em.Router.transitionTo('step10'),
  32. isRoutable: function() {
  33. return typeof this.get('route') === 'string' && App.router.get('loggedIn');
  34. }.property('App.router.loggedIn')
  35. });
  36. /**
  37. * This route executes "back" and "next" handler on the next run-loop
  38. * Reason: It's done like this, because in general transitions have highest priority in the Ember run-loop
  39. * So, CP's and observers for <code>App.router.backBtnClickInProgress</code> and <code>App.router.nextBtnClickInProgress</code>
  40. * will be triggered after "back" or "next" are complete and not before them.
  41. * It's more important for "back", because usually it doesn't do any requests that may cause a little delay for run loops
  42. * <code>Em.run.next</code> is used to avoid this
  43. *
  44. * Example:
  45. * <pre>
  46. * App.Step2Route = App.StepRoute.extend({
  47. *
  48. * route: '/step2',
  49. *
  50. * connectOutlets: function (router, context) {
  51. * // some code
  52. * },
  53. *
  54. * nextTransition: function (router) {
  55. * router.transitionTo('step3');
  56. * },
  57. *
  58. * backTransition: function (router) {
  59. * router.transitionTo('step1');
  60. * }
  61. *
  62. * });
  63. * </pre>
  64. * In this case both <code>transitionTo</code> will be executed in the next run loop after loop where "next" or "back" were called
  65. * <b>IMPORTANT!</b> Flags <code>App.router.backBtnClickInProgress</code> and <code>App.router.nextBtnClickInProgress</code> are set to <code>true</code>
  66. * in the "back" and "next". Be sure to set them <code>false</code> when needed
  67. *
  68. * @type {Em.Route}
  69. */
  70. App.StepRoute = Em.Route.extend({
  71. /**
  72. * @type {Function}
  73. */
  74. backTransition: Em.K,
  75. /**
  76. * @type {Function}
  77. */
  78. nextTransition: Em.K,
  79. /**
  80. * Default "Back"-action
  81. * Execute <code>backTransition</code> once
  82. *
  83. * @param {Em.Router} router
  84. */
  85. back: function (router) {
  86. if (App.get('router.btnClickInProgress')) {
  87. return;
  88. }
  89. App.set('router.backBtnClickInProgress', true);
  90. var self = this;
  91. Em.run.next(function () {
  92. Em.tryInvoke(self, 'backTransition', [router]);
  93. })
  94. },
  95. /**
  96. * Default "Next"-action
  97. * Execute <code>nextTransition</code> once
  98. *
  99. * @param {Em.Router} router
  100. */
  101. next: function (router) {
  102. if (App.get('router.btnClickInProgress')) {
  103. return;
  104. }
  105. App.set('router.nextBtnClickInProgress', true);
  106. var self = this;
  107. Em.run.next(function () {
  108. Em.tryInvoke(self, 'nextTransition', [router]);
  109. })
  110. }
  111. });
  112. App.Router = Em.Router.extend({
  113. enableLogging: true,
  114. isFwdNavigation: true,
  115. backBtnForHigherStep: false,
  116. /**
  117. * Checks if Back button is clicked
  118. * Set to default value on the <code>App.WizardController.connectOutlet</code>
  119. *
  120. * @type {boolean}
  121. * @default false
  122. */
  123. backBtnClickInProgress: false,
  124. /**
  125. * Checks if Next button is clicked
  126. * Set to default value on the <code>App.WizardController.connectOutlet</code>
  127. *
  128. * @type {boolean}
  129. * @default false
  130. */
  131. nextBtnClickInProgress: false,
  132. /**
  133. * Checks if Next or Back button is clicked
  134. * Used in the <code>App.StepRoute</code>-instances to avoid "next"/"back" double-clicks
  135. *
  136. * @type {boolean}
  137. * @default false
  138. */
  139. btnClickInProgress: Em.computed.or('backBtnClickInProgress', 'nextBtnClickInProgress'),
  140. /**
  141. * Path for local login page. This page will be always accessible without
  142. * redirect to auth server different from ambari-server. Used in some types of
  143. * authorizations like knox sso.
  144. *
  145. * @type {string}
  146. */
  147. localUserAuthUrl: '/login/local',
  148. /**
  149. * LocalStorage property <code>redirectsCount</code> from <code>tmp</code> namespace
  150. * will be incremented by each redirect action performed by UI and reset on success login.
  151. * <code>redirectsLimitCount</code> determines maximum redirect tries. When redirects count overflow
  152. * then something goes wrong and we have to inform user about the problem.
  153. *
  154. * @type {number}
  155. */
  156. redirectsLimitCount: 0,
  157. /**
  158. * Is true, if cluster.provisioning_state is equal to 'INSTALLED'
  159. * @type {Boolean}
  160. */
  161. clusterInstallCompleted: false,
  162. /**
  163. * user prefered path to route
  164. */
  165. preferedPath: null,
  166. setNavigationFlow: function (step) {
  167. var matches = step.match(/\d+$/);
  168. var newStep;
  169. if (matches) {
  170. newStep = parseInt(matches[0], 10);
  171. }
  172. var previousStep = parseInt(this.getInstallerCurrentStep(), 10);
  173. this.set('isFwdNavigation', newStep >= previousStep);
  174. },
  175. clearAllSteps: function () {
  176. this.get('installerController').clear();
  177. this.get('addHostController').clear();
  178. this.get('addServiceController').clear();
  179. this.get('backgroundOperationsController').clear();
  180. for (var i = 1; i < 11; i++) {
  181. this.set('wizardStep' + i + 'Controller.hasSubmitted', false);
  182. this.set('wizardStep' + i + 'Controller.isDisabled', true);
  183. }
  184. },
  185. /**
  186. * Temporary fix for getting cluster name
  187. * @return {*}
  188. */
  189. getClusterName: function () {
  190. return App.router.get('clusterController').get('clusterName');
  191. },
  192. /**
  193. * Get current step of Installer wizard
  194. * @return {*}
  195. */
  196. getInstallerCurrentStep: function () {
  197. return this.getWizardCurrentStep('installer');
  198. },
  199. /**
  200. * Get current step for <code>wizardType</code> wizard
  201. * @param wizardType one of <code>installer</code>, <code>addHost</code>, <code>addServices</code>
  202. */
  203. getWizardCurrentStep: function (wizardType) {
  204. var currentStep = App.db.getWizardCurrentStep(wizardType);
  205. if (!currentStep) {
  206. currentStep = wizardType === 'installer' ? '0' : '1';
  207. }
  208. return currentStep;
  209. },
  210. /**
  211. * @type {boolean}
  212. */
  213. loggedIn: App.db.getAuthenticated(),
  214. loginName: function() {
  215. return this.getLoginName();
  216. }.property('loggedIn'),
  217. displayLoginName: Em.computed.truncate('loginName', 10, 10),
  218. getAuthenticated: function () {
  219. var dfd = $.Deferred();
  220. var self = this;
  221. var auth = App.db.getAuthenticated();
  222. App.ajax.send({
  223. name: 'router.login.clusters',
  224. sender: this,
  225. success: 'onAuthenticationSuccess',
  226. error: 'onAuthenticationError'
  227. }).complete(function (xhr) {
  228. if (xhr.isResolved()) {
  229. // if server knows the user and user authenticated by UI
  230. if (auth) {
  231. dfd.resolve(self.get('loggedIn'));
  232. // if server knows the user but UI don't, check the response header
  233. // and try to authorize
  234. } else if (xhr.getResponseHeader('User')) {
  235. var user = xhr.getResponseHeader('User');
  236. App.ajax.send({
  237. name: 'router.login',
  238. sender: self,
  239. data: {
  240. usr: user,
  241. loginName: encodeURIComponent(user)
  242. },
  243. success: 'loginSuccessCallback',
  244. error: 'loginErrorCallback'
  245. }).then(function() {
  246. dfd.resolve(true);
  247. });
  248. } else {
  249. self.setAuthenticated(false);
  250. dfd.resolve(false);
  251. }
  252. } else {
  253. //if provisioning state unreachable then consider user as unauthenticated
  254. self.setAuthenticated(false);
  255. dfd.resolve(false);
  256. }
  257. });
  258. return dfd.promise();
  259. },
  260. /**
  261. * Response for <code>/clusters?fields=Clusters/provisioning_state</code>
  262. * @type {null|object}
  263. */
  264. clusterData: null,
  265. onAuthenticationSuccess: function (data) {
  266. if (App.db.getAuthenticated() === true) {
  267. this.set('clusterData', data);
  268. this.setAuthenticated(true);
  269. if (data.items.length) {
  270. this.setClusterInstalled(data);
  271. }
  272. }
  273. },
  274. /**
  275. * If authentication failed, need to check for jwt auth url
  276. * and redirect user if current location is not <code>localUserAuthUrl</code>
  277. *
  278. * @param {?object} data
  279. */
  280. onAuthenticationError: function (data) {
  281. if (data.status === 403) {
  282. try {
  283. var responseJson = JSON.parse(data.responseText);
  284. if (responseJson.jwtProviderUrl && this.get('location.lastSetURL') !== this.get('localUserAuthUrl')) {
  285. this.redirectByURL(responseJson.jwtProviderUrl + encodeURIComponent(this.getCurrentLocationUrl()));
  286. }
  287. } catch (e) {
  288. } finally {
  289. this.setAuthenticated(false);
  290. }
  291. } else if (data.status >= 500) {
  292. this.setAuthenticated(false);
  293. this.loginErrorCallback(data);
  294. }
  295. },
  296. setAuthenticated: function (authenticated) {
  297. App.db.setAuthenticated(authenticated);
  298. this.set('loggedIn', authenticated);
  299. },
  300. getLoginName: function () {
  301. return App.db.getLoginName();
  302. },
  303. setLoginName: function (loginName) {
  304. App.db.setLoginName(loginName);
  305. },
  306. /**
  307. * Set user model to local storage
  308. * @param user
  309. */
  310. setUser: function (user) {
  311. App.db.setUser(user);
  312. },
  313. /**
  314. * Get user model from local storage
  315. * @return {*}
  316. */
  317. getUser: function () {
  318. return App.db.getUser();
  319. },
  320. setUserLoggedIn: function(userName) {
  321. this.setAuthenticated(true);
  322. this.setLoginName(userName);
  323. this.setUser(App.User.find().findProperty('id', userName));
  324. App.db.set('tmp', 'redirectsCount', 0);
  325. },
  326. /**
  327. * Set `clusterInstallCompleted` property based on cluster info response.
  328. *
  329. * @param {Object} clusterObject
  330. **/
  331. setClusterInstalled: function(clusterObject) {
  332. this.set('clusterInstallCompleted', clusterObject.items[0].Clusters.provisioning_state === 'INSTALLED')
  333. },
  334. login: function () {
  335. var controller = this.get('loginController');
  336. var loginName = controller.get('loginName');
  337. controller.set('loginName', loginName);
  338. var hash = misc.utf8ToB64(loginName + ":" + controller.get('password'));
  339. var usr = '';
  340. if (App.get('testMode')) {
  341. if (loginName === "admin" && controller.get('password') === 'admin') {
  342. usr = 'admin';
  343. } else if (loginName === 'user' && controller.get('password') === 'user') {
  344. usr = 'user';
  345. }
  346. }
  347. App.ajax.send({
  348. name: 'router.login',
  349. sender: this,
  350. data: {
  351. auth: "Basic " + hash,
  352. usr: usr,
  353. loginName: encodeURIComponent(loginName)
  354. },
  355. beforeSend: 'authBeforeSend',
  356. success: 'loginSuccessCallback',
  357. error: 'loginErrorCallback'
  358. });
  359. },
  360. authBeforeSend: function(opt, xhr, data) {
  361. xhr.setRequestHeader("Authorization", data.auth);
  362. },
  363. loginSuccessCallback: function(data, opt, params) {
  364. var self = this;
  365. App.router.set('loginController.isSubmitDisabled', false);
  366. App.usersMapper.map({"items": [data]});
  367. this.setUserLoggedIn(data.Users.user_name);
  368. var requestData = {
  369. loginName: data.Users.user_name,
  370. loginData: data
  371. };
  372. App.router.get('clusterController').loadAuthorizations().complete(function() {
  373. App.ajax.send({
  374. name: 'router.login.message',
  375. sender: self,
  376. data: requestData,
  377. success: 'showLoginMessageSuccessCallback',
  378. error: 'showLoginMessageErrorCallback'
  379. });
  380. });
  381. },
  382. loginErrorCallback: function(request) {
  383. var controller = this.get('loginController');
  384. this.setAuthenticated(false);
  385. if (request.status > 400) {
  386. var responseMessage = request.responseText;
  387. try{
  388. responseMessage = JSON.parse(request.responseText).message;
  389. }catch(e){}
  390. }
  391. if (request.status == 403) {
  392. controller.postLogin(true, false, responseMessage);
  393. } else if (request.status == 500) {
  394. controller.postLogin(false, false, responseMessage);
  395. } else {
  396. controller.postLogin(false, false, null);
  397. }
  398. },
  399. /**
  400. * success callback of router.login.message
  401. * @param {object} data
  402. * @param {object} opt
  403. * @param {object} params
  404. */
  405. showLoginMessageSuccessCallback: function (data, opt, params) {
  406. try {
  407. var response = JSON.parse(data.Settings.content.replace(/\n/g, "\\n"))
  408. } catch (e) {
  409. this.setClusterData(data, opt, params);
  410. return false;
  411. }
  412. var
  413. text = response.text ? response.text.replace(/(\r\n|\n|\r)/gm, '<br>') : "",
  414. buttonText = response.button ? response.button : Em.I18n.t('ok'),
  415. status = response.status && response.status == "true" ? true : false,
  416. self = this;
  417. if(text && status){
  418. return App.ModalPopup.show({
  419. classNames: ['sixty-percent-width-modal'],
  420. header: Em.I18n.t('login.message.title'),
  421. bodyClass: Ember.View.extend({
  422. template: Ember.Handlebars.compile(text)
  423. }),
  424. primary:null,
  425. secondary: null,
  426. footerClass: Ember.View.extend({
  427. template: Ember.Handlebars.compile(
  428. '<div class="modal-footer">' +
  429. '<button class="btn btn-success" {{action onPrimary target="view"}}>' + buttonText + '</button>'+
  430. '</div>'
  431. ),
  432. onPrimary: function() {
  433. this.get('parentView').onPrimary();
  434. }
  435. }),
  436. onPrimary: function () {
  437. self.setClusterData(data, opt, params);
  438. this.hide();
  439. },
  440. onClose: function () {
  441. self.setClusterData(data, opt, params);
  442. this.hide();
  443. }
  444. });
  445. }
  446. this.setClusterData(data, opt, params);
  447. return false;
  448. },
  449. /**
  450. * error callback of router.login.message
  451. * @param {object} request
  452. * @param {string} ajaxOptions
  453. * @param {string} error
  454. * @param {object} opt
  455. * @param {object} params
  456. */
  457. showLoginMessageErrorCallback: function (request, ajaxOptions, error, opt, params) {
  458. this.showLoginMessageSuccessCallback(null, opt, params);
  459. },
  460. setClusterData: function (data, opt, params) {
  461. var
  462. self = this,
  463. requestData = {
  464. loginName: params.loginName,
  465. loginData: params.loginData
  466. };
  467. // no need to load cluster data if it's already loaded
  468. if (this.get('clusterData')) {
  469. this.loginGetClustersSuccessCallback(self.get('clusterData'), {}, requestData);
  470. }
  471. else {
  472. App.ajax.send({
  473. name: 'router.login.clusters',
  474. sender: self,
  475. data: requestData,
  476. success: 'loginGetClustersSuccessCallback'
  477. });
  478. }
  479. },
  480. /**
  481. * success callback of login request
  482. * @param {object} clustersData
  483. * @param {object} opt
  484. * @param {object} params
  485. */
  486. loginGetClustersSuccessCallback: function (clustersData, opt, params) {
  487. var privileges = params.loginData.privileges || [];
  488. var router = this;
  489. var isAdmin = privileges.mapProperty('PrivilegeInfo.permission_name').contains('AMBARI.ADMINISTRATOR');
  490. App.set('isAdmin', isAdmin);
  491. if (clustersData.items.length) {
  492. var clusterPermissions = privileges.
  493. filterProperty('PrivilegeInfo.cluster_name', clustersData.items[0].Clusters.cluster_name).
  494. mapProperty('PrivilegeInfo.permission_name');
  495. //cluster installed
  496. router.setClusterInstalled(clustersData);
  497. if (clusterPermissions.contains('CLUSTER.ADMINISTRATOR')) {
  498. App.setProperties({
  499. isAdmin: true,
  500. isOperator: true,
  501. isClusterUser: false
  502. });
  503. }
  504. if (App.get('isOnlyViewUser')) {
  505. router.transitionToViews();
  506. } else {
  507. router.transitionToApp();
  508. }
  509. } else {
  510. if (App.get('isOnlyViewUser')) {
  511. router.transitionToViews();
  512. } else {
  513. router.transitionToAdminView();
  514. }
  515. }
  516. App.set('isPermissionDataLoaded', true);
  517. App.router.get('userSettingsController').dataLoading();
  518. },
  519. /**
  520. * redirect user to Admin View
  521. * @returns {$.ajax}
  522. */
  523. transitionToAdminView: function() {
  524. return App.ajax.send({
  525. name: 'ambari.service.load_server_version',
  526. sender: this,
  527. success: 'adminViewInfoSuccessCallback',
  528. error: 'adminViewInfoErrorCallback'
  529. });
  530. },
  531. /**
  532. * redirect user to application Dashboard
  533. */
  534. transitionToApp: function () {
  535. var router = this;
  536. if (!router.restorePreferedPath()) {
  537. router.getSection(function (route) {
  538. router.transitionTo(route);
  539. });
  540. }
  541. },
  542. /**
  543. * redirect user to application Views
  544. */
  545. transitionToViews: function() {
  546. App.router.get('mainViewsController').loadAmbariViews();
  547. this.transitionTo('main.views.index');
  548. },
  549. adminViewInfoSuccessCallback: function(data) {
  550. var components = Em.get(data,'components');
  551. if (Em.isArray(components)) {
  552. var mappedVersions = components.map(function(component) {
  553. if (Em.get(component, 'RootServiceComponents.component_version')) {
  554. return Em.get(component, 'RootServiceComponents.component_version');
  555. }
  556. }),
  557. sortedMappedVersions = mappedVersions.sort(),
  558. latestVersion = sortedMappedVersions[sortedMappedVersions.length-1];
  559. window.location.replace(App.appURLRoot + 'views/ADMIN_VIEW/' + latestVersion + '/INSTANCE/#/');
  560. }
  561. },
  562. adminViewInfoErrorCallback: function() {
  563. this.transitionToViews();
  564. },
  565. getSection: function (callback) {
  566. if (App.get('testMode')) {
  567. if (App.alwaysGoToInstaller) {
  568. callback('installer');
  569. } else {
  570. callback('main.dashboard.index');
  571. }
  572. } else {
  573. if (this.get('clusterInstallCompleted')) {
  574. App.router.get('wizardWatcherController').getUser().complete(function() {
  575. App.clusterStatus.updateFromServer(false).complete(function () {
  576. var route = 'main.dashboard.index';
  577. var clusterStatusOnServer = App.clusterStatus.get('value');
  578. if (clusterStatusOnServer) {
  579. var wizardControllerRoutes = require('data/controller_route');
  580. var wizardControllerRoute = wizardControllerRoutes.findProperty('wizardControllerName', clusterStatusOnServer.wizardControllerName);
  581. if (wizardControllerRoute && !App.router.get('wizardWatcherController').get('isNonWizardUser')) {
  582. route = wizardControllerRoute.route;
  583. }
  584. }
  585. if (wizardControllerRoute && wizardControllerRoute.wizardControllerName === 'mainAdminStackAndUpgradeController') {
  586. var clusterController = App.router.get('clusterController');
  587. clusterController.loadClusterName().done(function(){
  588. clusterController.restoreUpgradeState().done(function(){
  589. callback(route);
  590. });
  591. });
  592. } else {
  593. callback(route);
  594. }
  595. });
  596. });
  597. } else {
  598. callback('installer');
  599. }
  600. }
  601. },
  602. logOff: function (context) {
  603. var self = this;
  604. $('title').text(Em.I18n.t('app.name'));
  605. App.router.get('mainController').stopPolling();
  606. // App.db.cleanUp() must be called before router.clearAllSteps().
  607. // otherwise, this.set('installerController.currentStep, 0) would have no effect
  608. // since it's a computed property but we are not setting it as a dependent of App.db.
  609. App.db.cleanUp();
  610. App.setProperties({
  611. isAdmin: false,
  612. auth: null,
  613. isOperator: false,
  614. isClusterUser: false,
  615. isPermissionDataLoaded: false
  616. });
  617. this.set('loggedIn', false);
  618. this.clearAllSteps();
  619. this.set('loginController.loginName', '');
  620. this.set('loginController.password', '');
  621. // When logOff is called by Sign Out button, context contains event object. As it is only case we should send logoff request, we are checking context below.
  622. if (!App.get('testMode') && context) {
  623. App.ajax.send({
  624. name: 'router.logoff',
  625. sender: this,
  626. success: 'logOffSuccessCallback',
  627. error: 'logOffErrorCallback',
  628. beforeSend: 'logOffBeforeSend'
  629. }).complete(function() {
  630. self.logoffRedirect(context);
  631. });
  632. } else {
  633. this.logoffRedirect();
  634. }
  635. },
  636. logOffSuccessCallback: function () {
  637. var applicationController = App.router.get('applicationController');
  638. applicationController.set('isPollerRunning', false);
  639. },
  640. logOffErrorCallback: function () {
  641. },
  642. logOffBeforeSend: function(opt, xhr) {
  643. xhr.setRequestHeader('Authorization', '');
  644. },
  645. /**
  646. * Redirect function on sign off request.
  647. *
  648. * @param {$.Event} [context=undefined] - triggered event context
  649. */
  650. logoffRedirect: function(context) {
  651. this.transitionTo('login', context);
  652. if (App.router.get('clusterController.isLoaded')) {
  653. Em.run.next(function() {
  654. window.location.reload();
  655. });
  656. }
  657. },
  658. /**
  659. * save prefered path
  660. * @param {string} path
  661. * @param {string} key
  662. */
  663. savePreferedPath: function(path, key) {
  664. if (key) {
  665. if (path.contains(key)) {
  666. this.set('preferedPath', path.slice(path.indexOf(key) + key.length));
  667. }
  668. } else {
  669. this.set('preferedPath', path);
  670. }
  671. },
  672. /**
  673. * If path exist route to it, otherwise return false
  674. * @returns {boolean}
  675. */
  676. restorePreferedPath: function() {
  677. var preferredPath = this.get('preferedPath');
  678. var isRestored = false;
  679. if (preferredPath) {
  680. // If the preferred path is relative, allow a redirect to it.
  681. // If the path is not relative, silently ignore it - if the path is an absolute URL, the user
  682. // may be routed to a different server where the possibility exists for a phishing attack.
  683. if ((preferredPath.startsWith('/') || preferredPath.startsWith('#')) && !preferredPath.contains('#/login')) {
  684. window.location = preferredPath;
  685. isRestored = true;
  686. }
  687. // Unset preferedPath
  688. this.set('preferedPath', null);
  689. }
  690. return isRestored;
  691. },
  692. /**
  693. * initialize isAdmin if user is administrator
  694. */
  695. initAdmin: function(){
  696. if (App.db) {
  697. var user = App.db.getUser();
  698. if (user) {
  699. if (user.admin) {
  700. App.set('isAdmin', true);
  701. }
  702. if (user.operator) {
  703. App.set('isOperator', true);
  704. }
  705. if (user.cluster_user) {
  706. App.set('isClusterUser', true);
  707. }
  708. App.set('isPermissionDataLoaded', true);
  709. }
  710. }
  711. },
  712. /**
  713. * initialize Auth for user
  714. */
  715. initAuth: function(){
  716. if (App.db) {
  717. var auth = App.db.getAuth();
  718. if(auth) {
  719. App.set('auth', auth);
  720. }
  721. }
  722. },
  723. /**
  724. * Increment redirect count if <code>redirected</code> parameter passed.
  725. */
  726. handleUIRedirect: function() {
  727. if (/(\?|&)redirected=/.test(location.hash)) {
  728. var redirectsCount = App.db.get('tmp', 'redirectsCount') || 0;
  729. App.db.set('tmp', 'redirectsCount', ++redirectsCount);
  730. }
  731. },
  732. /**
  733. * <code>window.location</code> setter. Will add query param which determines that we redirect user
  734. * @param {string} url - url to navigate
  735. */
  736. redirectByURL: function(url) {
  737. var suffix = "?redirected=true";
  738. var redirectsCount = App.db.get('tmp', 'redirectsCount') || 0;
  739. if (redirectsCount > this.get('redirectsLimitCount')) {
  740. this.showRedirectIssue();
  741. return;
  742. }
  743. // skip adding redirected parameter if added
  744. if (/(\?|&)redirected=/.test(location.hash)) {
  745. this.setLocationUrl(url);
  746. return;
  747. }
  748. // detect if query params were assigned and replace "?" with "&" for suffix param
  749. if (/\?\w+=/.test(location.hash)) {
  750. suffix = suffix.replace('?', '&');
  751. }
  752. this.setLocationUrl(url + suffix);
  753. },
  754. /**
  755. * Convenient method to set <code>window.location</code>.
  756. * Useful for faking url manipulation in tests.
  757. *
  758. * @param {string} url
  759. */
  760. setLocationUrl: function(url) {
  761. window.location = url;
  762. },
  763. /**
  764. * Convenient method to get current <code>window.location</code>.
  765. * Useful for faking url manipulation in tests.
  766. */
  767. getCurrentLocationUrl: function() {
  768. return window.location.href;
  769. },
  770. /**
  771. * Inform user about redirect issue in modal popup.
  772. *
  773. * @returns {App.ModalPopup}
  774. */
  775. showRedirectIssue: function() {
  776. var bodyMessage = Em.I18n.t('app.redirectIssuePopup.body').format(location.origin + '/#' + this.get('localUserAuthUrl'));
  777. var popupHeader = Em.I18n.t('app.redirectIssuePopup.header');
  778. var popup = App.showAlertPopup(popupHeader, bodyMessage);
  779. popup.set('encodeBody', false);
  780. return popup;
  781. },
  782. root: Em.Route.extend({
  783. index: Em.Route.extend({
  784. route: '/',
  785. redirectsTo: 'login'
  786. }),
  787. enter: function(router){
  788. router.initAdmin();
  789. router.initAuth();
  790. router.handleUIRedirect();
  791. },
  792. login: Em.Route.extend({
  793. route: '/login:suffix',
  794. /**
  795. * If the user is already logged in, redirect to where the user was previously
  796. */
  797. enter: function (router, context) {
  798. if ($.mocho) {
  799. return;
  800. }
  801. var location = router.location.location.hash;
  802. router.getAuthenticated().done(function (loggedIn) {
  803. if (loggedIn) {
  804. Ember.run.next(function () {
  805. router.getSection(function (route) {
  806. router.transitionTo(route, context);
  807. });
  808. });
  809. } else {
  810. //key to parse URI for prefered path to route
  811. router.savePreferedPath(location, '?targetURI=');
  812. }
  813. });
  814. },
  815. connectOutlets: function (router, context) {
  816. $('title').text(Em.I18n.t('app.name'));
  817. router.get('applicationController').connectOutlet('login');
  818. },
  819. serialize: function(router, context) {
  820. // check for login/local hash
  821. var location = router.get('location.location.hash');
  822. return {
  823. suffix: location === '#' + router.get('localUserAuthUrl') ? '/local' : ''
  824. };
  825. }
  826. }),
  827. installer: require('routes/installer'),
  828. main: require('routes/main'),
  829. adminView: Em.Route.extend({
  830. route: '/adminView',
  831. enter: function (router) {
  832. if (!router.get('loggedIn') || !App.isAuthorized('CLUSTER.UPGRADE_DOWNGRADE_STACK')) {
  833. Em.run.next(function () {
  834. router.transitionTo('login');
  835. });
  836. } else {
  837. App.ajax.send({
  838. name: 'ambari.service.load_server_version',
  839. sender: router,
  840. success: 'adminViewInfoSuccessCallback'
  841. });
  842. }
  843. }
  844. }),
  845. experimental: Em.Route.extend({
  846. route: '/experimental',
  847. enter: function (router, context) {
  848. if (!App.isAuthorized('AMBARI.MANAGE_SETTINGS')) {
  849. if (App.isAuthorized('CLUSTER.UPGRADE_DOWNGRADE_STACK')) {
  850. Em.run.next(function () {
  851. if (router.get('clusterInstallCompleted')) {
  852. router.transitionTo("main.dashboard.widgets");
  853. } else {
  854. router.transitionTo("main.views.index");
  855. }
  856. });
  857. } else {
  858. Em.run.next(function () {
  859. router.transitionTo("main.views.index");
  860. });
  861. }
  862. }
  863. },
  864. connectOutlets: function (router, context) {
  865. if (App.isAuthorized('AMBARI.MANAGE_SETTINGS')) {
  866. App.router.get('experimentalController').loadSupports().complete(function () {
  867. $('title').text(Em.I18n.t('app.name.subtitle.experimental'));
  868. router.get('applicationController').connectOutlet('experimental');
  869. });
  870. }
  871. }
  872. }),
  873. logoff: function (router, context) {
  874. router.logOff(context);
  875. }
  876. })
  877. });