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

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

Fixed exceptions being thrown incorrectly in following situations:

Incorrect login
Existing account on account creation
ToggleBay action run but not logged in

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