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

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

You can now check for new mail while logged in (when you open the mail bay)

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