-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
EditKeyStoreControlViewModel.cs
381 lines (347 loc) · 13.9 KB
/
EditKeyStoreControlViewModel.cs
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
using Leosac.KeyManager.Library;
using Leosac.KeyManager.Library.KeyStore;
using Leosac.KeyManager.Library.Plugin;
using Leosac.KeyManager.Library.UI;
using Leosac.KeyManager.Library.UI.Domain;
using Leosac.WpfApp;
using MaterialDesignThemes.Wpf;
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Collections.Generic;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System.Windows.Input;
using Org.BouncyCastle.Crypto;
using log4net;
namespace Leosac.KeyManager.Domain
{
public class EditKeyStoreControlViewModel : ObservableValidator
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod()?.DeclaringType);
public EditKeyStoreControlViewModel(ISnackbarMessageQueue snackbarMessageQueue)
{
_showProgress = false;
_snackbarMessageQueue = snackbarMessageQueue;
Tabs = new ObservableCollection<TabItem>();
_keModels = new List<KeyEntriesControlViewModel>();
RefreshKeyEntriesCommand = new AsyncRelayCommand(() => RefreshKeyEntries(500));
SaveFavoriteCommand = new RelayCommand(
() =>
{
Flipper.FlipCommand.Execute(null, null);
var favorites = Favorites.GetSingletonInstance();
favorites?.SaveToFile();
});
}
protected ISnackbarMessageQueue _snackbarMessageQueue;
protected IList<KeyEntriesControlViewModel> _keModels;
protected void OnKeyStoreUpdated()
{
if (Favorite != null)
{
var favorites = Favorites.GetSingletonInstance();
if (favorites != null)
{
SaveToFavorite(favorites, Favorite);
}
}
}
private KeyStore? _keyStore;
public KeyStore? KeyStore
{
get => _keyStore;
set => SetProperty(ref _keyStore, value);
}
private Favorite? _favorite;
public Favorite? Favorite
{
get => _favorite;
set => SetProperty(ref _favorite, value);
}
private bool _showProgress;
public bool ShowProgress
{
get => _showProgress;
set => SetProperty(ref _showProgress, value);
}
private int _progressValue;
public int ProgressValue
{
get => _progressValue;
set => SetProperty(ref _progressValue, value);
}
private int _progressMaximum;
public int ProgressMaximum
{
get => _progressMaximum;
set => SetProperty(ref _progressMaximum, value);
}
private bool _isLoadingKeyEntries;
public bool IsLoadingKeyEntries
{
get => _isLoadingKeyEntries;
set => SetProperty(ref _isLoadingKeyEntries, value);
}
public ObservableCollection<TabItem> Tabs { get; set; }
public RelayCommand? HomeCommand { get; set; }
public AsyncRelayCommand RefreshKeyEntriesCommand { get; }
public RelayCommand SaveFavoriteCommand { get; }
public void CloseKeyStore()
{
CloseKeyStore(true);
}
public void CloseKeyStore(bool navigate)
{
KeyStore?.Close();
KeyStore = null;
_keModels.Clear();
Tabs.Clear();
Favorite = null;
if (navigate)
{
HomeCommand?.Execute(null);
}
}
public async Task OpenKeyStore()
{
if (KeyStore != null)
{
Mouse.OverrideCursor = Cursors.Wait;
try
{
await KeyStore.Open();
var classes = KeyStore.SupportedClasses;
foreach (var kclass in classes)
{
var model = new KeyEntriesControlViewModel(_snackbarMessageQueue, kclass) { KeyStore = KeyStore };
model.DefaultKeyEntryUpdated += (sender, e) =>
{
OnKeyStoreUpdated();
};
_keModels.Add(model);
Tabs.Add(new TabItem
{
Header = string.Format("{0} Key Entries", kclass.ToString()),
Content = new KeyEntriesControl
{
DataContext = model
}
});
}
}
finally
{
Mouse.OverrideCursor = null;
}
await RefreshKeyEntries();
}
}
public Task RefreshKeyEntries() => RefreshKeyEntries(0);
public async Task RefreshKeyEntries(int delay)
{
IsLoadingKeyEntries = true;
if (delay > 0)
{
await Task.Delay(delay);
}
try
{
foreach (var model in _keModels)
{
await model.RefreshKeyEntries();
}
}
catch(Exception ex)
{
SnackbarHelper.EnqueueError(_snackbarMessageQueue, ex, "Key Store Error");
}
IsLoadingKeyEntries = false;
}
public async Task EditFavorite()
{
if (Favorite != null)
{
await EditFavorite(Favorites.GetSingletonInstance(), Favorite);
}
}
public static async Task EditFavorite(Favorites? favorites, Favorite fav)
{
var factory = KeyStoreUIFactory.GetFactoryFromPropertyType(fav.Properties?.GetType());
if (factory != null)
{
if (favorites != null)
{
var model = new KeyStoreSelectorDialogViewModel
{
Message = "Edit the Key Store Favorite"
};
model.SelectedFactoryItem = model.KeyStoreFactories.Where(item => item.Factory == factory).FirstOrDefault();
if (model.SelectedFactoryItem != null)
{
model.SelectedFactoryItem.DataContext!.Properties = fav.Properties;
var dialog = new KeyStoreSelectorDialog
{
DataContext = model
};
object? ret = await DialogHost.Show(dialog, "RootDialog");
if (ret != null)
{
fav.Properties = model.SelectedFactoryItem.DataContext.Properties;
SaveToFavorite(favorites, fav);
}
}
}
}
}
private static void SaveToFavorite(Favorites favorites, Favorite fav)
{
int favindex = favorites.KeyStores.IndexOf(fav);
if (favindex > -1)
{
favorites.KeyStores.RemoveAt(favindex);
}
favorites.KeyStores.Add(fav);
favorites.SaveToFile();
}
public static async Task<bool> AskForKeyStoreSecretIfRequired(KeyStore ks)
{
if (ks.Properties != null && (ks.Properties.StoreSecret || !string.IsNullOrEmpty(ks.Properties.Secret)))
{
return true;
}
var dialog = new OpenFavoriteControl
{
DataContext = ks,
Properties = ks.Properties!,
Title = string.Format("{0} - {1}", Properties.Resources.OpenFavorite, ks.Name),
Command = new RelayCommand(() =>
{
DialogHost.CloseDialogCommand.Execute(ks, null);
})
};
var ret = await DialogHost.Show(dialog, "RootDialog");
return (ret != null);
}
public async Task<bool> RunOnKeyStore(UserControl dialog, Func<KeyStore, Func<string, KeyStore?>, Func<KeyStore, Task<bool>>?, KeyEntryClass, IEnumerable<KeyEntryId>?, Action<KeyStore, KeyEntryClass, int>?, Task> action)
{
var model = new PublishKeyStoreDialogViewModel();
dialog.DataContext = model;
object? ret = await DialogHost.Show(dialog, "RootDialog");
if (ret != null && model.Favorite != null)
{
var prop = model.Favorite.Properties;
if (prop != null)
{
var factory = KeyStoreFactory.GetFactoryFromPropertyType(prop.GetType());
if (factory != null)
{
try
{
ProgressValue = 0;
ShowProgress = true;
var deststore = factory.CreateKeyStore();
deststore.Properties = prop;
deststore.KeyEntryRetrieved += (sender, e) => ProgressValue++;
deststore.KeyEntryUpdated += (sender, e) => ProgressValue++;
deststore.Options = model.Options;
KeyStore!.Options = model.Options; // Options object contains information for source and destination key stores, this should probably be splitted...
var initCallback = new Action<KeyStore, KeyEntryClass, int>((_, _, nbentries) =>
{
ProgressMaximum = nbentries * 2;
});
var getFavoriteKeyStore = new Func<string, KeyStore?>((favoriteName) =>
{
if (!string.IsNullOrEmpty(favoriteName))
{
var favorites = Favorites.GetSingletonInstance();
if (favorites != null)
{
var fav = favorites.KeyStores.Where(ks => ks.Name.ToLowerInvariant() == favoriteName.ToLowerInvariant()).SingleOrDefault();
if (fav != null)
{
return fav.CreateKeyStore();
}
else
{
log.Error(string.Format("Cannot found the favorite Key Store `{0}`.", favoriteName));
throw new KeyStoreException("Cannot found the favorite Key Store.");
}
}
}
return null;
});
foreach (var keModel in _keModels)
{
IEnumerable<KeyEntryId>? entries = null;
if (keModel.ShowSelection)
{
entries = keModel.Identifiers.Where(k => k.Selected && k.KeyEntryId != null).Select(k => k.KeyEntryId!);
}
await action(deststore,
getFavoriteKeyStore,
AskForKeyStoreSecretIfRequired,
keModel.KeyEntryClass,
entries,
initCallback
);
}
}
finally
{
ShowProgress = false;
}
return true;
}
}
}
return false;
}
public async Task Publish()
{
if (KeyStore != null)
{
try
{
if (await RunOnKeyStore(new PublishKeyStoreDialog(), KeyStore.Publish))
{
SnackbarHelper.EnqueueMessage(_snackbarMessageQueue, "Key Entries have been successfully published.");
}
}
catch (KeyStoreException ex)
{
SnackbarHelper.EnqueueError(_snackbarMessageQueue, ex, "Key Store Error");
}
catch (Exception ex)
{
log.Error("Publishing the Key Entries failed unexpected.", ex);
SnackbarHelper.EnqueueError(_snackbarMessageQueue, ex);
}
}
}
public async Task Diff()
{
if (KeyStore != null)
{
try
{
if (await RunOnKeyStore(new DiffKeyStoreDialog(), KeyStore.Diff))
{
SnackbarHelper.EnqueueMessage(_snackbarMessageQueue, "No differences found.");
}
}
catch (KeyStoreException ex)
{
SnackbarHelper.EnqueueError(_snackbarMessageQueue, ex, "Key Store Error");
}
catch (Exception ex)
{
log.Error("Comparing the Key Entries failed unexpected.", ex);
SnackbarHelper.EnqueueError(_snackbarMessageQueue, ex);
}
}
}
}
}