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

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

Progress on the 'Forgot Password' process

File size: 23.1 KB
Line 
1package org.expeditee.auth;
2
3import java.io.File;
4import java.io.FileNotFoundException;
5import java.io.IOException;
6import java.nio.file.Files;
7import java.nio.file.Path;
8import java.nio.file.Paths;
9import java.nio.file.StandardCopyOption;
10import java.security.InvalidKeyException;
11import java.security.KeyFactory;
12import java.security.KeyStoreException;
13import java.security.NoSuchAlgorithmException;
14import java.security.PrivateKey;
15import java.security.PublicKey;
16import java.security.cert.CertificateException;
17import java.security.spec.InvalidKeySpecException;
18import java.security.spec.PKCS8EncodedKeySpec;
19import java.sql.SQLException;
20import java.text.ParseException;
21import java.util.Base64;
22import java.util.Collection;
23import java.util.HashMap;
24import java.util.List;
25import java.util.Map;
26import java.util.Optional;
27import java.util.Scanner;
28import java.util.stream.Collectors;
29
30import javax.crypto.BadPaddingException;
31import javax.crypto.IllegalBlockSizeException;
32import javax.crypto.NoSuchPaddingException;
33
34import org.expeditee.agents.ExistingFramesetException;
35import org.expeditee.agents.InvalidFramesetNameException;
36import org.expeditee.auth.Mail.MailEntry;
37import org.expeditee.auth.account.Authenticate;
38import org.expeditee.auth.account.Authenticate.AuthenticationResult;
39import org.expeditee.auth.account.Create;
40import org.expeditee.auth.account.Password;
41import org.expeditee.auth.gui.MailBay;
42import org.expeditee.auth.tags.AuthenticationTag;
43import org.expeditee.core.Colour;
44import org.expeditee.gui.DisplayController;
45import org.expeditee.gui.Frame;
46import org.expeditee.gui.FrameIO;
47import org.expeditee.gui.MessageBay;
48import org.expeditee.items.Item;
49import org.expeditee.items.Text;
50import org.expeditee.settings.UserSettings;
51import org.expeditee.settings.identity.secrets.KeyList;
52import org.expeditee.stats.Formatter;
53import org.ngikm.cryptography.CryptographyConstants;
54
55public class Actions implements CryptographyConstants {
56
57 //Debug Functions
58 public static void SendTestMessage(String colleagueName) throws InvalidKeySpecException, NoSuchAlgorithmException, FileNotFoundException, KeyStoreException, CertificateException, ClassNotFoundException, IOException, SQLException {
59 String time = org.expeditee.stats.Formatter.getDateTime();
60 String sender = UserSettings.UserName.get();
61 String topic = "Test Message";
62 String message = "This is a test message.";
63 Map<String, String> options = new HashMap<String, String>();
64 options.put("Neat", "Beep");
65 MailEntry mail = new MailEntry(time, sender, colleagueName, topic, message, options);
66 Mail.sendMail(mail, colleagueName);
67 MessageBay.displayMessage("Test message sent.");
68 }
69 public static void SendTestMessageHemi(String param) {
70 String time = Formatter.getDateTime();
71 String sender = UserSettings.UserName.get();
72 String recipient = param.split(" ")[0];
73 String message = param.split(" ")[1];
74 Map<String, String> options = new HashMap<String, String>();
75 options.put("Accept", "beep");
76 options.put("Reject", "beep");
77 MailEntry mail = new MailEntry(time, sender, recipient, "Have a key", message, options);
78 Mail.sendMail(mail, recipient);
79 MessageBay.displayMessage("Test message sent.");
80 }
81
82 private static String userbackup = "authadmin";
83 public static void ToggleAuth() {
84 String backup = UserSettings.UserName.get();
85 UserSettings.UserName.set(userbackup);
86 userbackup = backup;
87 }
88
89 /**
90 * Display Expeditee Mail
91 * @throws IOException
92 * @throws SQLException
93 * @throws ClassNotFoundException
94 * @throws CertificateException
95 * @throws NoSuchAlgorithmException
96 * @throws FileNotFoundException
97 * @throws KeyStoreException
98 * @throws ParseException
99 * @throws InvalidKeySpecException
100 * @throws BadPaddingException
101 * @throws IllegalBlockSizeException
102 * @throws NoSuchPaddingException
103 * @throws InvalidKeyException
104 */
105 public static void ToggleBay() throws KeyStoreException, FileNotFoundException, NoSuchAlgorithmException, CertificateException, ClassNotFoundException, SQLException, IOException, ParseException, InvalidKeySpecException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
106 if (!AuthenticatorBrowser.isAuthenticated()) return;
107 if (!DisplayController.isMailMode()) {
108 MailBay.ensureLink();
109 Mail.clear();
110 String keyEncoded = KeyList.PrivateKey.get().getData().get(0);
111 byte[] keyBytes = Base64.getDecoder().decode(keyEncoded);
112 PrivateKey key = KeyFactory.getInstance(AsymmetricAlgorithm).generatePrivate(new PKCS8EncodedKeySpec(keyBytes));
113 Mail.checkMail(key);
114 }
115 DisplayController.ToggleMailMode();
116 }
117
118 /**
119 * Action used to navigate the authorised user back to their desktop.
120 */
121 public static void AuthGoToDesktop() {
122 DisplayController.setCurrentFrame(FrameIO.LoadFrame(UserSettings.HomeFrame.get()), true);
123 }
124
125 /**
126 * Action used to created a new user account.
127 * Attempts to use content from text items on frame, will default to java properties if they cannot be found.
128 * Will fail if it cannot find content from text items on frame and all required java properties are not present.
129 * @throws SQLException
130 * @throws IOException
131 * @throws ExistingFramesetException
132 * @throws InvalidFramesetNameException
133 * @throws ClassNotFoundException
134 * @throws FileNotFoundException
135 * @throws CertificateException
136 * @throws NoSuchAlgorithmException
137 * @throws KeyStoreException
138 * @throws BadPaddingException
139 * @throws IllegalBlockSizeException
140 * @throws NoSuchPaddingException
141 * @throws InvalidKeySpecException
142 * @throws InvalidKeyException
143 * @throws ParseException
144 * @throws Exception
145 */
146 public static void AuthCreateAccount() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, ClassNotFoundException, InvalidFramesetNameException, ExistingFramesetException, IOException, SQLException, InvalidKeyException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, ParseException {
147 Collection<Text> textItems = DisplayController.getCurrentFrame().getTextItems();
148 Optional<Map<AuthenticationTag, String>> userdata =
149 AuthenticationTag.fetchUserData(textItems, false,
150 AuthenticationTag.Username,
151 AuthenticationTag.Password,
152 AuthenticationTag.PasswordAgain,
153 AuthenticationTag.Email,
154 AuthenticationTag.EmailAgain);
155
156 if (userdata.isPresent()) {
157 Map<AuthenticationTag, String> userData = userdata.get();
158
159 // A profile already existing with 'username' means an account cannot be created with that username.
160 if (FrameIO.getProfilesList().contains(userData.get(AuthenticationTag.Username))) {
161 MessageBay.errorMessage("A Expeditee profile with this username already exists, please choose another.");
162 return;
163 }
164
165 // The chosen username must be a valid frameset name.
166 if (!FrameIO.isValidFramesetName(userData.get(AuthenticationTag.Username))) {
167 MessageBay.errorMessage("The provided username must begin and end with a letter and contain only letters and numbers inbetween, please choose another.");
168 return;
169 }
170
171 // The passwords provided must match
172 if (userData.get(AuthenticationTag.Password).compareTo(userData.get(AuthenticationTag.PasswordAgain)) != 0) {
173 MessageBay.errorMessage("The provided passwords do not match, please fix this and try again.");
174 return;
175 }
176
177 // The emails provided must match
178 if (userData.get(AuthenticationTag.Email).compareTo(userData.get(AuthenticationTag.EmailAgain)) != 0) {
179 MessageBay.errorMessage("The provided emails do not match, please fix this and try again.");
180 return;
181 }
182
183 Create.createAccount(userData);
184 Authenticate.login(userData);
185 AuthenticatorBrowser.Authenticated = true;
186 } else {
187 MessageBay.errorMessage("Please fill out all the supplied text boxes.");
188 }
189 }
190
191 /**
192 * Action used to start authentication as a specified user.
193 * Attempts to use content from text items on frame, will default to java properties if they cannot be found.
194 * Will fail if it cannot find content from text items on frame and all required java properties are not present.
195 * @throws Exception
196 */
197 public static void AuthLogin() {
198 final Collection<Text> textItems = DisplayController.getCurrentFrame().getTextItems();
199 final Optional<Map<AuthenticationTag, String>> userdata = AuthenticationTag.fetchUserData(textItems, false, AuthenticationTag.Username, AuthenticationTag.Password);
200 if (userdata.isPresent()) {
201 AuthenticationResult result = Authenticate.login(userdata.get());
202 if (result == AuthenticationResult.SuccessLogin) {
203 MessageBay.displayMessage(result.toString());
204 } else {
205 MessageBay.errorMessage(result.toString());
206 }
207 //login(userdata.get());
208 AuthenticatorBrowser.Authenticated = true;
209 } else {
210 MessageBay.errorMessage("Please fill out all the supplied text boxes.");
211 }
212 }
213
214 public static void AuthLogout() {
215 MessageBay.displayMessage(Authenticate.logout().toString());
216 }
217
218 /**
219 * Action used to change the currently authenticated users password.
220 * Attempts to use content from text items on frame, will default to java properties if they cannot be found.
221 * Will fail if it cannot find content from text items on frame and all required java properties are not present.
222 * Will fail if no user is currently logged in.
223 * @throws IOException
224 * @throws CertificateException
225 * @throws FileNotFoundException
226 * @throws KeyStoreException
227 * @throws NoSuchAlgorithmException
228 * @throws SQLException
229 * @throws ClassNotFoundException
230 */
231 public static void AuthChangePassword() throws NoSuchAlgorithmException, KeyStoreException, FileNotFoundException, CertificateException, IOException, ClassNotFoundException, SQLException {
232 final Collection<Text> textItems = DisplayController.getCurrentFrame().getTextItems();
233
234 if (!AuthenticatorBrowser.Authenticated) {
235 MessageBay.errorMessage("You must be logged in to perform this action.");
236 } else {
237 final Optional<Map<AuthenticationTag, String>> userdata = AuthenticationTag.fetchUserData(textItems, false, AuthenticationTag.Password, AuthenticationTag.NewPassword, AuthenticationTag.NewPasswordAgain);
238 if (userdata.isPresent()) {
239 final Map<AuthenticationTag, String> userData = userdata.get();
240 if (userData.get(AuthenticationTag.NewPassword).compareTo(userData.get(AuthenticationTag.NewPasswordAgain)) != 0) {
241 MessageBay.errorMessage("The provided passwords do not match, please fix this and try again.");
242 } else {
243 userData.put(AuthenticationTag.Username, UserSettings.UserName.get());
244 Password.changePassword(userData);
245 }
246 } else {
247 MessageBay.errorMessage("Please fill out all the supplied text boxes.");
248 }
249 }
250 }
251
252 public static void AuthGotoAccountManagement() {
253 if (AuthenticatorBrowser.Authenticated) {
254 DisplayController.setCurrentFrame(FrameIO.LoadFrame("multiuser1"), false);
255 } else {
256 DisplayController.setCurrentFrame(FrameIO.LoadFrame("authentication1"), false);
257 }
258 }
259
260 public static void AuthResetPasswordPt1() {
261 Collection<Text> textItems = DisplayController.getCurrentFrame().getTextItems();
262 Optional<Map<AuthenticationTag, String>> userdata = AuthenticationTag.fetchUserData(textItems, false, AuthenticationTag.Username);
263 if (userdata.isPresent()) {
264 Map<AuthenticationTag, String> userData = userdata.get();
265
266 String username = userData.get(AuthenticationTag.Username);
267 Path credentialsDirPath = Paths.get(FrameIO.PROFILE_PATH).resolve(username).resolve(username + "-credentials");
268 Path credentialsFilePath = credentialsDirPath.resolve("credentials.inf");
269 String fileName = null;
270 if (credentialsFilePath.toFile().exists()) {
271 try (Scanner in = new Scanner(credentialsFilePath)) {
272 fileName = in.nextLine();
273 } catch (IOException e) {
274 MessageBay.errorMessage("Unable to locate public email for specified user, are they registered on this computer?");
275 return;
276 }
277 } else {
278 MessageBay.errorMessage("Unable to locate public email for specified user, are they registered on this computer?");
279 return;
280 }
281
282 int number = Integer.parseInt(fileName.replace(".exp", ""));
283 Frame credentialsFrame = FrameIO.LoadFrame(username + number, FrameIO.PROFILE_PATH);
284 textItems = credentialsFrame.getTextItems();
285 textItems.removeIf(text -> !text.getText().startsWith("Email: "));
286 if (textItems.isEmpty()) {
287 MessageBay.errorMessage("Unable to locate public email for specified user, are they registered on this computer?");
288 return;
289 } else {
290 Text emailText = textItems.iterator().next();
291 String email = emailText.getText().replace("Email: ", "");
292 userData.put(AuthenticationTag.Email, email);
293 Password.generateAndDeliverIntergalacticNumber(userData);
294 MessageBay.displayMessage("A Intergalactic number has been sent to the email associated with your account. Enter it below to proceed.");
295 }
296 }
297 }
298
299 public static void AuthResetPasswordPt2() {
300 MessageBay.displayMessage("AuthResetPasswordPt2");
301 }
302
303 public static void AuthShareFrameset() throws IOException {
304 Collection<Text> textItems = DisplayController.getCurrentFrame().getTextItems();
305
306 Optional<Map<AuthenticationTag, String>> userdata = AuthenticationTag.fetchUserData(textItems, false, AuthenticationTag.Frameset);
307 if (userdata.isPresent()) {
308 Map<AuthenticationTag, String> userData = userdata.get();
309 FrameIO.SuspendCache();
310 Frame toShare = FrameIO.LoadFrame(userData.get(AuthenticationTag.Frameset) + 1);
311 FrameIO.ResumeCache();
312
313 if (toShare == null) {
314 MessageBay.errorMessage("Insufficient information provided to complete this action.");
315 return;
316 }
317
318 shareFrameset(toShare);
319 }
320 }
321
322 /**
323 * Navigation action for progressing the process of recruiting colleagues to assist in password recovery.
324 * Hides certain content that AuthSubmitPWCollegues goes onto show if it does not fail.
325 */
326 public static void AuthGotoColleagueSubmissionFrame() {
327 Frame destination = FrameIO.LoadFrame("authentication7");
328 DisplayController.setCurrentFrame(destination, true);
329 Collection<Item> toHide = getByData(destination, "ShowOnProgress");
330 for (Item i: toHide) {
331 i.setVisible(false);
332 }
333 }
334
335 /**
336 * Action used to start the process of formalising the password recovery process.
337 * @throws SQLException
338 * @throws IOException
339 * @throws ClassNotFoundException
340 * @throws CertificateException
341 * @throws NoSuchAlgorithmException
342 * @throws FileNotFoundException
343 * @throws KeyStoreException
344 * @throws InvalidKeySpecException
345 */
346 public static void AuthSubmitPWColleagues() throws InvalidKeySpecException, NoSuchAlgorithmException, KeyStoreException, FileNotFoundException, CertificateException, ClassNotFoundException, IOException, SQLException {
347 Frame currentFrame = DisplayController.getCurrentFrame();
348 Collection<Text> textItems = currentFrame.getTextItems();
349
350 if (!AuthenticatorBrowser.Authenticated) {
351 MessageBay.errorMessage("You must be logged in to perform this action.");
352 return;
353 }
354
355 Optional<Map<AuthenticationTag, String>> userdata = AuthenticationTag.fetchUserData(textItems, false, AuthenticationTag.ColleagueOne, AuthenticationTag.ColleagueTwo);
356 if (userdata.isPresent()) {
357 Map<AuthenticationTag, String> userData = userdata.get();
358 String colleagueOne = userData.get(AuthenticationTag.ColleagueOne);
359 Path colleagueOnePath = Paths.get(FrameIO.CONTACTS_PATH).resolve(colleagueOne + "-credentials");
360 String colleagueTwo = userData.get(AuthenticationTag.ColleagueTwo);
361 Path colleagueTwoPath = Paths.get(FrameIO.CONTACTS_PATH).resolve(colleagueTwo + "-credentials");
362 if (!colleagueOnePath.toFile().exists()) {
363 MessageBay.errorMessage("Your nominated colleague: " + colleagueOne + " must exist in your contacts.");
364 } else if (!colleagueTwoPath.toFile().exists()) {
365 MessageBay.errorMessage("Your nominated colleague: " + colleagueTwo + " must exist in your contacts.");
366 } else {
367 userData.put(AuthenticationTag.Username, UserSettings.UserName.get());
368 boolean success = submitPWColleagues(userData);
369 if (success) {
370 Collection<Item> toShow = getByData(currentFrame, "ShowOnProgress");
371 for (Item i: toShow) {
372 i.setVisible(true);
373 }
374 currentFrame.change();
375 MessageBay.displayMessage("-------Messages sent-------");
376 }
377 FrameIO.SaveFrame(currentFrame);
378 DisplayController.requestRefresh(false);
379 }
380 }
381 }
382
383// public static void AuthSetupPasswordRecovery() throws KeyStoreException, FileNotFoundException, NoSuchAlgorithmException, CertificateException, ClassNotFoundException, IOException, SQLException, UnrecoverableEntryException {
384// if (!UserSettings.Authenticated.get()) {
385// MessageBay.errorMessage("You must be logged in to perform this action.");
386// } else if (!Authenticator.getInstance().hasRegisteredEmail(UserSettings.UserName.get())) {
387// Frame registerEmailFrame = FrameIO.LoadFrame("authentication4");
388// DisplayController.setCurrentFrame(registerEmailFrame, true);
389// } else if (!Authenticator.getInstance().hasRequestedColleagues(UserSettings.UserName.get()) && Authenticator.getInstance().getColleagues(UserSettings.UserName.get()) == null) {
390// Frame submitColleaguesFrame = FrameIO.LoadFrame("authentication5");
391// DisplayController.setCurrentFrame(submitColleaguesFrame, true);
392// } else if (Authenticator.getInstance().hasRequestedColleagues(UserSettings.UserName.get()) && Authenticator.getInstance().getColleagues(UserSettings.UserName.get()) == null) {
393// MessageBay.displayMessage("You have already nominated two colleagues to assist you in the process of password recovery and are awaiting their response."
394// + " You will be alerted on Expeditee startup when they have both responded.");
395// } else if (Authenticator.getInstance().getColleagues(UserSettings.UserName.get()) != null) {
396// MessageBay.displayMessage("You have completed the Password Recovery Setup process, there is nothing more to do here.");
397// }
398// }
399
400 public static void AuthConfirmPasswordColleagueRelationship(String colleagueName) {
401
402 }
403
404 public static void AuthDenyPasswordColleagueRelationship(String colleagueName) throws InvalidKeySpecException, NoSuchAlgorithmException,
405 KeyStoreException, FileNotFoundException, CertificateException, ClassNotFoundException, IOException, SQLException {
406 denyPasswordColleagueRelationship(colleagueName);
407 }
408
409 public static void AuthClearPWColleaguesNominated() {
410
411 }
412
413 /*
414 * Function to share a specified frameset.
415 * 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.
416 */
417 private static void shareFrameset(Frame toShare) throws IOException {
418 File destinationDir = new File(FrameIO.SHARED_FRAMESETS_PATH + File.separator + toShare.getFramesetName());
419 File sourceDir = new File(toShare.getFramesetPath());
420
421 if (destinationDir.exists()) {
422 MessageBay.errorMessage("A frameset by this name already exists.");
423 return;
424 }
425
426 destinationDir.mkdir();
427 List<Path> files = Files.walk(sourceDir.toPath()).collect(Collectors.toList());
428 Files.move(files.get(0), destinationDir.toPath(), StandardCopyOption.ATOMIC_MOVE);
429
430 MessageBay.displayMessage("The frameset " + toShare.getFramesetName() + " has been moved to " + destinationDir + ". Google Drive functionality can now be used to share it with colleagues.");
431 }
432
433 private static void denyPasswordColleagueRelationship(String colleagueName) throws InvalidKeySpecException, NoSuchAlgorithmException, KeyStoreException, FileNotFoundException, CertificateException, ClassNotFoundException, IOException, SQLException {
434 String time = org.expeditee.stats.Formatter.getDateTime();
435 String sender = UserSettings.UserName.get();
436 String message = "You have received a reply from " + sender + " reguarding your request for assistance.";
437 String message2 = "Unfortunately " + sender + " has indicated that they are unable to help you with your potential password recovery.";
438 Map<String, String> options = new HashMap<String, String>();
439 options.put("Clear Preview Colleague Nominations", "AuthClearPWColleaguesNominated");
440 MailEntry mail = new MailEntry(time, sender, colleagueName, message, message2, options);
441 Mail.sendMail(mail, colleagueName);
442 }
443
444 private static boolean submitPWColleagues(Map<AuthenticationTag, String> userData) throws InvalidKeySpecException, NoSuchAlgorithmException, KeyStoreException, FileNotFoundException, CertificateException, ClassNotFoundException, IOException, SQLException {
445 String colleagueOne = userData.get(AuthenticationTag.ColleagueOne);
446 String colleagueTwo = userData.get(AuthenticationTag.ColleagueTwo);
447 PublicKey colleagueOneKey = AuthenticatorBrowser.getInstance().getPublicKey(colleagueOne);
448 PublicKey colleagueTwoKey = AuthenticatorBrowser.getInstance().getPublicKey(colleagueTwo);
449 if (colleagueOneKey == null) {
450 MessageBay.errorMessage("Unable to get public key for colleague: " + colleagueOne);
451 return false;
452 } else if (colleagueTwoKey == null) {
453 MessageBay.errorMessage("Unable to get public key for colleague: " + colleagueTwo);
454 return false;
455 } else {
456 String time = org.expeditee.stats.Formatter.getDateTime();
457 String sender = userData.get(AuthenticationTag.Username);
458 String topic = "You have received a request for cooperation from your colleague " + sender;
459 String message = "Should " + sender + " forget their password, they would like your help recoverying it.";
460 Map<String, String> arguments = new HashMap<String, String>();
461 arguments.put("I agree to assist " + sender + " if they loose access to their account.", "AuthConfirmPasswordColleagueRelationship " + sender);
462 arguments.put("I wish to excuse myself from this responsibility.", "AuthDenyPasswordColleagueRelationship " + sender);
463 MailEntry mail = new MailEntry(time, sender, colleagueOne, topic, message, arguments);
464 Mail.sendMail(mail, colleagueOne);
465 mail = new MailEntry(time, sender, colleagueTwo, topic, message, arguments);
466 Mail.sendMail(mail, colleagueTwo);
467 AuthenticatorBrowser.getInstance().markRequestedColleagues(UserSettings.UserName.get());
468 return true;
469 }
470 }
471
472 public static void TickBox(final Text item) {
473 if (item.getBackgroundColor() != Colour.RED) {
474 item.setBackgroundColor(Colour.RED);
475 } else {
476 item.setBackgroundColor(Colour.GREEN);
477 }
478 }
479
480 /*
481 * Gets all items on a specified frame that contain the specified data.
482 */
483 public static Collection<Item> getByData(final Frame frame, final String data) {
484 final Collection<Item> allItems = frame.getAllItems();
485 allItems.removeIf(i -> i.getData() == null || !i.hasData(data));
486 return allItems;
487 }
488
489 public static Collection<Item> getByContent(final Frame frame, final String content) {
490 final Collection<Item> allItems = frame.getAllItems();
491 allItems.removeIf(i -> i.getText().compareTo(content) != 0);
492 return allItems;
493 }
494}
Note: See TracBrowser for help on using the repository browser.