router.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  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. App.Router = Em.Router.extend({
  37. enableLogging: true,
  38. isFwdNavigation: true,
  39. backBtnForHigherStep: false,
  40. transitionInProgress: false,
  41. nextBtnClickInProgress: false,
  42. /**
  43. * Path for local login page. This page will be always accessible without
  44. * redirect to auth server different from ambari-server. Used in some types of
  45. * authorizations like knox sso.
  46. *
  47. * @type {string}
  48. */
  49. localUserAuthUrl: '/login/local',
  50. /**
  51. * LocalStorage property <code>redirectsCount</code> from <code>tmp</code> namespace
  52. * will be incremented by each redirect action performed by UI and reset on success login.
  53. * <code>redirectsLimitCount</code> determines maximum redirect tries. When redirects count overflow
  54. * then something goes wrong and we have to inform user about the problem.
  55. *
  56. * @type {number}
  57. */
  58. redirectsLimitCount: 0,
  59. /**
  60. * Is true, if cluster.provisioning_state is equal to 'INSTALLED'
  61. * @type {Boolean}
  62. */
  63. clusterInstallCompleted: false,
  64. /**
  65. * user prefered path to route
  66. */
  67. preferedPath: null,
  68. setNavigationFlow: function (step) {
  69. var matches = step.match(/\d+$/);
  70. var newStep;
  71. if (matches) {
  72. newStep = parseInt(matches[0]);
  73. }
  74. var previousStep = parseInt(this.getInstallerCurrentStep());
  75. this.set('isFwdNavigation', newStep >= previousStep);
  76. },
  77. clearAllSteps: function () {
  78. this.get('installerController').clear();
  79. this.get('addHostController').clear();
  80. this.get('addServiceController').clear();
  81. this.get('backgroundOperationsController').clear();
  82. for (var i = 1; i < 11; i++) {
  83. this.set('wizardStep' + i + 'Controller.hasSubmitted', false);
  84. this.set('wizardStep' + i + 'Controller.isDisabled', true);
  85. }
  86. },
  87. /**
  88. * Temporary fix for getting cluster name
  89. * @return {*}
  90. */
  91. getClusterName: function () {
  92. return App.router.get('clusterController').get('clusterName');
  93. },
  94. /**
  95. * Get current step of Installer wizard
  96. * @return {*}
  97. */
  98. getInstallerCurrentStep: function () {
  99. return this.getWizardCurrentStep('installer');
  100. },
  101. /**
  102. * Get current step for <code>wizardType</code> wizard
  103. * @param wizardType one of <code>installer</code>, <code>addHost</code>, <code>addServices</code>
  104. */
  105. getWizardCurrentStep: function (wizardType) {
  106. var currentStep = App.db.getWizardCurrentStep(wizardType);
  107. if (!currentStep) {
  108. currentStep = wizardType === 'installer' ? '0' : '1';
  109. }
  110. return currentStep;
  111. },
  112. /**
  113. * @type {boolean}
  114. */
  115. loggedIn: App.db.getAuthenticated(),
  116. loginName: function() {
  117. return this.getLoginName();
  118. }.property('loggedIn'),
  119. getAuthenticated: function () {
  120. var dfd = $.Deferred();
  121. var self = this;
  122. var auth = App.db.getAuthenticated();
  123. App.ajax.send({
  124. name: 'router.login.clusters',
  125. sender: this,
  126. success: 'onAuthenticationSuccess',
  127. error: 'onAuthenticationError'
  128. }).complete(function (xhr) {
  129. if (xhr.isResolved()) {
  130. // if server knows the user and user authenticated by UI
  131. if (auth) {
  132. dfd.resolve(self.get('loggedIn'));
  133. // if server knows the user but UI don't, check the response header
  134. // and try to authorize
  135. } else if (xhr.getResponseHeader('User')) {
  136. var user = xhr.getResponseHeader('User');
  137. App.ajax.send({
  138. name: 'router.login',
  139. sender: self,
  140. data: {
  141. usr: user,
  142. loginName: encodeURIComponent(user)
  143. },
  144. success: 'loginSuccessCallback',
  145. error: 'loginErrorCallback'
  146. });
  147. } else {
  148. self.setAuthenticated(false);
  149. dfd.resolve(false);
  150. }
  151. } else {
  152. //if provisioning state unreachable then consider user as unauthenticated
  153. self.setAuthenticated(false);
  154. dfd.resolve(false);
  155. }
  156. });
  157. return dfd.promise();
  158. },
  159. /**
  160. * Response for <code>/clusters?fields=Clusters/provisioning_state</code>
  161. * @type {null|object}
  162. */
  163. clusterData: null,
  164. onAuthenticationSuccess: function (data) {
  165. if (App.db.getAuthenticated() === true) {
  166. this.set('clusterData', data);
  167. this.setAuthenticated(true);
  168. if (data.items.length) {
  169. this.setClusterInstalled(data);
  170. }
  171. }
  172. },
  173. /**
  174. * If authentication failed, need to check for jwt auth url
  175. * and redirect user if current location is not <code>localUserAuthUrl</code>
  176. *
  177. * @param {?object} data
  178. */
  179. onAuthenticationError: function (data) {
  180. if (data.status === 403) {
  181. try {
  182. var responseJson = JSON.parse(data.responseText);
  183. if (responseJson.jwtProviderUrl && this.get('location.lastSetURL') !== this.get('localUserAuthUrl')) {
  184. this.redirectByURL(responseJson.jwtProviderUrl + encodeURIComponent(this.getCurrentLocationUrl()));
  185. }
  186. } catch (e) {
  187. } finally {
  188. this.setAuthenticated(false);
  189. }
  190. } else if (data.status >= 500) {
  191. this.setAuthenticated(false);
  192. this.loginErrorCallback(data);
  193. }
  194. },
  195. setAuthenticated: function (authenticated) {
  196. App.db.setAuthenticated(authenticated);
  197. this.set('loggedIn', authenticated);
  198. },
  199. getLoginName: function () {
  200. return App.db.getLoginName();
  201. },
  202. setLoginName: function (loginName) {
  203. App.db.setLoginName(loginName);
  204. },
  205. /**
  206. * Set user model to local storage
  207. * @param user
  208. */
  209. setUser: function (user) {
  210. App.db.setUser(user);
  211. },
  212. /**
  213. * Get user model from local storage
  214. * @return {*}
  215. */
  216. getUser: function () {
  217. return App.db.getUser();
  218. },
  219. setUserLoggedIn: function(userName) {
  220. this.setAuthenticated(true);
  221. this.setLoginName(userName);
  222. this.setUser(App.User.find().findProperty('id', userName));
  223. App.db.set('tmp', 'redirectsCount', 0);
  224. },
  225. /**
  226. * Set `clusterInstallCompleted` property based on cluster info response.
  227. *
  228. * @param {Object} clusterObject
  229. **/
  230. setClusterInstalled: function(clusterObject) {
  231. this.set('clusterInstallCompleted', clusterObject.items[0].Clusters.provisioning_state === 'INSTALLED')
  232. },
  233. login: function () {
  234. var controller = this.get('loginController');
  235. var loginName = controller.get('loginName');
  236. controller.set('loginName', loginName);
  237. var hash = misc.utf8ToB64(loginName + ":" + controller.get('password'));
  238. var usr = '';
  239. if (App.get('testMode')) {
  240. if (loginName === "admin" && controller.get('password') === 'admin') {
  241. usr = 'admin';
  242. } else if (loginName === 'user' && controller.get('password') === 'user') {
  243. usr = 'user';
  244. }
  245. }
  246. App.ajax.send({
  247. name: 'router.login',
  248. sender: this,
  249. data: {
  250. auth: "Basic " + hash,
  251. usr: usr,
  252. loginName: encodeURIComponent(loginName)
  253. },
  254. beforeSend: 'authBeforeSend',
  255. success: 'loginSuccessCallback',
  256. error: 'loginErrorCallback'
  257. });
  258. },
  259. authBeforeSend: function(opt, xhr, data) {
  260. xhr.setRequestHeader("Authorization", data.auth);
  261. },
  262. loginSuccessCallback: function(data, opt, params) {
  263. var self = this;
  264. App.router.set('loginController.isSubmitDisabled', false);
  265. App.usersMapper.map({"items": [data]});
  266. this.setUserLoggedIn(decodeURIComponent(params.loginName));
  267. var requestData = {
  268. loginName: params.loginName,
  269. loginData: data
  270. };
  271. App.router.get('clusterController').loadAuthorizations().complete(function() {
  272. App.ajax.send({
  273. name: 'router.login.message',
  274. sender: self,
  275. data: requestData,
  276. success: 'showLoginMessageSuccessCallback',
  277. error: 'showLoginMessageErrorCallback'
  278. });
  279. });
  280. },
  281. loginErrorCallback: function(request) {
  282. var controller = this.get('loginController');
  283. this.setAuthenticated(false);
  284. if (request.status > 400) {
  285. var responseMessage = request.responseText;
  286. try{
  287. responseMessage = JSON.parse(request.responseText).message;
  288. }catch(e){}
  289. }
  290. if (request.status == 403) {
  291. controller.postLogin(true, false, responseMessage);
  292. } else if (request.status == 500) {
  293. controller.postLogin(false, false, responseMessage);
  294. } else {
  295. controller.postLogin(false, false, null);
  296. }
  297. },
  298. /**
  299. * success callback of router.login.message
  300. * @param {object} data
  301. * @param {object} opt
  302. * @param {object} params
  303. */
  304. showLoginMessageSuccessCallback: function (data, opt, params) {
  305. try {
  306. var response = JSON.parse(data.Settings.content.replace(/\n/g, "\\n"))
  307. } catch (e) {
  308. this.setClusterData(data, opt, params);
  309. return false;
  310. }
  311. var
  312. text = response.text ? response.text.replace(/(\r\n|\n|\r)/gm, '<br>') : "",
  313. buttonText = response.button ? response.button : Em.I18n.t('ok'),
  314. status = response.status && response.status == "true" ? true : false,
  315. self = this;
  316. if(text && status){
  317. return App.ModalPopup.show({
  318. classNames: ['sixty-percent-width-modal'],
  319. header: Em.I18n.t('login.message.title'),
  320. bodyClass: Ember.View.extend({
  321. template: Ember.Handlebars.compile(text)
  322. }),
  323. primary:null,
  324. secondary: null,
  325. footerClass: Ember.View.extend({
  326. template: Ember.Handlebars.compile(
  327. '<div class="modal-footer">' +
  328. '<button class="btn btn-success" {{action onPrimary target="view"}}>' + buttonText + '</button>'+
  329. '</div>'
  330. ),
  331. onPrimary: function() {
  332. this.get('parentView').onPrimary();
  333. }
  334. }),
  335. onPrimary: function () {
  336. self.setClusterData(data, opt, params);
  337. this.hide();
  338. },
  339. onClose: function () {
  340. self.setClusterData(data, opt, params);
  341. this.hide();
  342. }
  343. });
  344. }else{
  345. this.setClusterData(data, opt, params);
  346. return false;
  347. }
  348. },
  349. /**
  350. * error callback of router.login.message
  351. * @param {object} request
  352. * @param {string} ajaxOptions
  353. * @param {string} error
  354. * @param {object} opt
  355. * @param {object} params
  356. */
  357. showLoginMessageErrorCallback: function (request, ajaxOptions, error, opt, params) {
  358. this.showLoginMessageSuccessCallback(null, opt, params);
  359. },
  360. setClusterData: function (data, opt, params) {
  361. var
  362. self = this,
  363. requestData = {
  364. loginName: params.loginName,
  365. loginData: params.loginData
  366. };
  367. // no need to load cluster data if it's already loaded
  368. if (this.get('clusterData')) {
  369. this.loginGetClustersSuccessCallback(self.get('clusterData'), {}, requestData);
  370. }
  371. else {
  372. App.ajax.send({
  373. name: 'router.login.clusters',
  374. sender: self,
  375. data: requestData,
  376. success: 'loginGetClustersSuccessCallback'
  377. });
  378. }
  379. },
  380. /**
  381. * success callback of login request
  382. * @param {object} clustersData
  383. * @param {object} opt
  384. * @param {object} params
  385. */
  386. loginGetClustersSuccessCallback: function (clustersData, opt, params) {
  387. var privileges = params.loginData.privileges || [];
  388. var router = this;
  389. var isAdmin = privileges.mapProperty('PrivilegeInfo.permission_name').contains('AMBARI.ADMINISTRATOR');
  390. App.set('isAdmin', isAdmin);
  391. if (clustersData.items.length) {
  392. var clusterPermissions = privileges.
  393. filterProperty('PrivilegeInfo.cluster_name', clustersData.items[0].Clusters.cluster_name).
  394. mapProperty('PrivilegeInfo.permission_name');
  395. //cluster installed
  396. router.setClusterInstalled(clustersData);
  397. if (clusterPermissions.contains('CLUSTER.ADMINISTRATOR')) {
  398. App.setProperties({
  399. isAdmin: true,
  400. isOperator: true
  401. });
  402. }
  403. if (App.get('isOnlyViewUser')) {
  404. router.transitionToViews();
  405. } else {
  406. router.transitionToApp();
  407. }
  408. } else {
  409. if (App.get('isOnlyViewUser')) {
  410. router.transitionToViews();
  411. } else {
  412. router.transitionToAdminView();
  413. }
  414. }
  415. App.set('isPermissionDataLoaded', true);
  416. App.router.get('userSettingsController').dataLoading();
  417. },
  418. /**
  419. * redirect user to Admin View
  420. * @returns {$.ajax}
  421. */
  422. transitionToAdminView: function() {
  423. return App.ajax.send({
  424. name: 'ambari.service.load_server_version',
  425. sender: this,
  426. success: 'adminViewInfoSuccessCallback',
  427. error: 'adminViewInfoErrorCallback'
  428. });
  429. },
  430. /**
  431. * redirect user to application Dashboard
  432. */
  433. transitionToApp: function () {
  434. var router = this;
  435. if (!router.restorePreferedPath()) {
  436. router.getSection(function (route) {
  437. router.transitionTo(route);
  438. });
  439. }
  440. },
  441. /**
  442. * redirect user to application Views
  443. */
  444. transitionToViews: function() {
  445. App.router.get('mainViewsController').loadAmbariViews();
  446. this.transitionTo('main.views.index');
  447. },
  448. adminViewInfoSuccessCallback: function(data) {
  449. var components = Em.get(data,'components');
  450. if (Em.isArray(components)) {
  451. var mappedVersions = components.map(function(component) {
  452. if (Em.get(component, 'RootServiceComponents.component_version')) {
  453. return Em.get(component, 'RootServiceComponents.component_version');
  454. }
  455. }),
  456. sortedMappedVersions = mappedVersions.sort(),
  457. latestVersion = sortedMappedVersions[sortedMappedVersions.length-1];
  458. window.location.replace('/views/ADMIN_VIEW/' + latestVersion + '/INSTANCE/#/');
  459. }
  460. },
  461. adminViewInfoErrorCallback: function() {
  462. this.transitionToViews();
  463. },
  464. getSection: function (callback) {
  465. if (App.get('testMode')) {
  466. if (App.alwaysGoToInstaller) {
  467. callback('installer');
  468. } else {
  469. callback('main.dashboard.index');
  470. }
  471. } else {
  472. if (this.get('clusterInstallCompleted')) {
  473. App.router.get('wizardWatcherController').getUser().complete(function() {
  474. App.clusterStatus.updateFromServer(false).complete(function () {
  475. var route = 'main.dashboard.index';
  476. var clusterStatusOnServer = App.clusterStatus.get('value');
  477. if (clusterStatusOnServer) {
  478. var wizardControllerRoutes = require('data/controller_route');
  479. var wizardControllerRoute = wizardControllerRoutes.findProperty('wizardControllerName', clusterStatusOnServer.wizardControllerName);
  480. if (wizardControllerRoute && !App.router.get('wizardWatcherController').get('isNonWizardUser')) {
  481. route = wizardControllerRoute.route;
  482. }
  483. }
  484. if (wizardControllerRoute && wizardControllerRoute.wizardControllerName === 'mainAdminStackAndUpgradeController') {
  485. var clusterController = App.router.get('clusterController');
  486. clusterController.loadClusterName().done(function(){
  487. clusterController.restoreUpgradeState().done(function(){
  488. callback(route);
  489. });
  490. });
  491. } else {
  492. callback(route);
  493. }
  494. });
  495. });
  496. } else {
  497. callback('installer');
  498. }
  499. }
  500. },
  501. logOff: function (context) {
  502. var self = this;
  503. $('title').text(Em.I18n.t('app.name'));
  504. App.router.get('mainController').stopPolling();
  505. // App.db.cleanUp() must be called before router.clearAllSteps().
  506. // otherwise, this.set('installerController.currentStep, 0) would have no effect
  507. // since it's a computed property but we are not setting it as a dependent of App.db.
  508. App.db.cleanUp();
  509. App.setProperties({
  510. isAdmin: false,
  511. auth: null,
  512. isOperator: false,
  513. isPermissionDataLoaded: false
  514. });
  515. this.set('loggedIn', false);
  516. this.clearAllSteps();
  517. this.set('loginController.loginName', '');
  518. this.set('loginController.password', '');
  519. // 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.
  520. if (!App.get('testMode') && context) {
  521. App.ajax.send({
  522. name: 'router.logoff',
  523. sender: this,
  524. success: 'logOffSuccessCallback',
  525. error: 'logOffErrorCallback'
  526. }).complete(function() {
  527. self.logoffRedirect(context);
  528. });
  529. } else {
  530. this.logoffRedirect();
  531. }
  532. },
  533. logOffSuccessCallback: function () {
  534. var applicationController = App.router.get('applicationController');
  535. applicationController.set('isPollerRunning', false);
  536. },
  537. logOffErrorCallback: function () {
  538. },
  539. /**
  540. * Redirect function on sign off request.
  541. *
  542. * @param {$.Event} [context=undefined] - triggered event context
  543. */
  544. logoffRedirect: function(context) {
  545. if (App.router.get('clusterController.isLoaded')) {
  546. window.location.reload();
  547. } else {
  548. this.transitionTo('login', context);
  549. }
  550. },
  551. /**
  552. * save prefered path
  553. * @param {string} path
  554. * @param {string} key
  555. */
  556. savePreferedPath: function(path, key) {
  557. if (key) {
  558. if (path.contains(key)) {
  559. this.set('preferedPath', path.slice(path.indexOf(key) + key.length));
  560. }
  561. } else {
  562. this.set('preferedPath', path);
  563. }
  564. },
  565. /**
  566. * If path exist route to it, otherwise return false
  567. * @returns {boolean}
  568. */
  569. restorePreferedPath: function() {
  570. var preferredPath = this.get('preferedPath');
  571. var isRestored = false;
  572. if (preferredPath) {
  573. // If the preferred path is relative, allow a redirect to it.
  574. // If the path is not relative, silently ignore it - if the path is an absolute URL, the user
  575. // may be routed to a different server where the possibility exists for a phishing attack.
  576. if ((preferredPath.startsWith('/') || preferredPath.startsWith('#')) && !preferredPath.contains('#/login')) {
  577. window.location = preferredPath;
  578. isRestored = true;
  579. }
  580. // Unset preferedPath
  581. this.set('preferedPath', null);
  582. }
  583. return isRestored;
  584. },
  585. /**
  586. * initialize isAdmin if user is administrator
  587. */
  588. initAdmin: function(){
  589. if (App.db) {
  590. var user = App.db.getUser();
  591. if (user) {
  592. if (user.admin) {
  593. App.set('isAdmin', true);
  594. }
  595. if (user.operator) {
  596. App.set('isOperator', true);
  597. }
  598. App.set('isPermissionDataLoaded', true);
  599. }
  600. }
  601. },
  602. /**
  603. * initialize Auth for user
  604. */
  605. initAuth: function(){
  606. if (App.db) {
  607. var auth = App.db.getAuth();
  608. if(auth)
  609. App.set('auth', auth);
  610. }
  611. },
  612. /**
  613. * Increment redirect count if <code>redirected</code> parameter passed.
  614. */
  615. handleUIRedirect: function() {
  616. if (/(\?|&)redirected=/.test(location.hash)) {
  617. var redirectsCount = App.db.get('tmp', 'redirectsCount') || 0;
  618. App.db.set('tmp', 'redirectsCount', ++redirectsCount);
  619. }
  620. },
  621. /**
  622. * <code>window.location</code> setter. Will add query param which determines that we redirect user
  623. * @param {string} url - url to navigate
  624. */
  625. redirectByURL: function(url) {
  626. var suffix = "?redirected=true";
  627. var redirectsCount = App.db.get('tmp', 'redirectsCount') || 0;
  628. if (redirectsCount > this.get('redirectsLimitCount')) {
  629. this.showRedirectIssue();
  630. return;
  631. }
  632. // skip adding redirected parameter if added
  633. if (/(\?|&)redirected=/.test(location.hash)) {
  634. this.setLocationUrl(url);
  635. return;
  636. }
  637. // detect if query params were assigned and replace "?" with "&" for suffix param
  638. if (/\?\w+=/.test(location.hash)) {
  639. suffix = suffix.replace('?', '&');
  640. }
  641. this.setLocationUrl(url + suffix);
  642. },
  643. /**
  644. * Convenient method to set <code>window.location</code>.
  645. * Useful for faking url manipulation in tests.
  646. *
  647. * @param {string} url
  648. */
  649. setLocationUrl: function(url) {
  650. window.location = url;
  651. },
  652. /**
  653. * Convenient method to get current <code>window.location</code>.
  654. * Useful for faking url manipulation in tests.
  655. */
  656. getCurrentLocationUrl: function() {
  657. return window.location.href;
  658. },
  659. /**
  660. * Inform user about redirect issue in modal popup.
  661. *
  662. * @returns {App.ModalPopup}
  663. */
  664. showRedirectIssue: function() {
  665. var bodyMessage = Em.I18n.t('app.redirectIssuePopup.body').format(location.origin + '/#' + this.get('localUserAuthUrl'));
  666. var popupHeader = Em.I18n.t('app.redirectIssuePopup.header');
  667. var popup = App.showAlertPopup(popupHeader, bodyMessage);
  668. popup.set('encodeBody', false);
  669. return popup;
  670. },
  671. root: Em.Route.extend({
  672. index: Em.Route.extend({
  673. route: '/',
  674. redirectsTo: 'login'
  675. }),
  676. enter: function(router){
  677. router.initAdmin();
  678. router.initAuth();
  679. router.handleUIRedirect();
  680. },
  681. login: Em.Route.extend({
  682. route: '/login:suffix',
  683. /**
  684. * If the user is already logged in, redirect to where the user was previously
  685. */
  686. enter: function (router, context) {
  687. if ($.mocho) {
  688. return;
  689. }
  690. var location = router.location.location.hash;
  691. router.getAuthenticated().done(function (loggedIn) {
  692. if (loggedIn) {
  693. Ember.run.next(function () {
  694. router.getSection(function (route) {
  695. router.transitionTo(route, context);
  696. });
  697. });
  698. } else {
  699. //key to parse URI for prefered path to route
  700. router.savePreferedPath(location, '?targetURI=');
  701. }
  702. });
  703. },
  704. connectOutlets: function (router, context) {
  705. $('title').text(Em.I18n.t('app.name'));
  706. router.get('applicationController').connectOutlet('login');
  707. },
  708. serialize: function(router, context) {
  709. // check for login/local hash
  710. var location = router.get('location.location.hash');
  711. return {
  712. suffix: location === '#' + router.get('localUserAuthUrl') ? '/local' : ''
  713. };
  714. }
  715. }),
  716. installer: require('routes/installer'),
  717. main: require('routes/main'),
  718. adminView: Em.Route.extend({
  719. route: '/adminView',
  720. enter: function (router) {
  721. if (!router.get('loggedIn') || !App.isAuthorized('CLUSTER.UPGRADE_DOWNGRADE_STACK')) {
  722. Em.run.next(function () {
  723. router.transitionTo('login');
  724. });
  725. } else {
  726. App.ajax.send({
  727. name: 'ambari.service.load_server_version',
  728. sender: router,
  729. success: 'adminViewInfoSuccessCallback'
  730. });
  731. }
  732. }
  733. }),
  734. experimental: Em.Route.extend({
  735. route: '/experimental',
  736. enter: function (router, context) {
  737. if (App.isAuthorized('CLUSTER.UPGRADE_DOWNGRADE_STACK')) {
  738. Em.run.next(function () {
  739. if (router.get('clusterInstallCompleted')) {
  740. router.transitionTo("main.dashboard.widgets");
  741. } else {
  742. router.route("installer");
  743. }
  744. });
  745. } else if (!App.isAuthorized('CLUSTER.UPGRADE_DOWNGRADE_STACK')) {
  746. Em.run.next(function () {
  747. router.transitionTo("main.views.index");
  748. });
  749. }
  750. },
  751. connectOutlets: function (router, context) {
  752. if (App.isAuthorized('CLUSTER.UPGRADE_DOWNGRADE_STACK')) {
  753. App.router.get('experimentalController').loadSupports().complete(function () {
  754. $('title').text(Em.I18n.t('app.name.subtitle.experimental'));
  755. router.get('applicationController').connectOutlet('experimental');
  756. });
  757. }
  758. }
  759. }),
  760. logoff: function (router, context) {
  761. router.logOff(context);
  762. }
  763. })
  764. });