source: trunk/src/org/expeditee/auth/Actions.java@ 1283

Last change on this file since 1283 was 1283, checked in by bln4, 5 years ago

When loading in messages from the mail databases now uses the timestamp last-accessed companion file to only load in new ones.

File size: 33.5 KB
Line 
1package org.expeditee.auth;
2
3import java.io.File;
4import java.io.FileNotFoundException;
5import java.io.FileWriter;
6import java.io.IOException;
7import java.nio.file.Files;
8import java.nio.file.Path;
9import java.nio.file.Paths;
10import java.nio.file.StandardCopyOption;
11import java.security.InvalidKeyException;
12import java.security.KeyFactory;
13import java.security.KeyPair;
14import java.security.KeyPairGenerator;
15import java.security.KeyStoreException;
16import java.security.NoSuchAlgorithmException;
17import java.security.PrivateKey;
18import java.security.PublicKey;
19import java.security.SecureRandom;
20import java.security.cert.CertificateException;
21import java.security.spec.InvalidKeySpecException;
22import java.security.spec.PKCS8EncodedKeySpec;
23import java.sql.SQLException;
24import java.text.ParseException;
25import java.util.Base64;
26import java.util.Collection;
27import java.util.HashMap;
28import java.util.List;
29import java.util.Map;
30import java.util.Optional;
31import java.util.Random;
32import java.util.function.Consumer;
33import java.util.stream.Collectors;
34
35import javax.crypto.BadPaddingException;
36import javax.crypto.IllegalBlockSizeException;
37import javax.crypto.NoSuchPaddingException;
38import javax.crypto.SecretKey;
39import javax.crypto.spec.SecretKeySpec;
40
41import org.apollo.io.AudioPathManager;
42import org.expeditee.agents.ExistingFramesetException;
43import org.expeditee.agents.InvalidFramesetNameException;
44import org.expeditee.auth.Mail.MailEntry;
45import org.expeditee.auth.gui.MailBay;
46import org.expeditee.auth.tags.AuthenticationTag;
47import org.expeditee.auth.tags.Constants;
48import org.expeditee.core.Colour;
49import org.expeditee.gui.Browser;
50import org.expeditee.gui.DisplayController;
51import org.expeditee.gui.Frame;
52import org.expeditee.gui.FrameIO;
53import org.expeditee.gui.MessageBay;
54import org.expeditee.io.ExpReader;
55import org.expeditee.items.Item;
56import org.expeditee.items.PermissionPair;
57import org.expeditee.items.Text;
58import org.expeditee.items.UserAppliedPermission;
59import org.expeditee.setting.GenericSetting;
60import org.expeditee.setting.Setting;
61import org.expeditee.setting.TextSetting;
62import org.expeditee.settings.Settings;
63import org.expeditee.settings.UserSettings;
64import org.expeditee.settings.folders.FolderSettings;
65import org.expeditee.settings.identity.secrets.KeyList;
66import org.ngikm.cryptography.CryptographyConstants;
67
68public class Actions implements CryptographyConstants {
69
70 //Debug Functions
71 public static void SendTestMessage(String colleagueName) throws InvalidKeySpecException, NoSuchAlgorithmException, FileNotFoundException, KeyStoreException, CertificateException, ClassNotFoundException, IOException, SQLException {
72 String time = org.expeditee.stats.Formatter.getDateTime();
73 String sender = UserSettings.UserName.get();
74 String topic = "Test Message";
75 String message = "This is a test message.";
76 Map<String, String> options = new HashMap<String, String>();
77 options.put("Neat", "Beep");
78 MailEntry mail = new MailEntry(time, sender, colleagueName, topic, message, options);
79 Mail.sendMail(mail, colleagueName);
80 }
81 private static String userbackup = "authadmin";
82 public static void ToggleAuth() {
83 String backup = UserSettings.UserName.get();
84 UserSettings.UserName.set(userbackup);
85 userbackup = backup;
86 }
87
88 /**
89 * Display Expeditee Mail
90 * @throws IOException
91 * @throws SQLException
92 * @throws ClassNotFoundException
93 * @throws CertificateException
94 * @throws NoSuchAlgorithmException
95 * @throws FileNotFoundException
96 * @throws KeyStoreException
97 * @throws ParseException
98 */
99 public static void ToggleBay() throws KeyStoreException, FileNotFoundException, NoSuchAlgorithmException, CertificateException, ClassNotFoundException, SQLException, IOException, ParseException {
100 if (!DisplayController.isMailMode()) {
101 Mail.clear();
102 AuthenticatorBrowser.getInstance().loadMailDatabase();
103 }
104 DisplayController.ToggleMailMode();
105 }
106
107 /**
108 * Action used to navigate the authorised user back to their desktop.
109 */
110 public static void AuthGoToDesktop() {
111 DisplayController.setCurrentFrame(FrameIO.LoadFrame(UserSettings.HomeFrame.get()), true);
112 }
113
114 /**
115 * Action used to created a new user account.
116 * Attempts to use content from text items on frame, will default to java properties if they cannot be found.
117 * Will fail if it cannot find content from text items on frame and all required java properties are not present.
118 * @throws SQLException
119 * @throws IOException
120 * @throws ExistingFramesetException
121 * @throws InvalidFramesetNameException
122 * @throws ClassNotFoundException
123 * @throws FileNotFoundException
124 * @throws CertificateException
125 * @throws NoSuchAlgorithmException
126 * @throws KeyStoreException
127 * @throws BadPaddingException
128 * @throws IllegalBlockSizeException
129 * @throws NoSuchPaddingException
130 * @throws InvalidKeySpecException
131 * @throws InvalidKeyException
132 * @throws ParseException
133 * @throws Exception
134 */
135 public static void AuthCreateAccount() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, ClassNotFoundException, InvalidFramesetNameException, ExistingFramesetException, IOException, SQLException, InvalidKeyException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, ParseException {
136 Collection<Text> textItems = DisplayController.getCurrentFrame().getTextItems();
137 Optional<Map<AuthenticationTag, String>> userdata =
138 AuthenticationTag.fetchUserData(textItems, false,
139 AuthenticationTag.Username,
140 AuthenticationTag.Password,
141 AuthenticationTag.PasswordAgain,
142 AuthenticationTag.Email,
143 AuthenticationTag.EmailAgain);
144
145 if (userdata.isPresent()) {
146 Map<AuthenticationTag, String> userData = userdata.get();
147
148 // A profile already existing with 'username' means an account cannot be created with that username.
149 if (FrameIO.LoadProfile(userData.get(AuthenticationTag.Username)) != null) {
150 MessageBay.errorMessage(Constants.ERROR_PROFILE_NAME_PREEXISTS);
151 return;
152 }
153
154 // The chosen username must be a valid frameset name.
155 if (!FrameIO.isValidFramesetName(userData.get(AuthenticationTag.Username))) {
156 MessageBay.errorMessage(Constants.ERROR_INVALID_USERNAME);
157 return;
158 }
159
160 // The passwords provided must match
161 if (userData.get(AuthenticationTag.Password).compareTo(userData.get(AuthenticationTag.PasswordAgain)) != 0) {
162 MessageBay.errorMessage(Constants.ERROR_MISMATCH_PASSWORDS);
163 return;
164 }
165
166 // The emails provided must match
167 if (userData.get(AuthenticationTag.Email).compareTo(userData.get(AuthenticationTag.EmailAgain)) != 0) {
168 MessageBay.errorMessage(Constants.ERROR_MISMATCH_EMAILS);
169 return;
170 }
171
172 createAccount(userData);
173 login(userData);
174 AuthenticatorBrowser.Authenticated = true;
175 } else {
176 MessageBay.errorMessage(Constants.ERROR_INSUFFICIENT_INFORMATION_PROVIDED);
177 }
178 }
179
180 /**
181 * Action used to start authentication as a specified user.
182 * Attempts to use content from text items on frame, will default to java properties if they cannot be found.
183 * Will fail if it cannot find content from text items on frame and all required java properties are not present.
184 * @throws Exception
185 */
186 public static void AuthLogin() throws Exception {
187 final Collection<Text> textItems = DisplayController.getCurrentFrame().getTextItems();
188 final Optional<Map<AuthenticationTag, String>> userdata = AuthenticationTag.fetchUserData(textItems, false, AuthenticationTag.Username, AuthenticationTag.Password);
189 if (userdata.isPresent()) {
190 login(userdata.get());
191 AuthenticatorBrowser.Authenticated = true;
192 } else {
193 MessageBay.errorMessage(Constants.ERROR_INSUFFICIENT_INFORMATION_PROVIDED);
194 }
195 }
196
197 /**
198 * Action used to change the currently authenticated users password.
199 * Attempts to use content from text items on frame, will default to java properties if they cannot be found.
200 * Will fail if it cannot find content from text items on frame and all required java properties are not present.
201 * Will fail if no user is currently logged in.
202 * @throws IOException
203 * @throws CertificateException
204 * @throws FileNotFoundException
205 * @throws KeyStoreException
206 * @throws NoSuchAlgorithmException
207 * @throws SQLException
208 * @throws ClassNotFoundException
209 */
210 public static void AuthChangePassword() throws NoSuchAlgorithmException, KeyStoreException, FileNotFoundException, CertificateException, IOException, ClassNotFoundException, SQLException {
211 final Collection<Text> textItems = DisplayController.getCurrentFrame().getTextItems();
212
213 if (!AuthenticatorBrowser.Authenticated) {
214 MessageBay.errorMessage(Constants.ERROR_MUST_BE_LOGGED_IN);
215 } else {
216 final Optional<Map<AuthenticationTag, String>> userdata = AuthenticationTag.fetchUserData(textItems, false, AuthenticationTag.Password, AuthenticationTag.NewPassword, AuthenticationTag.NewPasswordAgain);
217 if (userdata.isPresent()) {
218 final Map<AuthenticationTag, String> userData = userdata.get();
219 if (userData.get(AuthenticationTag.NewPassword).compareTo(userData.get(AuthenticationTag.NewPasswordAgain)) != 0) {
220 MessageBay.errorMessage(Constants.ERROR_MISMATCH_PASSWORDS);
221 } else {
222 userData.put(AuthenticationTag.Username, UserSettings.UserName.get());
223 changePassword(userData);
224 }
225 } else {
226 MessageBay.errorMessage(Constants.ERROR_INSUFFICIENT_INFORMATION_PROVIDED);
227 }
228 }
229 }
230
231 public static void AuthGotoAccountManagement() {
232 if (AuthenticatorBrowser.Authenticated) {
233 DisplayController.setCurrentFrame(FrameIO.LoadFrame(Constants.FRAME_MULTIUSER1), false);
234 } else {
235 DisplayController.setCurrentFrame(FrameIO.LoadFrame(Constants.FRAME_AUTHENTICATION1), false);
236 }
237 }
238
239 public static void AuthShareFrameset() throws IOException {
240 Collection<Text> textItems = DisplayController.getCurrentFrame().getTextItems();
241
242 Optional<Map<AuthenticationTag, String>> userdata = AuthenticationTag.fetchUserData(textItems, false, AuthenticationTag.Frameset);
243 if (userdata.isPresent()) {
244 Map<AuthenticationTag, String> userData = userdata.get();
245 FrameIO.SuspendCache();
246 Frame toShare = FrameIO.LoadFrame(userData.get(AuthenticationTag.Frameset) + 1);
247 FrameIO.ResumeCache();
248
249 if (toShare == null) {
250 MessageBay.errorMessage(Constants.ERROR_INSUFFICIENT_INFORMATION);
251 return;
252 }
253
254 shareFrameset(toShare);
255 }
256 }
257
258 /**
259 * Navigation action for progressing the process of recruiting colleagues to assist in password recovery.
260 * Hides certain content that AuthSubmitPWCollegues goes onto show if it does not fail.
261 */
262 public static void AuthGotoColleagueSubmissionFrame() {
263 Frame destination = FrameIO.LoadFrame(Constants.FRAME_COLLEAGUE_SUBMISSION_FRAME);
264 DisplayController.setCurrentFrame(destination, true);
265 Collection<Item> toHide = getByData(destination, Constants.DATA_SHOW_ON_PROGRESS);
266 for (Item i: toHide) {
267 i.setVisible(false);
268 }
269 }
270
271 /**
272 * Action used to start the process of formalising the password recovery process.
273 * @throws SQLException
274 * @throws IOException
275 * @throws ClassNotFoundException
276 * @throws CertificateException
277 * @throws NoSuchAlgorithmException
278 * @throws FileNotFoundException
279 * @throws KeyStoreException
280 * @throws InvalidKeySpecException
281 */
282 public static void AuthSubmitPWColleagues() throws InvalidKeySpecException, NoSuchAlgorithmException, KeyStoreException, FileNotFoundException, CertificateException, ClassNotFoundException, IOException, SQLException {
283 Frame currentFrame = DisplayController.getCurrentFrame();
284 Collection<Text> textItems = currentFrame.getTextItems();
285
286 if (!AuthenticatorBrowser.Authenticated) {
287 MessageBay.errorMessage(Constants.ERROR_MUST_BE_LOGGED_IN);
288 return;
289 }
290
291 Optional<Map<AuthenticationTag, String>> userdata = AuthenticationTag.fetchUserData(textItems, false, AuthenticationTag.ColleagueOne, AuthenticationTag.ColleagueTwo);
292 if (userdata.isPresent()) {
293 Map<AuthenticationTag, String> userData = userdata.get();
294 String colleagueOne = userData.get(AuthenticationTag.ColleagueOne);
295 Path colleagueOnePath = Paths.get(FrameIO.CONTACTS_PATH).resolve(colleagueOne + "-credentials");
296 String colleagueTwo = userData.get(AuthenticationTag.ColleagueTwo);
297 Path colleagueTwoPath = Paths.get(FrameIO.CONTACTS_PATH).resolve(colleagueTwo + "-credentials");
298 if (!colleagueOnePath.toFile().exists()) {
299 MessageBay.errorMessage("Your nominated colleague: " + colleagueOne + " must exist in your contacts.");
300 } else if (!colleagueTwoPath.toFile().exists()) {
301 MessageBay.errorMessage("Your nominated colleague: " + colleagueTwo + " must exist in your contacts.");
302 } else {
303 userData.put(AuthenticationTag.Username, UserSettings.UserName.get());
304 boolean success = submitPWColleagues(userData);
305 if (success) {
306 Collection<Item> toShow = getByData(currentFrame, Constants.DATA_SHOW_ON_PROGRESS);
307 for (Item i: toShow) {
308 i.setVisible(true);
309 }
310 currentFrame.change();
311 MessageBay.displayMessage("-------Messages sent-------");
312 }
313 FrameIO.SaveFrame(currentFrame);
314 DisplayController.requestRefresh(false);
315 }
316 }
317 }
318
319// public static void AuthSetupPasswordRecovery() throws KeyStoreException, FileNotFoundException, NoSuchAlgorithmException, CertificateException, ClassNotFoundException, IOException, SQLException, UnrecoverableEntryException {
320// if (!UserSettings.Authenticated.get()) {
321// MessageBay.errorMessage("You must be logged in to perform this action.");
322// } else if (!Authenticator.getInstance().hasRegisteredEmail(UserSettings.UserName.get())) {
323// Frame registerEmailFrame = FrameIO.LoadFrame("authentication4");
324// DisplayController.setCurrentFrame(registerEmailFrame, true);
325// } else if (!Authenticator.getInstance().hasRequestedColleagues(UserSettings.UserName.get()) && Authenticator.getInstance().getColleagues(UserSettings.UserName.get()) == null) {
326// Frame submitColleaguesFrame = FrameIO.LoadFrame("authentication5");
327// DisplayController.setCurrentFrame(submitColleaguesFrame, true);
328// } else if (Authenticator.getInstance().hasRequestedColleagues(UserSettings.UserName.get()) && Authenticator.getInstance().getColleagues(UserSettings.UserName.get()) == null) {
329// MessageBay.displayMessage("You have already nominated two colleagues to assist you in the process of password recovery and are awaiting their response."
330// + " You will be alerted on Expeditee startup when they have both responded.");
331// } else if (Authenticator.getInstance().getColleagues(UserSettings.UserName.get()) != null) {
332// MessageBay.displayMessage("You have completed the Password Recovery Setup process, there is nothing more to do here.");
333// }
334// }
335
336 public static void AuthConfirmPasswordColleagueRelationship(String colleagueName) {
337
338 }
339
340 public static void AuthDenyPasswordColleagueRelationship(String colleagueName) throws InvalidKeySpecException, NoSuchAlgorithmException,
341 KeyStoreException, FileNotFoundException, CertificateException, ClassNotFoundException, IOException, SQLException {
342 denyPasswordColleagueRelationship(colleagueName);
343 }
344
345 public static void AuthClearPWColleaguesNominated() {
346
347 }
348
349 /**
350 * Create a user account using the specified information in userdata. Creates and stores user keys.
351 * @param userdata Should contain username, password and email.
352 */
353 private static void createAccount(Map<AuthenticationTag, String> userdata) throws InvalidFramesetNameException, ExistingFramesetException,
354 KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, ClassNotFoundException, IOException, SQLException {
355 // Track progress
356 String message = "Creating new user account...";
357
358 // Extract user details
359 String username = userdata.get(AuthenticationTag.Username);
360 String password = userdata.get(AuthenticationTag.Password);
361 String email = userdata.get(AuthenticationTag.Email);
362
363 System.out.println(message + "Generating Keys.");
364
365 // Generate keys
366 // Personal key
367 Random rand = new SecureRandom();
368 byte[] keyBytes = new byte[16];
369 rand.nextBytes(keyBytes);
370 SecretKey key = new SecretKeySpec(keyBytes, SymmetricAlgorithm);
371 AuthenticatorBrowser.getInstance().putKey(username, password, key);
372 String personalKey = Base64.getEncoder().encodeToString(key.getEncoded());
373 // Public and private keys
374 KeyPairGenerator keyGen = KeyPairGenerator.getInstance(AsymmetricAlgorithm);
375 keyGen.initialize(1024);
376 KeyPair keyPair = keyGen.generateKeyPair();
377 String publicKey = Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded());
378 String privateKey = Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded());
379
380 System.out.println(message + "Creating Profile Frameset.");
381
382 // Update in memory settings
383 System.setProperty("user.name", username);
384 UserSettings.UserName.set(username);
385 UserSettings.ProfileName.set(username);
386 UserSettings.setupDefaultFolders();
387
388 // Establish the initial settings for the created user.
389 Map<String, Setting> initialSettings = new HashMap<String, Setting>();
390 initialSettings.put(Constants.SETTINGS_AUTH_SECRETS_PERSONAL_KEY, constructTextSetting(Constants.TOOLTIP_SETTING_PERSONAL_KEY, "PersonalKey", personalKey));
391 initialSettings.put(Constants.SETTINGS_AUTH_SECRETS_PRIVATE_KEY, constructTextSetting(Constants.TOOLTIP_SETTING_PRIVATE_KEY, "PrivateKey", privateKey));
392 initialSettings.put(Constants.SETTINGS_AUTH_PUBLIC_KEY, constructTextSetting(Constants.TOOLTIP_SETTING_PUBLIC_KEY, "PublicKey", publicKey));
393 initialSettings.put(Constants.SETTINGS_AUTH_EMAIL, constructGenericSetting(String.class, Constants.TOOLTIP_SETTING_EMAIL, "Email", email, username));
394 initialSettings.put(Constants.SETTINGS_USER_SETTINGS_USER_NAME, constructGenericSetting(String.class, Constants.LABEL_USERNAME, Constants.LABEL_USERNAME, username, username));
395 initialSettings.put(Constants.SETTINGS_USER_SETTINGS_PROFILE_NAME, constructGenericSetting(String.class, Constants.LABEL_PROFILENAME, Constants.LABEL_PROFILENAME, username, username));
396 initialSettings.put("org.expeditee.gui.folders.FolderSettings.FrameDirs", FolderSettings.FrameDirs);
397 initialSettings.put("org.expeditee.gui.folders.FolderSettings.ImageDirs", FolderSettings.ImageDirs);
398 initialSettings.put("org.expeditee.gui.folders.FolderSettings.AudioDirs", FolderSettings.AudioDirs);
399
400 // Record the credentials frame number
401 Map<String, Consumer<Frame>> notifiers = new HashMap<String, Consumer<Frame>>();
402 notifiers.put(Constants.SETTINGS_AUTH, frame -> {
403 AuthenticatorBrowser.CREDENTIALS_FRAME = frame.getNumber();
404 Collection<Text> textItems = frame.getTextItems();
405 for (Text t: textItems) {
406 if (t.getText().equals("Secrets")) {
407 t.setPermission(new PermissionPair(UserAppliedPermission.followLinks, UserAppliedPermission.denied));
408 break;
409 }
410 }
411 });
412
413 // Create users profile
414 Frame profile = FrameIO.CreateNewProfile(username, initialSettings, notifiers);
415 int lastNumber = FrameIO.getLastNumber(profile.getFramesetName());
416 for (int i = 1; i <= lastNumber; i++) {
417 Frame f = FrameIO.LoadFrame(profile.getFramesetName() + i);
418 Text titleItem = f.getTitleItem();
419 if (i == 1 && titleItem != null) {
420 titleItem.delete();
421 f.setBackgroundColor(new Colour(1, 1, 0.39f));
422 }
423 f.setOwner(username);
424 f.getAllItems().stream().forEach(item -> item.setOwner(username));
425 f.setChanged(true);
426 if (f.getNumber() != AuthenticatorBrowser.CREDENTIALS_FRAME) {
427 f.setEncryptionLabel("Profile");
428 }
429 Collection<Item> secretsLink = getByContent(f, "Secrets");
430 Collection<Item> publicKeyItem = getByContent(f, "PublicKey");
431 if (!secretsLink.isEmpty() && !publicKeyItem.isEmpty()) {
432 //Then we are on credentials frame
433 f.addToData("MultiuserCredentials");
434 }
435 Text backupPersonalKey = KeyList.PersonalKey.get();
436 Text tempPersonalKey = KeyList.PersonalKey.generateText();
437 tempPersonalKey.setData(personalKey);
438 KeyList.PersonalKey.setSetting(tempPersonalKey);
439 FrameIO.SaveFrame(f);
440 KeyList.PersonalKey.setSetting(backupPersonalKey);
441 }
442
443 if (AuthenticatorBrowser.CREDENTIALS_FRAME == -1) {
444 System.err.println("authActions::Unable to establish credentials frame for new profile frame. Account creation failed.");
445 return;
446 }
447
448 System.out.println(message + "Establishing user credentials.");
449
450 // Create credentials
451 File credentialsDir = new File(profile.getFramesetPath() + username + "-credentials");
452 credentialsDir.mkdir();
453 // credentials.inf file.
454 String credentialsPath = credentialsDir.getAbsolutePath() + File.separator + "credentials.inf";
455 File credentialsFile = new File(credentialsPath);
456 credentialsFile.createNewFile();
457 FileWriter out = new FileWriter(credentialsFile);
458 out.write(AuthenticatorBrowser.CREDENTIALS_FRAME + ".exp");
459 out.flush();
460 out.close();
461 // migrate credentials frame
462 Frame credentialsFrame = FrameIO.LoadFrame(username + AuthenticatorBrowser.CREDENTIALS_FRAME);
463 Path destinationDirectory = Paths.get(credentialsDir.getAbsolutePath());
464 Path destinationFile = destinationDirectory.resolve(AuthenticatorBrowser.CREDENTIALS_FRAME + ExpReader.EXTENTION);
465 FrameIO.migrateFrame(credentialsFrame, destinationFile);
466
467 System.out.println(message + "Creating Individual Space.");
468
469 // Copy private resources to personal area
470 Path personalResources = FrameIO.setupPersonalResources(username);
471
472 File contactsDir = new File(personalResources.resolve("contacts").toAbsolutePath().toString());
473 contactsDir.mkdir();
474
475 System.out.println(message + "Creating Space For Dead Drops");
476
477 File deadDropsDir = new File(personalResources.resolve("deaddrops").toAbsolutePath().toString());
478 deadDropsDir.mkdir();
479
480 System.err.println("**** Hardwired call in Apollo's AuthioPathManager");
481 AudioPathManager.activateAndScanAudioDir(); // ****
482
483 System.out.println(message + "Done.");
484 }
485
486 /*
487 * Function used to authenticate as a specified user (via function arguments).
488 */
489 private static void login(Map<AuthenticationTag, String> userdata) throws NoSuchAlgorithmException, KeyStoreException, FileNotFoundException, CertificateException, ClassNotFoundException, IOException, SQLException, InvalidKeySpecException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, ParseException {
490 String username = userdata.get(AuthenticationTag.Username);
491 String password = userdata.get(AuthenticationTag.Password);
492
493 if (username.equals(Browser.USER_NOBODY)) {
494 return;
495 }
496
497 SecretKey personalKey = null;
498
499 try {
500 personalKey = AuthenticatorBrowser.getInstance().getSecretKey(username, password);
501 } catch (Exception e) {
502 // leave personalKey null
503 }
504
505 if (personalKey == null) {
506 // Incorrect username and password
507 MessageBay.errorMessage("The username + password combination was incorrect.");
508 return;
509 }
510
511 // **** DB
512 // Have not been able to test the following as auth + login not currently working
513 // 'out of the box'
514
515 // Currently causing a concurrent modification setting related to InputManager.distributeGesture (preGesture)
516
517 // initialize Apollo
518// EcosystemManager.getMiscManager().runOnGIOThread(new BlockingRunnable() {
519// public void execute() {
520// ApolloSystem.initialize();
521// }
522// });
523
524 Frame oneFrame = null;
525 if (!username.equals(AuthenticatorBrowser.ADMINACCOUNT)) {
526 // Load in and cache the profile frame using the personal key fetched from keystore.
527 // Reset the personal key once finished so that setting parsing can correctly set it.
528 FrameIO.ClearCache();
529 Text personalKeyText = KeyList.PersonalKey.generateText();
530 personalKeyText.setData(Base64.getEncoder().encodeToString(personalKey.getEncoded()));
531 KeyList.PersonalKey.setSetting(personalKeyText);
532 UserSettings.UserName.set(username);
533 oneFrame = FrameIO.LoadProfile(username);
534 for (int i = 1; i <= FrameIO.getLastNumber(username); i++) {
535 Frame f = FrameIO.LoadFrame(oneFrame.getFramesetName() + i);
536 if (f != null && f.getData() != null && f.getData().contains("MultiuserCredentials")) {
537 AuthenticatorBrowser.CREDENTIALS_FRAME = f.getNumber();
538 }
539 }
540
541 // Parse the settings frame to update the settings datastructure.
542 Text fakeLink = new Text("settings");
543 fakeLink.setLink(oneFrame.getFramesetName() + "2");
544 Settings.parseSettings(fakeLink);
545
546 // Update default folders.
547 UserSettings.setupDefaultFolders();
548
549 // Check mail
550 MailBay.clear();
551 AuthenticatorBrowser.getInstance().loadMailDatabase();
552 Text keyItem = org.expeditee.settings.identity.secrets.KeyList.PrivateKey.get();
553 if (keyItem.getData() != null) {
554 String keyEncoded = keyItem.getData().get(0);
555 byte[] keyBytes = Base64.getDecoder().decode(keyEncoded);
556 PrivateKey key = KeyFactory.getInstance(AsymmetricAlgorithm).generatePrivate(new PKCS8EncodedKeySpec(keyBytes));
557 List<MailEntry> mailForLoggingInUser = Mail.getEntries(UserSettings.UserName.get(), key);
558 for (MailEntry mail: mailForLoggingInUser) {
559 MailBay.addMessage(mail.timestamp, mail.message, mail.message2, mail.options);
560 }
561 }
562 Path deadDropPath = Paths.get(FrameIO.DEAD_DROPS_PATH);
563 for (File connectionDir: deadDropPath.toFile().listFiles()) {
564 if (connectionDir.isDirectory()) {
565 Path deaddropforcontactPath = Paths.get(connectionDir.getAbsolutePath());
566 AuthenticatorBrowser.getInstance().updateLastReadMailTime(deaddropforcontactPath);
567 }
568 }
569
570 } else {
571 UserSettings.UserName.set(AuthenticatorBrowser.ADMINACCOUNT);
572 oneFrame = FrameIO.LoadFrame("multiuser1");
573 }
574
575 Collection<Item> usernameFields = getByData(FrameIO.LoadFrame(Constants.FRAME_MULTIUSER1), "txtUsername");
576 usernameFields.forEach(usernameField -> usernameField.setText(username));
577
578 Frame homeFrame = FrameIO.LoadFrame("home1");
579 DisplayController.setCurrentFrame(homeFrame == null ? oneFrame : homeFrame, false);
580 }
581
582 /*
583 * Function to share a specified frameset.
584 * Currently, this moves the frameset to the 'Shared By Me' directory and then relies on the user to use Google Drive functionality to share it appropriately.
585 */
586 private static void shareFrameset(Frame toShare) throws IOException {
587 File destinationDir = new File(FrameIO.SHARED_FRAMESETS_PATH + File.separator + toShare.getFramesetName());
588 File sourceDir = new File(toShare.getFramesetPath());
589
590 if (destinationDir.exists()) {
591 MessageBay.errorMessage("A frameset by this name already exists.");
592 return;
593 }
594
595 destinationDir.mkdir();
596 List<Path> files = Files.walk(sourceDir.toPath()).collect(Collectors.toList());
597 Files.move(files.get(0), destinationDir.toPath(), StandardCopyOption.ATOMIC_MOVE);
598
599 MessageBay.displayMessage("The frameset " + toShare.getFramesetName() + " has been moved to " + destinationDir + ". Google Drive functionality can now be used to share it with colleagues.");
600 }
601
602 private static void denyPasswordColleagueRelationship(String colleagueName) throws InvalidKeySpecException, NoSuchAlgorithmException, KeyStoreException, FileNotFoundException, CertificateException, ClassNotFoundException, IOException, SQLException {
603 String time = org.expeditee.stats.Formatter.getDateTime();
604 String sender = UserSettings.UserName.get();
605 String message = "You have received a reply from " + sender + " reguarding your request for assistance.";
606 String message2 = "Unfortunately " + sender + " has indicated that they are unable to help you with your potential password recovery.";
607 Map<String, String> options = new HashMap<String, String>();
608 options.put("Clear Preview Colleague Nominations", "AuthClearPWColleaguesNominated");
609 MailEntry mail = new MailEntry(time, sender, colleagueName, message, message2, options);
610 Mail.sendMail(mail, colleagueName);
611 }
612
613 private static boolean submitPWColleagues(Map<AuthenticationTag, String> userData) throws InvalidKeySpecException, NoSuchAlgorithmException, KeyStoreException, FileNotFoundException, CertificateException, ClassNotFoundException, IOException, SQLException {
614 String colleagueOne = userData.get(AuthenticationTag.ColleagueOne);
615 String colleagueTwo = userData.get(AuthenticationTag.ColleagueTwo);
616 PublicKey colleagueOneKey = AuthenticatorBrowser.getInstance().getPublicKey(colleagueOne);
617 PublicKey colleagueTwoKey = AuthenticatorBrowser.getInstance().getPublicKey(colleagueTwo);
618 if (colleagueOneKey == null) {
619 MessageBay.errorMessage("Unable to get public key for colleague: " + colleagueOne);
620 return false;
621 } else if (colleagueTwoKey == null) {
622 MessageBay.errorMessage("Unable to get public key for colleague: " + colleagueTwo);
623 return false;
624 } else {
625 String time = org.expeditee.stats.Formatter.getDateTime();
626 String sender = userData.get(AuthenticationTag.Username);
627 String topic = "You have received a request for cooperation from your colleague " + sender;
628 String message = "Should " + sender + " forget their password, they would like your help recoverying it.";
629 Map<String, String> arguments = new HashMap<String, String>();
630 arguments.put("I agree to assist " + sender + " if they loose access to their account.", "AuthConfirmPasswordColleagueRelationship " + sender);
631 arguments.put("I wish to excuse myself from this responsibility.", "AuthDenyPasswordColleagueRelationship " + sender);
632 MailEntry mail = new MailEntry(time, sender, colleagueOne, topic, message, arguments);
633 Mail.sendMail(mail, colleagueOne);
634 mail = new MailEntry(time, sender, colleagueTwo, topic, message, arguments);
635 Mail.sendMail(mail, colleagueTwo);
636 AuthenticatorBrowser.getInstance().markRequestedColleagues(UserSettings.UserName.get());
637 return true;
638 }
639 }
640
641
642 private static TextSetting constructTextSetting(String tooltip, String text, String data) {
643 return new TextSetting(tooltip, text) {
644 @Override
645 public Text generateText() {
646 Text t = new Text(text);
647 t.setData(data);
648 return t;
649 }
650 };
651 }
652
653 private static <T> GenericSetting<T> constructGenericSetting(Class<T> type, String tooltip, String name, T value, String frameset) {
654 return new GenericSetting<T>(type, tooltip, name, value) {
655 @Override
656 public Text generateRepresentation(String name, String frameset) {
657 Text t = new Text(name + ": " + value);
658 return t;
659 }
660 };
661 }
662
663 /*
664 * Changes the recorded password for a user in the key store.
665 */
666 private static void changePassword(final Map<AuthenticationTag, String> userdata) throws NoSuchAlgorithmException, KeyStoreException, FileNotFoundException, CertificateException, IOException, ClassNotFoundException, SQLException {
667 final String username = userdata.get(AuthenticationTag.Username);
668 final String password = userdata.get(AuthenticationTag.Password);
669 final String newpassword = userdata.get(AuthenticationTag.NewPassword);
670
671 final SecretKey key = AuthenticatorBrowser.getInstance().getSecretKey(username, password);
672 if (key == null) {
673 MessageBay.errorMessage("The username + existing password combination was incorrect.");
674 } else {
675 AuthenticatorBrowser.getInstance().putKey(username, newpassword, key);
676 MessageBay.displayMessage("Password changed successfully.");
677 }
678 }
679
680// // establish properties
681// final String from = "[email protected]";
682// final Properties properties = System.getProperties();
683//
684// properties.setProperty("mail.transport.protocol", "smtp");
685// properties.setProperty("mail.smtp.host", "smtp.gmail.com");
686// properties.setProperty("mail.smtp.port", "465");
687// properties.setProperty("mail.smtp.starttls.enable", "true");
688// properties.setProperty("mail.smtp.auth", "true");
689// properties.setProperty("mail.smtp.debug", "true");
690// properties.setProperty("mail.smtp.auth", "true");
691// properties.setProperty("mail.smtp.socketFactory.port", "465");
692// properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
693// properties.setProperty("mail.smtp.socketFactory.fallback", "false");
694//
695// final Session session = Session.getDefaultInstance(properties, new javax.mail.Authenticator() {
696// @Override
697// protected PasswordAuthentication getPasswordAuthentication() {
698// return new PasswordAuthentication("noreply.expeditee", "intergalacticnumber");
699// };
700// });
701
702// // construct email message
703// final MimeMessage message = new MimeMessage(session);
704// message.setFrom(new InternetAddress(from));
705// message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
706// message.setSubject("Expeditee Password Recovery");
707// message.setText(intergalacticNumber);
708//
709// // send email message
710// Transport.send(message);
711
712
713 public static void TickBox(final Text item) {
714 if (item.getBackgroundColor() != Colour.RED) {
715 item.setBackgroundColor(Colour.RED);
716 } else {
717 item.setBackgroundColor(Colour.GREEN);
718 }
719 }
720
721 /*
722 * Gets all items on a specified frame that contain the specified data.
723 */
724 public static Collection<Item> getByData(final Frame frame, final String data) {
725 final Collection<Item> allItems = frame.getAllItems();
726 allItems.removeIf(i -> i.getData() == null || !i.hasData(data));
727 return allItems;
728 }
729
730 public static Collection<Item> getByContent(final Frame frame, final String content) {
731 final Collection<Item> allItems = frame.getAllItems();
732 allItems.removeIf(i -> i.getText().compareTo(content) != 0);
733 return allItems;
734 }
735}
Note: See TracBrowser for help on using the repository browser.