This repository has been archived by the owner on May 12, 2021. It is now read-only.
/
app.js
3209 lines (2993 loc) · 114 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
This file is part of the Juju GUI, which lets users view and manage Juju
environments within a graphical interface (https://launchpad.net/juju-gui).
Copyright (C) 2012-2013 Canonical Ltd.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3, as published by
the Free Software Foundation.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
General Public License for more details.
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
*/
'use strict';
/**
* Provide the main App class, based on the YUI App framework. Also provide
* the routing definitions, which map the request paths to the top-level
* views defined by the App class.
*
* @module app
*/
// Create a global for debug console access to YUI context.
var yui; // eslint-disable-line no-unused-vars
YUI.add('juju-gui', function(Y) {
// Assign the global for console access.
yui = Y;
var juju = Y.namespace('juju'),
models = Y.namespace('juju.models'),
views = Y.namespace('juju.views'),
widgets = Y.namespace('juju.widgets'),
d3 = Y.namespace('d3');
/**
* The main app class.
*
* @class App
*/
var extensions = [
widgets.AutodeployExtension,
Y.juju.Cookies,
Y.juju.AppRenderer,
Y.juju.GhostDeployer
];
var JujuGUI = Y.Base.create('juju-gui', Y.App, extensions, {
/**
* Views
*
* The views encapsulate the functionality blocks that output
* the GUI pages. The "parent" attribute defines the hierarchy.
*
* @attribute views
*/
views: {
environment: {
type: 'juju.views.environment',
preserve: true
}
},
/*
* Declarative keybindings on the window object.
*
* Prefix supported are:
* C - Control
* A - Alt
* S - Shift
*
* Followed by a lowercase letter. For example
*
* A-s is the 'Alt + s' keybinding.
*
* This maps to an object which has the following behavior.
*
* target: {String} CSS selector of one element
* focus: {Boolean} Focus the element.
* toggle: {Boolean} Toggle element visibility.
* fire: {String} Event to fire when triggered. (XXX: Target is topology)
* condition: {Function} returns Boolean, should method be added to
* keybindings.
* callback: {Function} Taking (event, target).
* help: {String} Help text to display in popup.
* label: {String} The label to display in the help text. Defaults to the
* specified keybinding.
*
* All are optional.
*/
keybindings: {
'A-s': {
target: '#charm-search-field',
focus: true,
help: 'Select the charm Search',
label: 'Alt + s'
},
'/': {
target: '.header-search__input',
focus: true,
help: 'Select the charm Search'
},
'S-1': {
callback: function() {
this._clearShortcutsModal();
if (document.getElementById('modal-gui-settings').
children.length > 0) {
this._clearSettingsModal();
} else {
this._displaySettingsModal();
}
},
help: 'GUI Settings',
label: 'Shift + !'
},
'S-/': {
callback: function() {
this._clearSettingsModal();
if (document.getElementById('modal-shortcuts').
children.length > 0) {
this._clearShortcutsModal();
} else {
this._displayShortcutsModal();
}
},
help: 'Display this help',
label: 'Shift + ?'
},
'S-+': {
fire: 'topo.zoom_in',
help: 'Zoom In',
label: 'Shift + "+"'
},
'S--': {
fire: 'topo.zoom_out',
help: 'Zoom Out',
label: 'Shift + -'
},
'S-0': {
fire: 'topo.panToCenter',
help: 'Center the model overview',
label: 'Shift + 0'
},
'esc': {
fire: 'topo.clearState',
callback: function() {
this._clearSettingsModal();
this._clearShortcutsModal();
},
help: 'Cancel current action',
label: 'Esc'
},
'S-d': {
callback: function(evt) {
views.utils.exportEnvironmentFile(this.db);
},
help: 'Export the model',
label: 'Shift + d'
}
},
/**
* Activate the keyboard listeners. Only called by the main index.html,
* not by the tests' one.
*
* @method activateHotkeys
*/
activateHotkeys: function() {
var key_map = {
'1': 49, '/': 191, '?': 63, '+': 187, '-': 189,
enter: 13, esc: 27, backspace: 8,
tab: 9, pageup: 33, pagedown: 34};
var code_map = {};
Object.keys(key_map).forEach(k => {
const v = key_map[k];
code_map[v] = k;
});
this._keybindings = document.addEventListener('keydown', evt => {
// Normalize key-code
// This gets triggered by different types of elements some YUI some
// React. So try and use the native tagName property first, if that
// fails then fall back to ReactDOM.findDOMNode().
var tagName = evt.target.tagName;
var contentEditable = evt.target.contentEditable;
var currentKey;
if (code_map[evt.keyCode]) {
currentKey = code_map[evt.which];
} else {
currentKey = String.fromCharCode(evt.which).toLowerCase();
}
if (!tagName) {
tagName = ReactDOM.findDOMNode(evt.target).tagName;
}
if (!contentEditable) {
contentEditable = ReactDOM.findDOMNode(evt.target).contentEditable;
}
// Don't ignore esc in the search box.
if (currentKey === 'esc' &&
evt.target.className === 'header-search__input') {
// Remove the focus from the search box.
evt.target.blur();
// Target filtering, we want to listen on window
// but not honor hotkeys when focused on
// text oriented input fields.
} else if (['INPUT', 'TEXTAREA'].indexOf(tagName) !== -1 ||
contentEditable === 'true') {
return;
}
var symbolic = [];
if (evt.ctrlKey) { symbolic.push('C');}
if (evt.altKey) { symbolic.push('A');}
if (evt.shiftKey) { symbolic.push('S');}
symbolic.push(currentKey);
var trigger = symbolic.join('-');
var spec = this.keybindings[trigger];
if (spec) {
if (spec.condition && !spec.condition.call(this)) {
// Note that when a condition check fails,
// the event still propagates.
return;
}
var target = document.querySelector(spec.target);
if (target) {
if (spec.toggle) {
if (target.classList.contains('hidden')) {
target.classList.remove('hidden');
} else {
target.classList.add('hidden');
}
}
if (spec.focus) { target.focus(); }
}
if (spec.callback) { spec.callback.call(this, evt, target); }
// HACK w/o context/view restriction but right direction
if (spec.fire) {
document.dispatchEvent(new Event(spec.fire));
}
// If we handled the event nothing else has to.
evt.stopPropagation();
}
});
},
/**
Return the current model unique identifier.
@method _getModelUUID
@return {String} The model UUID.
*/
_getModelUUID: function() {
return this.get('modelUUID') ||
(window.juju_config && window.juju_config.jujuEnvUUID);
},
/**
* @method initializer
* @param {Object} cfg Application configuration data.
*/
initializer: function(cfg) {
// If no cfg is passed in, use a default empty object so we don't blow up
// getting at things.
cfg = cfg || {};
// If this flag is true, start the application with the console activated.
var consoleEnabled = this.get('consoleEnabled');
// Concession to testing, they need muck with console, we cannot as well.
if (window.mochaPhantomJS === undefined) {
if (consoleEnabled) {
consoleManager.native();
} else {
consoleManager.noop();
}
}
/**
Reference to the juju.Cookies instance.
@property cookieHandler
@type {juju.Cookies}
@default null
*/
this.cookieHandler = null;
this.renderEnvironment = true;
// When a user drags a file over the browser we show notifications which
// are drop targets to illustrate what they can do with their selected
// file. This array keeps track of those masks and their respective
// handlers with a { mask: mask, handlers: handlers } format.
this.dragNotifications = [];
/**
The object used for storing a mapping of previously visited user paths
to the type of entity (model, store). e.g. /u/spinach/ghost would map to
store.
@property userPaths
@type {Map}
*/
this.userPaths = new Map();
// Track anonymous mode. This value will be set to true when anonymous
// navigation is allowed, in essence when a GISF anonymous user is being
// modeling on a new canvas.
this.anonymousMode = false;
const config = window.juju_config || {};
config.interactiveLogin = this.get('interactiveLogin');
// Set up a client side database to store state.
this.db = new models.Database();
// Create a user store to track authentication details.
const userCfg = {
externalAuth: this.get('auth'),
expiration: window.sessionStorage.getItem('expirationDatetime')
};
this.user = this.get('user') || new window.jujugui.User(userCfg);
// Instantiate a macaroon bakery, which is used to handle the macaroon
// acquisition over HTTP.
const webHandler = new Y.juju.environments.web.WebHandler();
const stateGetter = () => {
return this.state.current;
};
const cookieSetter = (value, callback) => {
this.get('charmstore').setAuthCookie(value, callback);
};
this.bakery = Y.juju.bakeryutils.newBakery(
config, this.user, stateGetter, cookieSetter, webHandler);
// Create and set up a new instance of the charmstore.
this._setupCharmstore(config, window.jujulib.charmstore);
// Create and set up a new instance of the bundleservice.
this._setupBundleservice(window.jujulib.bundleservice);
// Set up a new modelController instance.
this.modelController = new juju.ModelController({
db: this.db,
charmstore: this.get('charmstore')
});
let environments = juju.environments;
// This is wrapped to be called twice.
// The early return (at line 478) would state from being set (originally
// at line 514).
const setUpStateWrapper = function() {
// If there is no protocol in the baseURL then prefix the origin when
// creating state.
let baseURL = cfg.baseUrl;
if (baseURL.indexOf('://') < 0) {
baseURL = `${window.location.origin}${baseURL}`;
}
this.state = this._setupState(baseURL);
}.bind(this);
// Create an environment facade to interact with.
// Allow "env" as an attribute/option to ease testing.
var env = this.get('env');
if (env) {
setUpStateWrapper();
this._init(cfg, env, this.get('controllerAPI'));
return;
}
var ecs = new juju.EnvironmentChangeSet({db: this.db});
this.renderDeploymentBarListener = this._renderDeploymentBar.bind(this);
document.addEventListener(
'ecs.changeSetModified', this.renderDeploymentBarListener);
document.addEventListener(
'ecs.currentCommitFinished', this.renderDeploymentBarListener);
if (this.get('gisf')) {
document.body.classList.add('u-is-beta');
}
this.defaultPageTitle = 'Juju GUI';
let modelOptions = {
user: this.user,
ecs: ecs,
conn: this.get('conn'),
jujuCoreVersion: this.get('jujuCoreVersion'),
bundleService: this.get('bundleService')
};
let controllerOptions = Object.assign({}, modelOptions);
modelOptions.webHandler = new environments.web.WebHandler();
const modelAPI = new environments.GoEnvironment(modelOptions);
const controllerAPI = new Y.juju.ControllerAPI(controllerOptions);
// For analytics to work we need to set it up before state is set up.
// Relies on controllerAPI, is used by state
this.sendAnalytics = juju.sendAnalyticsFactory(
controllerAPI,
window.dataLayer
);
setUpStateWrapper();
this.defaultPageTitle = 'Juju GUI';
this._init(cfg, modelAPI, controllerAPI);
},
/**
Complete the application initialization.
@method _init
@param {Object} cfg Application configuration data.
@param {Object} modelAPI The environment instance.
@param {Object} controllerAPI The controller api instance.
*/
_init: function(cfg, modelAPI, controllerAPI) {
// Store the initial model UUID.
const modelUUID = this._getModelUUID();
this.set('modelUUID', modelUUID);
const controllerCreds = this.user.controller;
this.env = modelAPI;
// Generate the application state then see if we have to disambiguate
// the user portion of the state.
const pathState = this.state.generateState(window.location.href, false);
let entityPromise = null;
if (!pathState.error && pathState.state.user) {
// If we have a user component to the state then it is ambiguous.
// disambiguate the user state by checking if the user fragment
// represents a charm store entity.
entityPromise = this._fetchEntityFromUserState(pathState.state.user);
}
this.controllerAPI = this.setUpControllerAPI(
controllerAPI,
controllerCreds.user,
controllerCreds.password,
controllerCreds.macaroons,
entityPromise);
const getBundleChanges = this.controllerAPI.getBundleChanges.bind(
this.controllerAPI);
// Create Romulus API client instances.
this._setupRomulusServices(window.juju_config, window.jujulib);
// Set the modelAPI in the model controller here so
// that we know that it's been setup.
this.modelController.set('env', this.env);
// Create a Bundle Importer instance.
this.bundleImporter = new Y.juju.BundleImporter({
db: this.db,
modelAPI: this.env,
getBundleChanges: getBundleChanges,
makeEntityModel: Y.juju.makeEntityModel,
charmstore: this.get('charmstore'),
hideDragOverNotification: this._hideDragOverNotification.bind(this)
});
// Create the ACL object.
this.acl = new Y.juju.generateAcl(this.controllerAPI, this.env);
this.changesUtils = window.juju.utils.ChangesUtils;
this.relationUtils = window.juju.utils.RelationUtils;
// Listen for window unloads and trigger the unloadWindow function.
window.onbeforeunload = views.utils.unloadWindow.bind(this);
// When the environment name becomes available, display it.
this.env.after('environmentNameChange',
this.onEnvironmentNameChange, this);
this.env.after('defaultSeriesChange', this.onDefaultSeriesChange, this);
// Once we know about MAAS server, update the header accordingly.
let maasServer = this.env.get('maasServer');
if (!maasServer && this.controllerAPI) {
maasServer = this.controllerAPI.get('maasServer');
}
if (maasServer) {
this._displayMaasLink(maasServer);
} else {
if (this.controllerAPI) {
this.controllerAPI.once('maasServerChange', this._onMaasServer, this);
}
this.env.once('maasServerChange', this._onMaasServer, this);
}
// Feed environment changes directly into the database.
this.onDeltaBound = this.db.onDelta.bind(this.db);
document.addEventListener('delta', this.onDeltaBound);
// Handlers for adding and removing services to the service list.
this.endpointsController = new juju.EndpointsController({
db: this.db,
modelController: this.modelController
});
this.endpointsController.bind();
// Stash the location object so that tests can override it.
this.location = window.location;
// When the connection resets, reset the db, re-login (a delta will
// arrive with successful authentication), and redispatch.
this.env.after('connectedChange', evt => {
this._renderProviderLogo();
if (!evt.newVal) {
// The model is not connected, do nothing waiting for a reconnection.
console.log('model disconnected');
return;
}
console.log('model connected');
this.env.userIsAuthenticated = false;
// Attempt to log in if we already have credentials available.
const credentials = this.user.model;
if (credentials.areAvailable) {
this.loginToAPIs(null, !!credentials.macaroons, [this.env]);
return;
}
});
// If the database updates, redraw the view (distinct from model updates).
// TODO: bound views will automatically update this on individual models.
this.bound_on_database_changed = this.on_database_changed.bind(this);
document.addEventListener('update', this.bound_on_database_changed);
// Watch specific things, (add units), remove db.update above
// Note: This hides under the flag as tests don't properly clean
// up sometimes and this binding creates spooky interaction
// at a distance and strange failures.
this.db.machines.after(
['add', 'remove', '*:change'],
this.on_database_changed, this);
this.db.services.after(
['add', 'remove', '*:change'],
this.on_database_changed, this);
this.db.relations.after(
['add', 'remove', '*:change'],
this.on_database_changed, this);
this.db.environment.after(
['add', 'remove', '*:change'],
this.on_database_changed, this);
this.db.units.after(
['add', 'remove', '*:change'],
this.on_database_changed, this);
this.db.notifications.after('add', this._renderNotifications, this);
// When someone wants a charm to be deployed they fire an event and we
// show the charm panel to configure/deploy the service.
this._onInitiateDeploy = evt => {
this.deployService(evt.detail.charm, evt.detail.ghostAttributes);
};
document.addEventListener('initiateDeploy', this._onInitiateDeploy);
this._boundAppDragOverHandler = this._appDragOverHandler.bind(this);
// These are manually detached in the destructor.
['dragenter', 'dragover', 'dragleave'].forEach((eventName) => {
document.addEventListener(
eventName, this._boundAppDragOverHandler);
});
// In Juju >= 2 we connect to the controller and then to the model.
this.state.bootstrap();
},
/**
Sends the discharge token via POST to the storefront. This is used
when the GUI is operating in GISF mode, allowing a shared login between
the GUI and the storefront.
@method _sendGISFPostBack
*/
_sendGISFPostBack: function() {
const dischargeToken = this.user.getMacaroon('identity');
if (!dischargeToken) {
console.error('no discharge token in local storage after login');
return;
}
console.log('sending discharge token to storefront');
const content = 'discharge-token=' + dischargeToken;
const webhandler = new Y.juju.environments.web.WebHandler();
webhandler.sendPostRequest(
'/_login',
{'Content-Type': 'application/x-www-form-urlencoded'},
content);
},
/**
Auto log the user into the charm store as part of the login process
when the GUI operates in a GISF context.
*/
_ensureLoggedIntoCharmstore: function() {
if (!this.user.getMacaroon('charmstore')) {
this.get('charmstore').getMacaroon((err, macaroon) => {
if (err) {
console.error(err);
return;
}
this.storeUser('charmstore', true);
console.log('logged into charmstore');
});
}
},
/**
Creates the second instance of the WebSocket for communication with
the Juju controller if it's necessary. A username and password must be
supplied if you're connecting to a standalone Juju controller and not to
one which requires macaroon authentication.
@method setUpControllerAPI
@param {Object} controllerAPI Instance of the GoEnvironment class.
@param {String} user The username if not using macaroons.
@param {String} password The password if not using macaroons.
@param {Array} macaroons A list of macaroons that the user has saved.
@param {Promise} entityPromise A promise with the entity if any.
@return {environments.GoEnvironment} An instance of the environment class
with the necessary events attached and values set. Or undefined if
we're in a legacy juju model and no controllerAPI instance was supplied.
*/
setUpControllerAPI: function(
controllerAPI, user, password, macaroons, entityPromise) {
this.user.controller = { user, password, macaroons };
this.controllerLoginHandler = evt => {
const state = this.state;
const current = this.state.current;
this.anonymousMode = false;
if (evt.detail && evt.detail.err) {
this._renderLogin(evt.detail.err);
return;
}
this._renderUserMenu();
console.log('successfully logged into controller');
// If the GUI is embedded in storefront, we need to share login
// data with the storefront backend and ensure we're already
// logged into the charmstore.
if (this.get('gisf')) {
this._sendGISFPostBack();
this._ensureLoggedIntoCharmstore();
}
// If state has a `next` property then that overrides all defaults.
const specialState = current.special;
const next = specialState && specialState.next;
const dd = specialState && specialState.dd;
if (state.current.root === 'login') {
if (dd) {
console.log('initiating direct deploy');
this.maskVisibility(false);
this._directDeploy(dd);
return;
} else if (next) {
// There should never be a `next` state if we aren't on login but
// adding the state login check here just to be sure.
console.log('redirecting to "next" state', next);
const {error, state: newState} = state.generateState(next, false);
if (error === null) {
// The root at this point will be 'login' and because the `next`
// url may not explicitly define a new root path we have to set it
// to null to clear 'login' from the url.
if (!newState.root) {
newState.root = null;
}
newState.special = null;
this.maskVisibility(false);
state.changeState(newState);
return;
}
console.error('error redirecting to previous state', error);
return;
}
}
// If the user is connected to a model then the modelList will be
// fetched by the modelswitcher component.
if (this.env.get('modelUUID')) {
return;
}
const modelUUID = this._getModelUUID();
if (modelUUID && !current.profile && current.root !== 'store') {
// A model uuid was defined in the config so attempt to connect to it.
this._listAndSwitchModel(null, modelUUID);
} else if (entityPromise !== null) {
this._disambiguateUserState(entityPromise);
} else {
// Drop into disconnected mode and show the profile but only if there
// is no state defined in root or store. If there is a state defined
// either of those then we want to let that dispatcher handle the
// routing.
this.maskVisibility(false);
const isLogin = current.root === 'login';
const previousState = state.previous;
const previousRoot = previousState && previousState.root || null;
// If there was a previous root before the login then redirect to that
// otherwise go to the profile.
let newState = {
// We don't want to redirect to the previous root if it was the
// login page.
profile: previousRoot && previousRoot !== 'login' ?
null : current.profile,
root: isLogin ? previousRoot : current.root
};
// If the current root is 'login' after logging into the controller,
// and there is no root, no store and no profile defined then we
// want to render the users profile.
if (
!current.store &&
!newState.profile &&
newState.root !== 'account' &&
(isLogin || !current.root) &&
this.get('gisf')
) {
newState.profile = this.user.displayName;
}
state.changeState(newState);
}
};
document.addEventListener('login', this.controllerLoginHandler);
controllerAPI.after('connectedChange', evt => {
if (!evt.newVal) {
// The controller is not connected, do nothing waiting for a
// reconnection.
console.log('controller disconnected');
return;
}
console.log('controller connected');
const creds = this.user.controller;
const gisf = this.get('gisf');
const currentState = this.state.current;
const rootState = currentState ? currentState.root : null;
// If an anonymous GISF user lands on the GUI at /new then don't
// attempt to log into the controller.
if ((
!creds.areAvailable && gisf && rootState === 'new'
) || (
this.anonymousMode && rootState !== 'login'
)) {
this.anonymousMode = true;
console.log('now in anonymous mode');
this.maskVisibility(false);
return;
}
if (!creds.areAvailable ||
// When using direct deploy when a user is not logged in it will
// navigate to show the login if we do not have this state check.
(currentState.special && currentState.special.dd)) {
this._displayLogin();
return;
}
// If macaroons are available or if we have an external token from
// Keystone, then proceed with the macaroons based authentication.
if (creds.macaroons || creds.areExternal) {
this.loginToAPIs(null, true, [this.controllerAPI]);
return;
}
// The traditional user/password authentication does not make sense if
// the GUI is embedded in the storefront.
if (!gisf) {
this.loginToAPIs(null, false, [this.controllerAPI]);
}
});
controllerAPI.set('socket_url',
this.createSocketURL(this.get('controllerSocketTemplate')));
return controllerAPI;
},
/**
Handles logging into both the env and controller api WebSockets.
@method loginToAPIs
@param {Object} credentials The credentials for the controller APIs.
@param {Boolean} useMacaroons Whether to use macaroon based auth
(macaraq) or simple username/password auth.
@param {Array} apis The apis instances that we should be logging into.
Defaults to [this.controllerAPI, this.env].
*/
loginToAPIs: function(
credentials, useMacaroons, apis=[this.controllerAPI, this.env]) {
if (useMacaroons) {
apis.forEach(api => {
// The api may be unset if the current Juju does not support it.
if (api && api.get('connected')) {
console.log(`logging into ${api.name} with macaroons`);
api.loginWithMacaroon(
this.bakery,
this._apiLoginHandler.bind(this, api));
}
});
return;
}
apis.forEach(api => {
// The api may be unset if the current Juju does not support it.
if (!api) {
return;
}
// Ensure the credentials are set, if available.
if (credentials && api.name === 'model-api') {
this.user.model = credentials;
} else if (credentials) {
this.user.controller = credentials;
}
if (api.get('connected')) {
console.log(`logging into ${api.name} with user and password`);
api.login();
}
});
},
/**
Callback handler for the API loginWithMacaroon method which handles
the "redirection required" error message.
@method _apiLoginHandler
@param {Object} api The API that the user is attempting to log into.
ex) this.env or this.controllerAPI
@param {String} err The login error message, if any.
*/
_apiLoginHandler: function(api, err) {
if (this.state.current.root === 'login') {
this.state.changeState({root: null});
}
if (!err) {
return;
}
if (!views.utils.isRedirectError(err)) {
// There is nothing to do in this case, and the user is already
// prompted with the error in the login view.
console.log(`cannot log into ${api.name}: ${err}`);
return;
}
// If the error is that redirection is required then we have to
// make a request to get the appropriate model connection information.
console.log(`redirection required for loggin into ${api.name}`);
api.redirectInfo((err, servers) => {
if (err) {
this.db.notifications.add({
title: 'Unable to log into Juju',
message: err,
level: 'error'
});
return;
}
// Loop through the available servers and find the public IP.
const hosts = servers[0];
const publicHosts = hosts.filter(host => host.scope === 'public');
if (!publicHosts.length) {
this.db.notifications.add({
title: 'Model connection error',
message: 'Cannot find a public host for connecting to the model',
level: 'error'
});
console.error('no public hosts found: ' + JSON.stringify(servers));
return;
}
const publicHost = publicHosts[0];
// Switch to the redirected model.
// Make sure we keep the change set by not clearing the db when
// creating a model with change set (last param false).
this.switchEnv(this.createSocketURL(
this.get('socketTemplate'),
this.get('modelUUID'), publicHost.value, publicHost.port), null,
null, null, true, false);
});
},
/**
Renders the login component.
@method _renderLogin
@param {String} err Possible authentication error, or null if no error
message must be displayed.
*/
_renderLogin: function(err) {
document.getElementById('loading-message').style.display = 'none';
// XXX j.c.sackett 2017-01-30 Right now USSO link is using
// loginToController, while loginToAPIs is used by the login form.
// We want to use loginToAPIs everywhere since it handles more.
const loginToController =
this.controllerAPI.loginWithMacaroon.bind(
this.controllerAPI, this.bakery);
const controllerIsConnected = () => {
return this.controllerAPI && this.controllerAPI.get('connected');
};
ReactDOM.render(
<window.juju.components.Login
controllerIsConnected={controllerIsConnected}
errorMessage={err}
gisf={this.get('gisf')}
loginToAPIs={this.loginToAPIs.bind(this)}
loginToController={loginToController} />,
document.getElementById('login-container'));
},
/**
Renders the Log out component or log in link depending on the
environment the GUI is executing in.
*/
_renderUserMenu: function() {
const controllerAPI = this.controllerAPI;
const linkContainerId = 'profile-link-container';
const linkContainer = document.getElementById(linkContainerId);
if (!linkContainer) {
console.error(`no linkContainerId: ${linkContainerId}`);
return;
}
const charmstore = this.get('charmstore');
const bakery = this.bakery;
const USSOLoginLink = (<window.juju.components.USSOLoginLink
displayType={'text'}
loginToController={controllerAPI.loginWithMacaroon.bind(
controllerAPI, bakery)}
/>);
let logoutUrl = '/logout';
if (window.juju_config.baseUrl) {
logoutUrl = window.juju_config.baseUrl.replace(/\/?$/, logoutUrl);
}
const doCharmstoreLogout = () => {
return this.getUser('charmstore') && !this.get('gisf');
};
const LogoutLink = (<window.juju.components.Logout
charmstoreLogoutUrl={charmstore.getLogoutUrl()}
doCharmstoreLogout={doCharmstoreLogout}
locationAssign={window.location.assign.bind(window.location)}
logoutUrl={logoutUrl}
// If the charmbrowser is open then don't show the logout link.
visible={!this.state.current.store}
/>);
const navigateUserProfile = () => {
const username = this.user.displayName;
if (!username) {
return;
}
views.utils.showProfile(
this.env && this.env.get('ecs'),
this.state.changeState.bind(this.state),
username);
};
const navigateUserAccount = () => {
const username = this.user.displayName;
if (!username) {
return;
}
views.utils.showAccount(
this.env && this.env.get('ecs'),
this.state.changeState.bind(this.state));
};
ReactDOM.render(<window.juju.components.UserMenu
controllerAPI={controllerAPI}
LogoutLink={LogoutLink}
navigateUserAccount={navigateUserAccount}
navigateUserProfile={navigateUserProfile}
USSOLoginLink={USSOLoginLink}
/>, linkContainer);
},
/**
Renders the user profile component.
@method _renderUserProfile
@param {Object} state - The app state.
@param {Function} next - Call to continue dispatching.
*/
_renderUserProfile: function(state, next) {
// XXX Jeff - 1-2-2016 - Because of a bug in the state system the profile
// view renders itself and then makes requests to identity before the
// controller is setup and the user has successfully logged in. As a
// temporary workaround we will just prevent rendering the profile until
// the controller is connected.
// XXX frankban: it seems that the profile is rendered even when the
// profile is not included in the state.
const guiState = state.gui || {};
if (
guiState.deploy !== undefined ||
!state.profile ||
!this.controllerAPI.get('connected') ||
!this.controllerAPI.userIsAuthenticated
) {
return;
}
// XXX Jeff - 18-11-2016 - This profile gets rendered before the
// controller has completed connecting and logging in when in gisf. The
// proper fix is to queue up the RPC calls but due to time constraints
// we're setting up this handler to simply re-render the profile when
// the controller is properly connected.
const facadesExist = !!this.controllerAPI.get('facades');
if (!facadesExist) {
const handler = this.controllerAPI.after('facadesChange', e => {
if (e.newVal) {
this._renderUserProfile(state, next);
handler.detach();
}
});
}
const charmstore = this.get('charmstore');
const utils = views.utils;
const currentModel = this.get('modelUUID');
// When going to the profile view, we are theoretically no longer
// connected to any model. Setting the current model identifier to null
// also allows switching to the same model from the profile view.