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

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

Use SecureRandom to generate personal key.

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