forked from juju/juju-gui
/
app.js
1395 lines (1271 loc) · 44.3 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';
var spinner;
/**
* 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;
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'),
importHelpers = juju.BundleHelpers;
/**
* The main app class.
*
* @class App
*/
var JujuGUI = Y.Base.create('juju-gui', Y.App, [
Y.juju.SubAppRegistration,
Y.juju.NSRouter,
Y.juju.Cookies,
Y.juju.GhostDeployer], {
/*
Extension properties
*/
subApplications: [{
type: Y.juju.subapps.Browser,
config: {}
}],
defaultNamespace: 'charmbrowser',
/*
End extension properties
*/
/**
* Views
*
* The views encapsulate the functionality blocks that output
* the GUI pages. The "parent" attribute defines the hierarchy.
*
* @attribute views
*/
views: {
login: {
type: 'juju.views.login',
preserve: false
},
environment: {
type: 'juju.views.environment',
preserve: true
},
notifications: {
type: 'juju.views.NotificationsView',
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.
*
* All are optional.
*/
keybindings: {
'A-s': {
target: '#charm-search-field',
focus: true,
help: 'Select the charm Search'
},
'/': {
target: '#charm-search-field',
focus: true,
help: 'Select the charm Search'
},
'S-/': {
target: '#shortcut-help',
toggle: true,
callback: function(evt, target) {
// This could be its own view.
if (target && !target.getHTML().length) {
var bindings = [];
Y.each(this.keybindings, function(v, k) {
if (v.help && (v.condition === undefined ||
v.condition.call(this) === true)) {
// TODO: translate keybindings to
// human <Alt> m
// <Control> <Shift> N (note caps)
// also 'g then i' style
bindings.push({key: k, help: v.help});
}
}, this);
target.setHTML(
views.Templates.shortcuts({bindings: bindings}));
}
},
help: 'Display this help'
},
'A-e': {
callback: function(evt) {
this.fire('navigateTo', { url: '/:gui:/' });
},
help: 'Navigate to the Environment overview.'
},
'S-+': {
fire: 'zoom_in',
help: 'Zoom In'
},
'S--': {
fire: 'zoom_out',
help: 'Zoom Out'
},
'S-0': {
fire: 'panToCenter',
help: 'Center the Environment overview'
},
'esc': {
fire: 'clearState',
callback: function() {
// Explicitly hide anything we might care about.
Y.one('#shortcut-help').hide();
},
help: 'Cancel current action'
},
'C-s': {
'condition': function() {
return this._simulator !== undefined;
},
callback: function() {
this._simulator.toggle();
},
help: 'Toggle the simulator'
},
'S-d': {
callback: function(evt) {
this.exportYAML();
},
help: 'Export the environment'
},
'C-S-d': {
callback: function(evt) {
Y.fire('saveWebsocketLog');
},
help: 'Save the websocket log to a file'
}
},
/**
* Data driven behaviors.
*
* Placeholder for real behaviors associated with DOM Node data-*
* attributes.
*
* @attribute behaviors
*/
behaviors: {
timestamp: {
/**
* Wait for the DOM to be built before rendering timestamps.
*
* @method behaviors.timestamp.callback
*/
callback: function() {
Y.later(6000, this, function(o) {
Y.one('body')
.all('[data-timestamp]')
.each(function(node) {
node.setHTML(views.humanizeTimestamp(
node.getAttribute('data-timestamp')));
});
}, [], true);}
}
},
/**
* Activate the keyboard listeners. Only called by the main index.html,
* not by the tests' one.
*
* @method activateHotkeys
*/
activateHotkeys: function() {
var key_map = {
'/': 191, '?': 63, '+': 187, '-': 189,
enter: 13, esc: 27, backspace: 8,
tab: 9, pageup: 33, pagedown: 34};
var code_map = {};
Y.each(key_map, function(v, k) {
code_map[v] = k;
});
this._keybindings = Y.one(window).on('keydown', function(evt) {
//Normalize key-code
var source = evt.target.getDOMNode();
// Target filtering, we want to listen on window
// but not honor hotkeys when focused on
// text oriented input fields
if (['INPUT', 'TEXTAREA'].indexOf(source.tagName) !== -1) {
return;
}
var symbolic = [];
if (evt.ctrlKey) { symbolic.push('C');}
if (evt.altKey) { symbolic.push('A');}
if (evt.shiftKey) { symbolic.push('S');}
if (code_map[evt.keyCode]) {
symbolic.push(code_map[evt.which]);
} else {
symbolic.push(String.fromCharCode(evt.which).toLowerCase());
}
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 = Y.one(spec.target);
if (target) {
if (spec.toggle) {
if (target.getStyle('display') !== 'none') {
target.hide();
} else {
target.show();
}
}
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) {
this.views.environment.instance.topo.fire(spec.fire);
}
// If we handled the event nothing else has to.
evt.stopPropagation();
evt.preventDefault();
}
}, this);
},
/**
* @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 || {};
window.flags = window.flags || {};
// 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();
}
}
if (window.flags && window.flags.websocket_capture) {
this.websocketLogging = new Y.juju.WebsocketLogging();
}
/**
Reference to the juju.Cookies instance.
@property cookieHandler
@type {juju.Cookies}
@default null
*/
this.cookieHandler = null;
this.renderEnvironment = true;
// If this property has a value other than '/' then
// navigate to it after logging in.
this.redirectPath = '/';
// This attribute is used by the namespaced URL tracker.
// _routeSeen is part of a mechanism to prevent non-namespaced routes
// from being processed multiple times when multiple namespaces are
// present in the URL. The data structure is reset for each URL (in
// _dispatch). It holds a mapping between route callback uids and a
// flag to indicate that the callback has been used.
this._routeSeen = {};
// Create a client side database to store state.
this.db = new models.Database();
// Set up a new modelController instance.
this.modelController = new juju.ModelController({
db: this.db,
store: this.get('store')
});
// Update the on-screen environment name provided in the configuration,
// or a default if none is configured.
var environment_name = this.get('environment_name') || 'Environment',
environment_node = Y.one('#environment-name');
// Some tests do not fully populate the DOM, so we check to be sure.
if (Y.Lang.isValue(environment_node)) {
environment_node.set('text', environment_name);
}
// Create an environment facade to interact with.
// Allow "env" as an attribute/option to ease testing.
if (this.get('env')) {
this.env = this.get('env');
} else {
// Calculate the socket_url.
var socketUrl = this.get('socket_url');
var socketPort = this.get('socket_port');
var socketProtocol = this.get('socket_protocol');
if (socketPort || socketProtocol) {
// Assemble a socket URL from the Location.
var loc = Y.getLocation();
socketPort = socketPort || loc.port;
socketProtocol = socketProtocol || 'wss';
socketUrl = socketProtocol + '://' + loc.hostname;
if (socketPort) {
socketUrl += ':' + socketPort;
}
socketUrl += '/ws';
this.set('socket_url', socketUrl);
}
// Instantiate the environment specified in the configuration, choosing
// between the available implementations, currently Go and Python.
var envOptions = {
socket_url: socketUrl,
user: this.get('user'),
password: this.get('password'),
readOnly: this.get('readOnly'),
conn: this.get('conn')
};
var apiBackend = this.get('apiBackend');
if (this.get('sandbox')) {
var sandboxModule = Y.namespace('juju.environments.sandbox');
var State = Y.namespace('juju.environments').FakeBackend;
var state = new State({store: this.get('store')});
if (envOptions.user && envOptions.password) {
var credentials = {};
credentials[envOptions.user] = envOptions.password;
state.set('authorizedUsers', credentials);
}
if (apiBackend === 'python') {
envOptions.conn = new sandboxModule.ClientConnection(
{juju: new sandboxModule.PyJujuAPI({state: state})});
} else if (apiBackend === 'go') {
envOptions.conn = new sandboxModule.ClientConnection(
{juju: new sandboxModule.GoJujuAPI({state: state})});
} else {
// Clean ourselves up before giving up the ghost, for tests' sake.
this.destroy();
throw 'unrecognized backend type: ' + apiBackend;
}
}
this.env = juju.newEnvironment(envOptions, apiBackend);
}
// Create an event simulator where possible.
// Starting the simulator is handled by hotkeys
// and/or the config setting 'simulateEvents'.
this.simulateEvents();
// Set the env in the model controller here so
// that we know that it's been setup.
this.modelController.set('env', this.env);
// Create notifications controller
this.notifications = new juju.NotificationController({
app: this,
env: this.env,
notifications: this.db.notifications});
this.on('*:navigateTo', function(e) {
this.navigate(e.url);
}, this);
// Notify user attempts to modify the environment without permission.
this.env.on('permissionDenied', this.onEnvPermissionDenied, this);
// When the provider type and environment names become available,
// display them.
this.env.after('providerTypeChange', this.onProviderTypeChange, this);
this.env.after('environmentNameChange',
this.onEnvironmentNameChange, this);
this.env.after('defaultSeriesChange', this.onDefaultSeriesChange, this);
// Once the user logs in, we need to redraw.
this.env.after('login', this.onLogin, this);
// Feed environment changes directly into the database.
this.env.on('delta', this.db.onDelta, this.db);
// Feed delta changes to the notifications system.
this.env.on('delta', this.notifications.generate_notices,
this.notifications);
// 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', function(ev) {
if (ev.newVal === true) {
this.db.reset();
this.env.userIsAuthenticated = false;
// Do not attempt environment login without credentials.
var credentials = this.env.getCredentials();
if (credentials && credentials.areAvailable) {
this.env.login();
} else {
// The user can also try to log in with an authentication token.
// This will look like ?authtoken=AUTHTOKEN. For instance,
// in the sandbox, try logging in with ?authtoken=demoToken.
// To get a real token from the Juju GUI charm's environment
// proxy, within an authenticated websocket session, use a
// request like this:
// {
// 'RequestId': 42,
// 'Type': 'GUIToken',
// 'Request': 'Create',
// 'Params': {},
// }
// You can then use the token once until it expires, within two
// minutes of this writing.
var querystring = this.location.search.substring(1);
var qs = Y.QueryString.parse(querystring);
var authtoken = qs.authtoken;
if (Y.Lang.isValue(authtoken)) {
// De-dupe if necessary.
if (Y.Lang.isArray(authtoken)) {
authtoken = authtoken[0];
}
// Try a token login.
this.env.tokenLogin(authtoken);
} else {
this.checkUserCredentials();
}
}
}
}, this);
// If the database updates, redraw the view (distinct from model updates).
// TODO: bound views will automatically update this on individual models.
this.db.on('update', this.on_database_changed, this);
this.enableBehaviors();
this.once('ready', function(e) {
if (this.get('socket_url') || this.get('sandbox')) {
// Connect to the environment.
this.env.connect();
}
if (this.get('activeView')) {
this.get('activeView').render();
} else {
this.dispatch();
}
this._renderHelpDropdownView();
}, this);
Y.one(Y.config.win).on('resize', function(e) {
this._displayZoomMessage();
}, this);
// Halt the default navigation on the juju logo to allow us to show
// the real root view without namespaces
var navNode = Y.one('#nav-brand-env');
// Tests won't have this node.
if (navNode) {
navNode.on('click', function(e) {
e.halt();
this.showRootView();
}, this);
}
Y.one('#logout-trigger').on('click', function(e) {
// If this is not a Get Juju link then allow it to work as normal.
if (!this.get('showGetJujuButton')) {
e.halt();
this.logout();
}
}, this);
var exportNode = Y.one('#export-trigger');
// Tests won't have this node.
if (exportNode) {
exportNode.on('click', function(e) {
e.halt();
this.exportYAML();
}, this);
}
var importNode = Y.one('#import-trigger');
var importFileInput = Y.one('.import-export input[type=file]');
// Tests won't have this node.
if (importNode && importFileInput) {
importNode.on('click', function(e) {
e.halt();
e.currentTarget.siblings('input[type=file]')
.item(0).getDOMNode().click();
});
importFileInput.on('change', function(e) {
importHelpers.deployBundleFiles(
e.currentTarget.get('files')._nodes,
this.env,
this.db
);
}, this);
}
// Attach SubApplications. The subapps should share the same db.
cfg.db = this.db;
// To use the new service Inspector use the deploy method
// from the Y.juju.GhostDeployer extension
cfg.deployService = Y.bind(this.deployService, this);
// Provide the bundle deployment helper to the subapps and views to
// access in case of an UX interaction that triggers a bundle deploy.
// Grab a reference of these for the nested event calls below.
var env = this.env;
var db = this.db;
cfg.deployBundle = function(bundle, bundleId) {
// The other views will hand us an Object vs a YAML string. The import
// helpers want the yaml string instead.
importHelpers.deployBundle(
Y.JSON.stringify({
bundle: bundle
}),
bundleId,
env,
db
);
};
// 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.services.after(
['add', 'remove', '*:change'],
this.on_database_changed, this);
this.db.relations.after(
['add', 'remove', '*:change'],
this.on_database_changed, this);
// Share the store instance with subapps.
cfg.store = this.get('store');
cfg.envSeries = this.env.get('defaultSeries');
this.addSubApplications(cfg);
// When someone wants a charm to be deployed they fire an event and we
// show the charm panel to configure/deploy the service.
Y.on('initiateDeploy', function(charm, ghostAttributes) {
cfg.deployService(charm, ghostAttributes);
}, this);
},
/**
* Handles rendering the help dropdown view on application load.
*
* @method _renderHelpDropdownView
*/
_renderHelpDropdownView: function() {
this.helpDropdown = new views.HelpDropdownView({
container: Y.one('#help-dropdown'),
env: this.db.environment
}).render();
// See `renderOnboarding()` in browser.js and `_startOnboarding()`
// in help-dropdown.js for why this is done like this.
this.helpDropdown.on('navigate', function(e) {
this.navigate(e.url);
}, this);
},
/**
* Display a message when the browser is too small to work.
*
* @method _displayZoomMessage
*/
_displayZoomMessage: function() {
if (Y.UA.os === 'macintosh') {
var metaKey = 'command';
} else {
var metaKey = 'ctrl';
}
// Only display the message once otherwise the message will continually
// fire while the browser is being resized or zoomed.
if (!this.zoomMessageDisplayed &&
Y.one('body').get('winWidth') <= 1024) {
this.db.notifications.add(
new models.Notification({
title: 'Browser too small',
message: 'This browser window is too small to display the Juju' +
'GUI properly. Try using "' + metaKey +
'+-" to zoom the window.',
level: 'error'
})
);
this.zoomMessageDisplayed = true;
}
},
/**
Export the YAML for this environment.
@method exportYAML
*/
exportYAML: function() {
var result = this.db.exportDeployer();
var exportData = jsyaml.dump(result);
var exportBlob = new Blob([exportData],
{type: 'application/yaml;charset=utf-8'});
saveAs(exportBlob, 'export.yaml');
},
/**
Start the simulator if it can start and it has not already been started.
@method simulateEvents
*/
simulateEvents: function() {
if (!this._simulator && this.env) {
// Try/Catch this to allow mocks in tests.
try {
var conn = this.env.get('conn');
var juju = conn && conn.get('juju');
var state = juju && juju.get('state');
if (state) {
var Simulator = Y.namespace('juju.environments').Simulator;
this._simulator = new Simulator({state: state});
if (this.get('simulateEvents')) {
this._simulator.start();
}
}
}
catch (err) {
// Unable to create simulator, usually due to mocks or an
// unsupported environment
console.log('Unable to create simulator: ');
}
}
},
/**
Release resources and inform subcomponents to do the same.
@method destructor
*/
destructor: function() {
if (this.helpDropdown) {
this.helpDropdown.destroy();
}
if (this._keybindings) {
this._keybindings.detach();
}
if (this._simulator) {
this._simulator.stop();
}
Y.each(
[this.env, this.db, this.notifications,
this.endpointsController],
function(o) {
if (o && o.destroy) {
o.detachAll();
o.destroy();
}
}
);
},
/**
* Hook up all of the declared behaviors.
*
* @method enableBehaviors
*/
enableBehaviors: function() {
Y.each(this.behaviors, function(behavior) {
behavior.callback.call(this);
}, this);
},
/**
* On database changes update the view.
*
* @method on_database_changed
*/
on_database_changed: function(evt) {
Y.log(evt, 'debug', 'App: Database changed');
// Database changed event is fired when the user logs-in but we deal with
// that case manually so we don't need to dispatch the whole application.
// This whole handler can be removed once we go to model bound views.
if (window.location.pathname.match(/login/)) {
return;
}
// This timeout helps to reduce the number of needless dispatches from
// upwards of 8 to 2. At least until we can move to the model bound views.
if (this.dbChangedTimer) {
this.dbChangedTimer.cancel();
}
this.dbChangedTimer = Y.later(100, this, this._dbChangedHandler);
return;
},
/**
After the db has changed and the timer has timed out to reduce repeat
calls then this is called to handle the db updates.
@method _dbChangedHandler
@private
*/
_dbChangedHandler: function() {
var active = this.get('activeView');
// Regardless of which view we are rendering,
// update the env view on db change.
if (this.views.environment.instance) {
this.views.environment.instance.topo.update();
}
// Redispatch to current view to update.
if (active && active.name === 'EnvironmentView') {
active.rendered();
} else {
this.dispatch();
}
},
// Route handlers
/**
* Show the login screen.
*
* @method showLogin
* @return {undefined} Nothing.
*/
showLogin: function() {
this.showView('login', {
env: this.env,
help_text: this.get('login_help')
});
var passwordField = this.get('container').one('input[type=password]');
// The password field may not be present in testing context.
if (passwordField) {
passwordField.focus();
}
},
/**
* Log the current user out and show the login screen again.
*
* @method logout
* @param {Object} req The request.
* @return {undefined} Nothing.
*/
logout: function(req) {
// If the environment view is instantiated, clear out the topology local
// database on log out, because we clear out the environment database as
// well. The order of these is important because we need to tell
// the env to log out after it has navigated to make sure that
// it always shows the login screen.
var environmentInstance = this.views.environment.instance;
if (environmentInstance) {
environmentInstance.topo.update();
}
this.set('loggedIn', false);
this.env.logout();
return;
},
// Persistent Views
/**
* `notifications` is a preserved view that remains rendered on all main
* views. We manually create an instance of this view and insert it into
* the App's view metadata.
*
* @method show_notifications_view
*/
show_notifications_view: function(req, res, next) {
var view = this.getViewInfo('notifications'),
instance = view.instance;
if (!instance) {
view.instance = new views.NotificationsView(
{container: Y.one('#notifications'),
env: this.env,
notifications: this.db.notifications,
nsRouter: this.nsRouter
});
view.instance.render();
}
next();
},
/**
* Ensure that the current user has authenticated.
*
* @method checkUserCredentials
* @param {Object} req The request.
* @param {Object} res ???
* @param {Object} next The next route handler.
*
*/
checkUserCredentials: function(req, res, next) {
// If the Juju environment is not connected, exit without letting the
// route dispatch proceed. On env connection change, the app will
// re-dispatch and this route callback will be executed again.
if (!this.env || !this.env.get('connected')) {
return;
}
var credentials = this.env.getCredentials();
// After re-arranging the execution order of our routes to support the
// new :gui: namespace we were unable to log out on prod build in Ubuntu
// chrome. It appeared to be because credentials was null so the log in
// form was never shown - this handles that edge case.
var noCredentials = !(credentials && credentials.areAvailable);
if (noCredentials) {
this.set('loggedIn', false);
// If there are no stored credentials redirect to the login page
if (!req || req.path !== '/login/') {
// Set the original requested path in the event the user has
// to log in before continuing.
this.redirectPath = this.get('currentUrl');
this.navigate('/login/', { overrideAllNamespaces: true });
return;
}
} else if (!this.get('loggedIn')) {
return;
}
next();
},
/**
* Notify with an error when the user tries to change the environment
* without permission.
*
* @method onEnvPermissionDenied
* @private
* @param {Object} evt An event object (with "title" and "message"
attributes).
* @return {undefined} Mutates only.
*/
onEnvPermissionDenied: function(evt) {
this.db.notifications.add(
new models.Notification({
title: evt.title,
message: evt.message,
level: 'error'
})
);
},
/**
Get the path to which we should redirect after logging in. Clear it out
afterwards so it is clear that we've consumed it.
This is logic from the onLogin method factored out to make it easier to
test.
@method popLoginRedirectPath
@private
@return {String} the path to which we should redirect.
*/
popLoginRedirectPath: function() {
var result = this.redirectPath;
delete this.redirectPath;
var currentPath = this.get('currentUrl');
var loginPath = /^\/login(\/|$)/;
if (currentPath !== '/' && !loginPath.test(currentPath)) {
// We used existing credentials or a token to go directly to a url.
result = currentPath;
} else if (!result || loginPath.test(result)) {
result = '/';
}
return result;
},
/**
* Hide the login mask and redispatch the router.
*
* When the environment gets a response from a login attempt,
* it fires a login event, to which this responds.
*
* @method onLogin
* @param {Object} e An event object (with a "data.result" attribute).
* @private
*/
onLogin: function(e) {
if (e.data.result) {
// The login was a success.
this.hideMask();
var redirectPath = this.popLoginRedirectPath();
this.set('loggedIn', true);
// Handle token authentication.
if (e.data.fromToken) {
// Alert the user. In the future, we might want to call out the
// password so the user can note it. That will probably want a
// modal or similar.
this.env.onceAfter('environmentNameChange', function() {
this.db.notifications.add(
new models.Notification({
title: 'Logged in with Token',
message: ('You have successfully logged in with a ' +
'single-use authentication token.'),
level: 'important'
})
);
}, this);
}
this.navigate(redirectPath, {overrideAllNamespaces: true});
// If the redirectPath has a hash then it will not dispatch after log in
// because navigateOnHash is set to false so that we can use hash's to
// show the correct tab in the charm details pages. This issue only
// presents itself until the next delta comes in and the application
// hits it's double dispatch and dispatches the url again. As a
// workaround we check if there is a hash in the url and then dispatch
// manually.
if (redirectPath.indexOf('#') > -1) {
this.dispatch();
}
} else {
this.showLogin();
}
},
/**
Hides the fullscreen mask and stops the spinner.