Cleaning up compilation warnings
[moonshot-ui.git] / src / moonshot-identity-dialog.vala
1 /*
2  * Copyright (c) 2016, JANET(UK)
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  *
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * 3. Neither the name of JANET(UK) nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31 */
32
33 using Gee;
34 using Gtk;
35
36
37 // Defined here as workaround for emacs vala-mode indentation failure.
38 #if VALA_0_12
39 static const string CANCEL = Stock.CANCEL;
40 #else
41 static const string CANCEL = STOCK_CANCEL;
42 #endif
43
44
45 // For use when exporting certificates.
46 static string export_directory = null;
47
48 class IdentityDialog : Dialog
49 {
50     private static Gdk.Color white = make_color(65535, 65535, 65535);
51     private static Gdk.Color selected_color = make_color(0xd9 << 8, 0xf7 << 8, 65535);
52
53     private static MoonshotLogger logger = get_logger("IdentityDialog");
54
55     static const string displayname_labeltext = _("Display Name");
56     static const string realm_labeltext = _("Realm");
57     static const string username_labeltext = _("Username");
58     static const string password_labeltext = _("Password");
59
60     private Entry displayname_entry;
61     private Label displayname_label;
62     private Entry realm_entry;
63     private Label realm_label;
64     private Entry username_entry;
65     private Label username_label;
66     private Entry password_entry;
67     private Label password_label;
68     private CheckButton remember_checkbutton;
69     private Label message_label;
70     public bool complete;
71     private IdCard card;
72
73     private Label selected_item = null;
74
75     // Whether to clear the card's TrustAnchor after the user selects OK
76     internal bool clear_trust_anchor = false;
77
78     public string display_name {
79         get { return displayname_entry.get_text(); }
80     }
81
82     public string issuer {
83         get { return realm_entry.get_text(); }
84     }
85
86     public string username {
87         get { return username_entry.get_text(); }
88     }
89
90     public string password {
91         get { return password_entry.get_text(); }
92     }
93
94     public bool store_password {
95         get { return remember_checkbutton.active; }
96     }
97
98     internal ArrayList<string> get_services()
99     {
100         return card.services;
101     }
102
103     public IdentityDialog(IdentityManagerView parent)
104     {
105         this.with_idcard(null, _("Add ID Card"), parent);
106     }
107
108     public IdentityDialog.with_idcard(IdCard? a_card, string title, IdentityManagerView parent)
109     {
110         bool is_new_card = false;
111         if (a_card == null)
112         {
113             is_new_card = true;
114         }
115
116         card = a_card ?? new IdCard();
117         this.set_title(title);
118         this.set_modal(true);
119         this.set_transient_for(parent);
120
121         this.add_buttons(_("OK"), ResponseType.OK, CANCEL, ResponseType.CANCEL);
122         Box content_area = (Box) this.get_content_area();
123
124         displayname_label = new Label(@"$displayname_labeltext:");
125         displayname_label.set_alignment(0, (float) 0.5);
126         displayname_entry = new Entry();
127         displayname_entry.set_text(card.display_name);
128         displayname_entry.set_width_chars(40);
129
130         realm_label = new Label(@"$realm_labeltext:");
131         realm_label.set_alignment(0, (float) 0.5);
132         realm_entry = new Entry();
133         realm_entry.set_text(card.issuer);
134         realm_entry.set_width_chars(60);
135
136         username_label = new Label(@"$username_labeltext:");
137         username_label.set_alignment(0, (float) 0.5);
138         username_entry = new Entry();
139         username_entry.set_text(card.username);
140         username_entry.set_width_chars(40);
141
142         password_label = new Label(@"$password_labeltext:");
143         password_label.set_alignment(0, (float) 0.5);
144
145         remember_checkbutton = new CheckButton.with_label(_("Remember password"));
146         remember_checkbutton.active = card.store_password;
147
148         password_entry = new Entry();
149         password_entry.set_invisible_char('*');
150         password_entry.set_visibility(false);
151         password_entry.set_width_chars(40);
152         password_entry.set_text(card.password);
153
154         message_label = new Label("");
155         message_label.set_visible(false);
156
157         set_atk_relation(displayname_label, displayname_entry, Atk.RelationType.LABEL_FOR);
158         set_atk_relation(realm_label, realm_entry, Atk.RelationType.LABEL_FOR);
159         set_atk_relation(username_label, username_entry, Atk.RelationType.LABEL_FOR);
160         set_atk_relation(password_label, password_entry, Atk.RelationType.LABEL_FOR);
161
162         content_area.pack_start(message_label, false, false, 6);
163         add_as_vbox(content_area, displayname_label, displayname_entry);
164         add_as_vbox(content_area, username_label, username_entry);
165         add_as_vbox(content_area, realm_label, realm_entry);
166         add_as_vbox(content_area, password_label, password_entry);
167
168         var remember_hbox = new HBox(false, 40);
169         remember_hbox.pack_start(new HBox(false, 0), false, false, 0);
170         remember_hbox.pack_start(remember_checkbutton, false, false, 0);
171         content_area.pack_start(remember_hbox, false, false, 2);
172
173         this.response.connect(on_response);
174         content_area.set_border_width(6);
175
176         if (!is_new_card)
177         {
178             Widget trust_anchor_box = make_trust_anchor_box(card);
179             content_area.pack_start(trust_anchor_box, false, false, 15);
180
181             var services_vbox = make_services_vbox();
182             content_area.pack_start(services_vbox);
183             var services_vbox_bottom_spacer = new Alignment(0, 0, 0, 0);
184             services_vbox_bottom_spacer.set_size_request(0, 12);
185             content_area.pack_start(services_vbox_bottom_spacer, false, false, 0);
186         }
187
188         if (card.is_no_identity())
189         {
190             displayname_entry.set_sensitive(false);
191             realm_entry.set_sensitive(false);
192             username_entry.set_sensitive(false);
193             password_entry.set_sensitive(false);
194             remember_checkbutton.set_sensitive(false);
195         }
196
197         this.set_border_width(6);
198         this.set_resizable(false);
199         this.modify_bg(StateType.NORMAL, white);
200         this.show_all();
201     }
202
203     private Widget make_trust_anchor_box(IdCard id)
204     {
205
206         Label ta_label = new Label(_("Trust anchor: ")
207                                    + (id.trust_anchor.is_empty() ? _("None") : _("Enterprise provisioned")));
208         ta_label.set_alignment(0, 0.5f);
209
210         if (id.trust_anchor.is_empty()) {
211             return ta_label;
212         }
213
214
215         AttachOptions fill_and_expand = AttachOptions.EXPAND | AttachOptions.FILL;
216         AttachOptions fill = AttachOptions.FILL;
217
218         Table ta_table = new Table(6, 2, false);
219         int row = 0;
220
221         var ta_clear_button = new Button.with_label(_("Clear Trust Anchor"));
222         ta_clear_button.clicked.connect((w) => {
223                 clear_trust_anchor = true;
224                 ta_table.set_sensitive(false);
225             }
226             );
227
228         ta_table.attach(ta_label, 0, 1, row, row + 1, fill_and_expand, fill_and_expand, 0, 0);
229         ta_table.attach(ta_clear_button, 1, 2, row, row + 1, fill, fill, 0, 0);
230         row++;
231
232         Label added_label = new Label(_("Added : " + id.trust_anchor.datetime_added));
233         added_label.set_alignment(0, 0.5f);
234         ta_table.attach(added_label, 0, 1, row, row + 1, fill_and_expand, fill_and_expand, 20, 5);
235         row++;
236
237         if (id.trust_anchor.get_anchor_type() == TrustAnchor.TrustAnchorType.SERVER_CERT) {
238             Widget fingerprint = make_ta_fingerprint_widget(id.trust_anchor);
239             ta_table.attach(fingerprint, 0, 1, row, row + 2, fill_and_expand, fill_and_expand, 5, 5);
240
241             // To make the fingerprint box wider, try:
242             // ta_table.attach(fingerprint, 0, 2, row, row + 2, fill_and_expand, fill_and_expand, 20, 5);
243
244         }
245         else {
246             Label ca_cert_label = new Label(_("CA Certificate:"));
247             ca_cert_label.set_alignment(0, 0.5f);
248             var export_button = new Button.with_label(_("Export Certificate"));
249             //!!TODO!
250             export_button.clicked.connect((w) => {export_certificate(id);});
251
252             ta_table.attach(ca_cert_label, 0, 1, row, row + 1, fill_and_expand, fill_and_expand, 20, 0);
253             ta_table.attach(export_button, 1, 2, row, row + 1, fill, fill, 0, 0);
254             row++;
255
256             //!!TODO: When to show Subject, and when (if ever) show Subject-Altname here?
257             Label subject_label = new Label(_("Subject: ") + id.trust_anchor.subject);
258             subject_label.set_alignment(0, 0.5f);
259             ta_table.attach(subject_label, 0, 1, row, row + 1, fill_and_expand, fill_and_expand, 40, 5);
260             row++;
261
262             Label expiration_label = new Label(_("Expiration date: ") + id.trust_anchor.get_expiration_date());
263             expiration_label.set_alignment(0, 0.5f);
264             ta_table.attach(expiration_label, 0, 1, row, row + 1, fill_and_expand, fill_and_expand, 40, 5);
265             row++;
266
267             //!!TODO: What *is* this?
268             Label constraint_label = new Label(_("Constraint: "));
269             constraint_label.set_alignment(0, 0.5f);
270             ta_table.attach(constraint_label, 0, 1, row, row + 1, fill_and_expand, fill_and_expand, 20, 0);
271             row++;
272         }
273
274         return ta_table;
275
276     }
277
278     private static void add_as_vbox(Box content_area, Label label, Entry entry)
279     {
280         VBox vbox = new VBox(false, 2);
281
282         vbox.pack_start(label, false, false, 0);
283         vbox.pack_start(entry, false, false, 0);
284
285         // Hack to prevent the text entries from stretching horizontally
286         HBox hbox = new HBox(false, 0);
287         hbox.pack_start(vbox, false, false, 0);
288         content_area.pack_start(hbox, false, false, 6);
289     }
290
291     private static string update_preamble(string preamble)
292     {
293         if (preamble == "")
294             return _("Missing required field: ");
295         return _("Missing required fields: ");
296     }
297
298     private static string update_message(string old_message, string new_item)
299     {
300         string message;
301         if (old_message == "")
302             message = new_item;
303         else
304             message = old_message + ", " + new_item;
305         return message;
306     }
307
308     private static void check_field(string field, Label label, string fieldname, ref string preamble, ref string message)
309     {
310         if (field != "") {
311             label.set_markup(@"$fieldname:");
312             return;
313         }
314         label.set_markup(@"<span foreground=\"red\">$fieldname:</span>");
315         preamble = update_preamble(preamble);
316         message = update_message(message, fieldname);
317     }
318
319     private bool check_fields()
320     {
321         string preamble = "";
322         string message = "";
323         string password_test = store_password ? password : "not required";
324         if (!card.is_no_identity())
325         {
326             check_field(display_name, displayname_label, displayname_labeltext, ref preamble, ref message);
327             check_field(username, username_label, username_labeltext, ref preamble, ref message);
328             check_field(issuer, realm_label, realm_labeltext, ref preamble, ref message);
329             check_field(password_test, password_label, password_labeltext, ref preamble, ref message);
330         }
331         if (message != "") {
332             message_label.set_visible(true);
333             message_label.set_markup(@"<span foreground=\"red\">$preamble$message</span>");
334             return false;
335         }
336         return true;
337     }
338
339     private void on_response(Dialog source, int response_id)
340     {
341         switch (response_id) {
342         case ResponseType.OK:
343             complete = check_fields();
344             break;
345         case ResponseType.CANCEL:
346             complete = true;
347             break;
348         }
349     }
350
351     private VBox make_services_vbox()
352     {
353         logger.trace("make_services_vbox");
354
355         var services_vbox_alignment = new Alignment(0, 0, 1, 0);
356         var services_vscroll = new ScrolledWindow(null, null);
357         services_vscroll.set_policy(PolicyType.NEVER, PolicyType.AUTOMATIC);
358         services_vscroll.set_shadow_type(ShadowType.IN);
359         services_vscroll.set_size_request(0, 60);
360         services_vscroll.add_with_viewport(services_vbox_alignment);
361
362 #if VALA_0_12
363         var remove_button = new Button.from_stock(Stock.REMOVE);
364 #else
365         var remove_button = new Button.from_stock(STOCK_REMOVE);
366 #endif
367         remove_button.set_sensitive(false);
368
369
370         var services_table = new Table(card.services.size, 1, false);
371         services_table.set_row_spacings(1);
372         services_table.set_col_spacings(0);
373         services_table.modify_bg(StateType.NORMAL, white);
374
375         var table_button_hbox = new HBox(false, 6);
376         table_button_hbox.pack_start(services_vscroll, true, true, 4);
377
378         // Hack to prevent the button from growing vertically
379         VBox fixed_height = new VBox(false, 0);
380         fixed_height.pack_start(remove_button, false, false, 0);
381         table_button_hbox.pack_start(fixed_height, false, false, 0);
382
383         // A table doesn't have a background color, so put it in an EventBox, and
384         // set the EventBox's background color instead.
385         EventBox table_bg = new EventBox();
386         table_bg.modify_bg(StateType.NORMAL, white);
387         table_bg.add(services_table);
388         services_vbox_alignment.add(table_bg);
389
390         var services_vbox_title = new Label(_("Services:"));
391         services_vbox_title.set_alignment(0, 0.5f);
392
393         var services_vbox = new VBox(false, 6);
394         services_vbox.pack_start(services_vbox_title, false, false, 0);
395         services_vbox.pack_start(table_button_hbox, true, true, 0);
396
397         int i = 0;
398         foreach (string service in card.services)
399         {
400             var label = new Label(service);
401             label.set_alignment((float) 0, (float) 0);
402             label.xpad = 3;
403
404             EventBox event_box = new EventBox();
405             event_box.modify_bg(StateType.NORMAL, white);
406             event_box.add(label);
407             event_box.button_press_event.connect(() =>
408                 {
409                     var state = label.get_state();
410                     logger.trace("button_press_callback: Label state=" + state.to_string() + " setting bg to " + white.to_string());
411
412                     if (selected_item == label)
413                     {
414                         // Deselect
415                         selected_item.parent.modify_bg(state, white);
416                         selected_item = null;
417                         remove_button.set_sensitive(false);
418                     }
419                     else
420                     {
421                         if (selected_item != null)
422                         {
423                             // Deselect
424                             selected_item.parent.modify_bg(state, white);
425                             selected_item = null;
426                         }
427
428                         // Select
429                         selected_item = label;
430                         selected_item.parent.modify_bg(state, selected_color);
431                         remove_button.set_sensitive(true);
432                     }
433                     return false;
434                 });
435
436             services_table.attach_defaults(event_box, 0, 1, i, i+1);
437             i++;
438         }
439
440         remove_button.clicked.connect((remove_button) =>
441             {
442                 var result = WarningDialog.confirm(this,
443                                                    Markup.printf_escaped(
444                                                        "<span font-weight='heavy'>You are about to remove the service '%s'.</span>",
445                                                        selected_item.label)
446                                                    + "\n\nAre you sure you want to do this?",
447                                                    "delete_service");
448
449                 if (result)
450                 {
451                     if (card != null) {
452                         card.services.remove(selected_item.label);
453                         services_table.remove(selected_item.parent);
454                         selected_item = null;
455                         remove_button.set_sensitive(false);
456                     }
457                 }
458
459             });
460
461         return services_vbox;
462     }
463
464     private void export_certificate(IdCard id) 
465     {
466         var dialog = new FileChooserDialog("Save File",
467                                            this,
468                                            FileChooserAction.SAVE,
469                                            _("Cancel"),ResponseType.CANCEL,
470                                            _("Save"), ResponseType.ACCEPT,
471                                            null);
472         dialog.set_do_overwrite_confirmation(true);
473         if (export_directory != null) {
474             dialog.set_current_folder(export_directory);
475         }
476         // Remove slashes from the default filename.
477         string default_filename = 
478             (id.display_name + ".pem").replace(Path.DIR_SEPARATOR_S, "_");
479         dialog.set_current_name(default_filename);
480         if (dialog.run() == ResponseType.ACCEPT)
481         {
482             // Export the certificate in PEM format.
483
484             const string CERT_HEADER = "-----BEGIN CERTIFICATE-----\n";
485             const string CERT_FOOTER = "\n-----END CERTIFICATE-----\n";
486
487             // Strip any embedded newlines in the certificate...
488             string cert = id.trust_anchor.ca_cert.replace("\n", "");
489
490             // Re-embed newlines every 64 chars.
491             string newcert = CERT_HEADER;
492             while (cert.length > 63) {
493                 newcert += cert[0:64];
494                 newcert += "\n";
495                 cert = cert[64:cert.length];
496             }
497             if (cert.length > 0) {
498                 newcert += cert;
499             }
500             newcert += CERT_FOOTER;
501
502             string filename = dialog.get_filename();
503             var file  = File.new_for_path(filename);
504             var stream = file.replace(null, false, FileCreateFlags.PRIVATE);
505             stream.write(newcert.data);
506
507             // Save the parent directory to use as default for next save
508             export_directory = file.get_parent().get_path();
509         }
510         dialog.destroy();
511     }
512 }