package org.expeditee.auth; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.security.InvalidKeyException; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.sql.SQLException; import java.text.ParseException; import java.util.Base64; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Random; import java.util.function.Consumer; import java.util.stream.Collectors; import javax.crypto.BadPaddingException; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.apollo.io.AudioPathManager; import org.expeditee.agents.ExistingFramesetException; import org.expeditee.agents.InvalidFramesetNameException; import org.expeditee.auth.Mail.MailEntry; import org.expeditee.auth.account.Authenticate; import org.expeditee.auth.account.Authenticate.AuthenticationResult; import org.expeditee.auth.gui.MailBay; import org.expeditee.auth.tags.AuthenticationTag; import org.expeditee.auth.tags.Constants; import org.expeditee.core.Colour; import org.expeditee.gui.DisplayController; import org.expeditee.gui.Frame; import org.expeditee.gui.FrameIO; import org.expeditee.gui.MessageBay; import org.expeditee.gui.MessageBay.Progress; import org.expeditee.io.ExpReader; import org.expeditee.items.Item; import org.expeditee.items.PermissionPair; import org.expeditee.items.Text; import org.expeditee.items.UserAppliedPermission; import org.expeditee.setting.GenericSetting; import org.expeditee.setting.Setting; import org.expeditee.setting.TextSetting; import org.expeditee.settings.UserSettings; import org.expeditee.settings.folders.FolderSettings; import org.expeditee.settings.identity.secrets.KeyList; import org.expeditee.stats.Formatter; import org.ngikm.cryptography.CryptographyConstants; public class Actions implements CryptographyConstants { //Debug Functions public static void SendTestMessage(String colleagueName) throws InvalidKeySpecException, NoSuchAlgorithmException, FileNotFoundException, KeyStoreException, CertificateException, ClassNotFoundException, IOException, SQLException { String time = org.expeditee.stats.Formatter.getDateTime(); String sender = UserSettings.UserName.get(); String topic = "Test Message"; String message = "This is a test message."; Map options = new HashMap(); options.put("Neat", "Beep"); MailEntry mail = new MailEntry(time, sender, colleagueName, topic, message, options); Mail.sendMail(mail, colleagueName); MessageBay.displayMessage("Test message sent."); } public static void SendTestMessageHemi(String param) { String time = Formatter.getDateTime(); String sender = UserSettings.UserName.get(); String recipient = param.split(" ")[0]; String message = param.split(" ")[1]; Map options = new HashMap(); options.put("Accept", "beep"); options.put("Reject", "beep"); MailEntry mail = new MailEntry(time, sender, recipient, "Have a key", message, options); Mail.sendMail(mail, recipient); MessageBay.displayMessage("Test message sent."); } private static String userbackup = "authadmin"; public static void ToggleAuth() { String backup = UserSettings.UserName.get(); UserSettings.UserName.set(userbackup); userbackup = backup; } /** * Display Expeditee Mail * @throws IOException * @throws SQLException * @throws ClassNotFoundException * @throws CertificateException * @throws NoSuchAlgorithmException * @throws FileNotFoundException * @throws KeyStoreException * @throws ParseException * @throws InvalidKeySpecException * @throws BadPaddingException * @throws IllegalBlockSizeException * @throws NoSuchPaddingException * @throws InvalidKeyException */ public static void ToggleBay() throws KeyStoreException, FileNotFoundException, NoSuchAlgorithmException, CertificateException, ClassNotFoundException, SQLException, IOException, ParseException, InvalidKeySpecException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { if (!AuthenticatorBrowser.isAuthenticated()) return; if (!DisplayController.isMailMode()) { MailBay.ensureLink(); Mail.clear(); String keyEncoded = KeyList.PrivateKey.get().getData().get(0); byte[] keyBytes = Base64.getDecoder().decode(keyEncoded); PrivateKey key = KeyFactory.getInstance(AsymmetricAlgorithm).generatePrivate(new PKCS8EncodedKeySpec(keyBytes)); Mail.checkMail(key); } DisplayController.ToggleMailMode(); } /** * Action used to navigate the authorised user back to their desktop. */ public static void AuthGoToDesktop() { DisplayController.setCurrentFrame(FrameIO.LoadFrame(UserSettings.HomeFrame.get()), true); } /** * Action used to created a new user account. * Attempts to use content from text items on frame, will default to java properties if they cannot be found. * Will fail if it cannot find content from text items on frame and all required java properties are not present. * @throws SQLException * @throws IOException * @throws ExistingFramesetException * @throws InvalidFramesetNameException * @throws ClassNotFoundException * @throws FileNotFoundException * @throws CertificateException * @throws NoSuchAlgorithmException * @throws KeyStoreException * @throws BadPaddingException * @throws IllegalBlockSizeException * @throws NoSuchPaddingException * @throws InvalidKeySpecException * @throws InvalidKeyException * @throws ParseException * @throws Exception */ public static void AuthCreateAccount() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, ClassNotFoundException, InvalidFramesetNameException, ExistingFramesetException, IOException, SQLException, InvalidKeyException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, ParseException { Collection textItems = DisplayController.getCurrentFrame().getTextItems(); Optional> userdata = AuthenticationTag.fetchUserData(textItems, false, AuthenticationTag.Username, AuthenticationTag.Password, AuthenticationTag.PasswordAgain, AuthenticationTag.Email, AuthenticationTag.EmailAgain); if (userdata.isPresent()) { Map userData = userdata.get(); // A profile already existing with 'username' means an account cannot be created with that username. if (FrameIO.getProfilesList().contains(userData.get(AuthenticationTag.Username))) { MessageBay.errorMessage(Constants.ERROR_PROFILE_NAME_PREEXISTS); return; } // The chosen username must be a valid frameset name. if (!FrameIO.isValidFramesetName(userData.get(AuthenticationTag.Username))) { MessageBay.errorMessage(Constants.ERROR_INVALID_USERNAME); return; } // The passwords provided must match if (userData.get(AuthenticationTag.Password).compareTo(userData.get(AuthenticationTag.PasswordAgain)) != 0) { MessageBay.errorMessage(Constants.ERROR_MISMATCH_PASSWORDS); return; } // The emails provided must match if (userData.get(AuthenticationTag.Email).compareTo(userData.get(AuthenticationTag.EmailAgain)) != 0) { MessageBay.errorMessage(Constants.ERROR_MISMATCH_EMAILS); return; } createAccount(userData); Authenticate.login(userData); AuthenticatorBrowser.Authenticated = true; } else { MessageBay.errorMessage(Constants.ERROR_INSUFFICIENT_INFORMATION_PROVIDED); } } /** * Action used to start authentication as a specified user. * Attempts to use content from text items on frame, will default to java properties if they cannot be found. * Will fail if it cannot find content from text items on frame and all required java properties are not present. * @throws Exception */ public static void AuthLogin() { final Collection textItems = DisplayController.getCurrentFrame().getTextItems(); final Optional> userdata = AuthenticationTag.fetchUserData(textItems, false, AuthenticationTag.Username, AuthenticationTag.Password); if (userdata.isPresent()) { AuthenticationResult result = Authenticate.login(userdata.get()); if (result == AuthenticationResult.SuccessLogin) { MessageBay.displayMessage(result.toString()); } else { MessageBay.errorMessage(result.toString()); } //login(userdata.get()); AuthenticatorBrowser.Authenticated = true; } else { MessageBay.errorMessage(Constants.ERROR_INSUFFICIENT_INFORMATION_PROVIDED); } } public static void AuthLogout() { MessageBay.displayMessage(Authenticate.logout().toString()); } /** * Action used to change the currently authenticated users password. * Attempts to use content from text items on frame, will default to java properties if they cannot be found. * Will fail if it cannot find content from text items on frame and all required java properties are not present. * Will fail if no user is currently logged in. * @throws IOException * @throws CertificateException * @throws FileNotFoundException * @throws KeyStoreException * @throws NoSuchAlgorithmException * @throws SQLException * @throws ClassNotFoundException */ public static void AuthChangePassword() throws NoSuchAlgorithmException, KeyStoreException, FileNotFoundException, CertificateException, IOException, ClassNotFoundException, SQLException { final Collection textItems = DisplayController.getCurrentFrame().getTextItems(); if (!AuthenticatorBrowser.Authenticated) { MessageBay.errorMessage(Constants.ERROR_MUST_BE_LOGGED_IN); } else { final Optional> userdata = AuthenticationTag.fetchUserData(textItems, false, AuthenticationTag.Password, AuthenticationTag.NewPassword, AuthenticationTag.NewPasswordAgain); if (userdata.isPresent()) { final Map userData = userdata.get(); if (userData.get(AuthenticationTag.NewPassword).compareTo(userData.get(AuthenticationTag.NewPasswordAgain)) != 0) { MessageBay.errorMessage(Constants.ERROR_MISMATCH_PASSWORDS); } else { userData.put(AuthenticationTag.Username, UserSettings.UserName.get()); changePassword(userData); } } else { MessageBay.errorMessage(Constants.ERROR_INSUFFICIENT_INFORMATION_PROVIDED); } } } public static void AuthGotoAccountManagement() { if (AuthenticatorBrowser.Authenticated) { DisplayController.setCurrentFrame(FrameIO.LoadFrame(Constants.FRAME_MULTIUSER1), false); } else { DisplayController.setCurrentFrame(FrameIO.LoadFrame(Constants.FRAME_AUTHENTICATION1), false); } } public static void AuthShareFrameset() throws IOException { Collection textItems = DisplayController.getCurrentFrame().getTextItems(); Optional> userdata = AuthenticationTag.fetchUserData(textItems, false, AuthenticationTag.Frameset); if (userdata.isPresent()) { Map userData = userdata.get(); FrameIO.SuspendCache(); Frame toShare = FrameIO.LoadFrame(userData.get(AuthenticationTag.Frameset) + 1); FrameIO.ResumeCache(); if (toShare == null) { MessageBay.errorMessage(Constants.ERROR_INSUFFICIENT_INFORMATION); return; } shareFrameset(toShare); } } /** * Navigation action for progressing the process of recruiting colleagues to assist in password recovery. * Hides certain content that AuthSubmitPWCollegues goes onto show if it does not fail. */ public static void AuthGotoColleagueSubmissionFrame() { Frame destination = FrameIO.LoadFrame(Constants.FRAME_COLLEAGUE_SUBMISSION_FRAME); DisplayController.setCurrentFrame(destination, true); Collection toHide = getByData(destination, Constants.DATA_SHOW_ON_PROGRESS); for (Item i: toHide) { i.setVisible(false); } } /** * Action used to start the process of formalising the password recovery process. * @throws SQLException * @throws IOException * @throws ClassNotFoundException * @throws CertificateException * @throws NoSuchAlgorithmException * @throws FileNotFoundException * @throws KeyStoreException * @throws InvalidKeySpecException */ public static void AuthSubmitPWColleagues() throws InvalidKeySpecException, NoSuchAlgorithmException, KeyStoreException, FileNotFoundException, CertificateException, ClassNotFoundException, IOException, SQLException { Frame currentFrame = DisplayController.getCurrentFrame(); Collection textItems = currentFrame.getTextItems(); if (!AuthenticatorBrowser.Authenticated) { MessageBay.errorMessage(Constants.ERROR_MUST_BE_LOGGED_IN); return; } Optional> userdata = AuthenticationTag.fetchUserData(textItems, false, AuthenticationTag.ColleagueOne, AuthenticationTag.ColleagueTwo); if (userdata.isPresent()) { Map userData = userdata.get(); String colleagueOne = userData.get(AuthenticationTag.ColleagueOne); Path colleagueOnePath = Paths.get(FrameIO.CONTACTS_PATH).resolve(colleagueOne + "-credentials"); String colleagueTwo = userData.get(AuthenticationTag.ColleagueTwo); Path colleagueTwoPath = Paths.get(FrameIO.CONTACTS_PATH).resolve(colleagueTwo + "-credentials"); if (!colleagueOnePath.toFile().exists()) { MessageBay.errorMessage("Your nominated colleague: " + colleagueOne + " must exist in your contacts."); } else if (!colleagueTwoPath.toFile().exists()) { MessageBay.errorMessage("Your nominated colleague: " + colleagueTwo + " must exist in your contacts."); } else { userData.put(AuthenticationTag.Username, UserSettings.UserName.get()); boolean success = submitPWColleagues(userData); if (success) { Collection toShow = getByData(currentFrame, Constants.DATA_SHOW_ON_PROGRESS); for (Item i: toShow) { i.setVisible(true); } currentFrame.change(); MessageBay.displayMessage("-------Messages sent-------"); } FrameIO.SaveFrame(currentFrame); DisplayController.requestRefresh(false); } } } // public static void AuthSetupPasswordRecovery() throws KeyStoreException, FileNotFoundException, NoSuchAlgorithmException, CertificateException, ClassNotFoundException, IOException, SQLException, UnrecoverableEntryException { // if (!UserSettings.Authenticated.get()) { // MessageBay.errorMessage("You must be logged in to perform this action."); // } else if (!Authenticator.getInstance().hasRegisteredEmail(UserSettings.UserName.get())) { // Frame registerEmailFrame = FrameIO.LoadFrame("authentication4"); // DisplayController.setCurrentFrame(registerEmailFrame, true); // } else if (!Authenticator.getInstance().hasRequestedColleagues(UserSettings.UserName.get()) && Authenticator.getInstance().getColleagues(UserSettings.UserName.get()) == null) { // Frame submitColleaguesFrame = FrameIO.LoadFrame("authentication5"); // DisplayController.setCurrentFrame(submitColleaguesFrame, true); // } else if (Authenticator.getInstance().hasRequestedColleagues(UserSettings.UserName.get()) && Authenticator.getInstance().getColleagues(UserSettings.UserName.get()) == null) { // MessageBay.displayMessage("You have already nominated two colleagues to assist you in the process of password recovery and are awaiting their response." // + " You will be alerted on Expeditee startup when they have both responded."); // } else if (Authenticator.getInstance().getColleagues(UserSettings.UserName.get()) != null) { // MessageBay.displayMessage("You have completed the Password Recovery Setup process, there is nothing more to do here."); // } // } public static void AuthConfirmPasswordColleagueRelationship(String colleagueName) { } public static void AuthDenyPasswordColleagueRelationship(String colleagueName) throws InvalidKeySpecException, NoSuchAlgorithmException, KeyStoreException, FileNotFoundException, CertificateException, ClassNotFoundException, IOException, SQLException { denyPasswordColleagueRelationship(colleagueName); } public static void AuthClearPWColleaguesNominated() { } /** * Create a user account using the specified information in userdata. Creates and stores user keys. * @param userdata Should contain username, password and email. */ private static void createAccount(Map userdata) throws InvalidFramesetNameException, ExistingFramesetException, KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, ClassNotFoundException, IOException, SQLException { // Track progress String message = "Creating new user account..."; int progress = 0; int step = 20; // Extract user details String username = userdata.get(AuthenticationTag.Username); String password = userdata.get(AuthenticationTag.Password); String email = userdata.get(AuthenticationTag.Email); Progress progressBar = MessageBay.displayProgress(message); try { progressBar.UpdateMessage(message + "Generating Keys.", progress += step); } catch (Exception e) { e.printStackTrace(); } DisplayController.refreshBayArea(); // Generate keys // Personal key Random rand = new SecureRandom(); byte[] keyBytes = new byte[16]; rand.nextBytes(keyBytes); SecretKey key = new SecretKeySpec(keyBytes, SymmetricAlgorithm); AuthenticatorBrowser.getInstance().putKey(username, password, key); String personalKey = Base64.getEncoder().encodeToString(key.getEncoded()); // Public and private keys KeyPairGenerator keyGen = KeyPairGenerator.getInstance(AsymmetricAlgorithm); keyGen.initialize(1024); KeyPair keyPair = keyGen.generateKeyPair(); String publicKey = Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded()); String privateKey = Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded()); try { progressBar.UpdateMessage(message + "Creating Profile Frameset.", progress += step); } catch (Exception e) { e.printStackTrace(); } DisplayController.refreshBayArea(); // Update in memory settings System.setProperty("user.name", username); UserSettings.UserName.set(username); UserSettings.ProfileName.set(username); UserSettings.setupDefaultFolders(); // Establish the initial settings for the created user. Map initialSettings = new HashMap(); initialSettings.put(Constants.SETTINGS_AUTH_SECRETS_PERSONAL_KEY, constructTextSetting(Constants.TOOLTIP_SETTING_PERSONAL_KEY, "PersonalKey", personalKey)); initialSettings.put(Constants.SETTINGS_AUTH_SECRETS_PRIVATE_KEY, constructTextSetting(Constants.TOOLTIP_SETTING_PRIVATE_KEY, "PrivateKey", privateKey)); initialSettings.put(Constants.SETTINGS_AUTH_PUBLIC_KEY, constructTextSetting(Constants.TOOLTIP_SETTING_PUBLIC_KEY, "PublicKey", publicKey)); initialSettings.put(Constants.SETTINGS_AUTH_EMAIL, constructGenericSetting(String.class, Constants.TOOLTIP_SETTING_EMAIL, "Email", email, username)); initialSettings.put(Constants.SETTINGS_USER_SETTINGS_USER_NAME, constructGenericSetting(String.class, Constants.LABEL_USERNAME, Constants.LABEL_USERNAME, username, username)); initialSettings.put(Constants.SETTINGS_USER_SETTINGS_PROFILE_NAME, constructGenericSetting(String.class, Constants.LABEL_PROFILENAME, Constants.LABEL_PROFILENAME, username, username)); initialSettings.put("settings.UserSettings.HomeFrame", constructGenericSetting(String.class, "The home frame", "HomeFrame", username + 1, username)); initialSettings.put("org.expeditee.gui.folders.FolderSettings.FrameDirs", FolderSettings.FrameDirs); initialSettings.put("org.expeditee.gui.folders.FolderSettings.ImageDirs", FolderSettings.ImageDirs); initialSettings.put("org.expeditee.gui.folders.FolderSettings.AudioDirs", FolderSettings.AudioDirs); // Record the credentials frame number Map> notifiers = new HashMap>(); notifiers.put(Constants.SETTINGS_AUTH, frame -> { AuthenticatorBrowser.CREDENTIALS_FRAME = frame.getNumber(); Collection textItems = frame.getTextItems(); for (Text t: textItems) { if (t.getText().equals("Secrets")) { t.setPermission(new PermissionPair(UserAppliedPermission.followLinks, UserAppliedPermission.denied)); break; } } }); // Create users profile Frame profile = FrameIO.CreateNewProfile(username, initialSettings, notifiers); int lastNumber = FrameIO.getLastNumber(profile.getFramesetName()); for (int i = 1; i <= lastNumber; i++) { Frame f = FrameIO.LoadFrame(profile.getFramesetName() + i); Text titleItem = f.getTitleItem(); if (i == 1 && titleItem != null) { titleItem.delete(); f.setBackgroundColor(new Colour(1, 1, 0.39f)); } f.setOwner(username); f.getAllItems().stream().forEach(item -> item.setOwner(username)); f.setChanged(true); if (f.getNumber() != AuthenticatorBrowser.CREDENTIALS_FRAME) { f.setEncryptionLabel(AuthenticatorBrowser.PROFILEENCRYPTIONLABEL); } Collection secretsLink = getByContent(f, "Secrets"); Collection publicKeyItem = getByContent(f, "PublicKey"); if (!secretsLink.isEmpty() && !publicKeyItem.isEmpty()) { //Then we are on credentials frame f.addToData("MultiuserCredentials"); } Text backupPersonalKey = KeyList.PersonalKey.get(); Text tempPersonalKey = KeyList.PersonalKey.generateText(); tempPersonalKey.setData(personalKey); KeyList.PersonalKey.setSetting(tempPersonalKey); FrameIO.SaveFrame(f); KeyList.PersonalKey.setSetting(backupPersonalKey); } if (AuthenticatorBrowser.CREDENTIALS_FRAME == -1) { System.err.println("authActions::Unable to establish credentials frame for new profile frame. Account creation failed."); return; } try { progressBar.UpdateMessage(message + "Establishing user credentials.", progress += step); } catch (Exception e) { e.printStackTrace(); } DisplayController.refreshBayArea(); // Create credentials File credentialsDir = new File(profile.getFramesetPath() + username + "-credentials"); credentialsDir.mkdir(); // credentials.inf file. String credentialsPath = credentialsDir.getAbsolutePath() + File.separator + "credentials.inf"; File credentialsFile = new File(credentialsPath); credentialsFile.createNewFile(); FileWriter out = new FileWriter(credentialsFile); out.write(AuthenticatorBrowser.CREDENTIALS_FRAME + ".exp"); out.flush(); out.close(); // migrate credentials frame Frame credentialsFrame = FrameIO.LoadFrame(username + AuthenticatorBrowser.CREDENTIALS_FRAME); Path destinationDirectory = Paths.get(credentialsDir.getAbsolutePath()); Path destinationFile = destinationDirectory.resolve(AuthenticatorBrowser.CREDENTIALS_FRAME + ExpReader.EXTENTION); FrameIO.migrateFrame(credentialsFrame, destinationFile); MessageBay.displayMessage(message + "Creating Individual Space."); DisplayController.refreshBayArea(); // Copy private resources to personal area Path personalResources = FrameIO.setupPersonalResources(username); File contactsDir = new File(personalResources.resolve("contacts").toAbsolutePath().toString()); contactsDir.mkdir(); try { progressBar.UpdateMessage(message + "Creating Space For Dead Drops.", progress += step); } catch (Exception e) { e.printStackTrace(); } DisplayController.refreshBayArea(); File deadDropsDir = new File(personalResources.resolve("deaddrops").toAbsolutePath().toString()); deadDropsDir.mkdir(); System.err.println("**** Hardwired call in Apollo's AuthioPathManager"); AudioPathManager.activateAndScanAudioDir(); // **** try { progressBar.UpdateMessage(message + "Done.", progress += step); } catch (Exception e) { e.printStackTrace(); } DisplayController.refreshBayArea(); } /* * Function to share a specified frameset. * 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. */ private static void shareFrameset(Frame toShare) throws IOException { File destinationDir = new File(FrameIO.SHARED_FRAMESETS_PATH + File.separator + toShare.getFramesetName()); File sourceDir = new File(toShare.getFramesetPath()); if (destinationDir.exists()) { MessageBay.errorMessage("A frameset by this name already exists."); return; } destinationDir.mkdir(); List files = Files.walk(sourceDir.toPath()).collect(Collectors.toList()); Files.move(files.get(0), destinationDir.toPath(), StandardCopyOption.ATOMIC_MOVE); MessageBay.displayMessage("The frameset " + toShare.getFramesetName() + " has been moved to " + destinationDir + ". Google Drive functionality can now be used to share it with colleagues."); } private static void denyPasswordColleagueRelationship(String colleagueName) throws InvalidKeySpecException, NoSuchAlgorithmException, KeyStoreException, FileNotFoundException, CertificateException, ClassNotFoundException, IOException, SQLException { String time = org.expeditee.stats.Formatter.getDateTime(); String sender = UserSettings.UserName.get(); String message = "You have received a reply from " + sender + " reguarding your request for assistance."; String message2 = "Unfortunately " + sender + " has indicated that they are unable to help you with your potential password recovery."; Map options = new HashMap(); options.put("Clear Preview Colleague Nominations", "AuthClearPWColleaguesNominated"); MailEntry mail = new MailEntry(time, sender, colleagueName, message, message2, options); Mail.sendMail(mail, colleagueName); } private static boolean submitPWColleagues(Map userData) throws InvalidKeySpecException, NoSuchAlgorithmException, KeyStoreException, FileNotFoundException, CertificateException, ClassNotFoundException, IOException, SQLException { String colleagueOne = userData.get(AuthenticationTag.ColleagueOne); String colleagueTwo = userData.get(AuthenticationTag.ColleagueTwo); PublicKey colleagueOneKey = AuthenticatorBrowser.getInstance().getPublicKey(colleagueOne); PublicKey colleagueTwoKey = AuthenticatorBrowser.getInstance().getPublicKey(colleagueTwo); if (colleagueOneKey == null) { MessageBay.errorMessage("Unable to get public key for colleague: " + colleagueOne); return false; } else if (colleagueTwoKey == null) { MessageBay.errorMessage("Unable to get public key for colleague: " + colleagueTwo); return false; } else { String time = org.expeditee.stats.Formatter.getDateTime(); String sender = userData.get(AuthenticationTag.Username); String topic = "You have received a request for cooperation from your colleague " + sender; String message = "Should " + sender + " forget their password, they would like your help recoverying it."; Map arguments = new HashMap(); arguments.put("I agree to assist " + sender + " if they loose access to their account.", "AuthConfirmPasswordColleagueRelationship " + sender); arguments.put("I wish to excuse myself from this responsibility.", "AuthDenyPasswordColleagueRelationship " + sender); MailEntry mail = new MailEntry(time, sender, colleagueOne, topic, message, arguments); Mail.sendMail(mail, colleagueOne); mail = new MailEntry(time, sender, colleagueTwo, topic, message, arguments); Mail.sendMail(mail, colleagueTwo); AuthenticatorBrowser.getInstance().markRequestedColleagues(UserSettings.UserName.get()); return true; } } private static TextSetting constructTextSetting(String tooltip, String text, String data) { return new TextSetting(tooltip, text) { @Override public Text generateText() { Text t = new Text(text); t.setData(data); return t; } }; } private static GenericSetting constructGenericSetting(Class type, String tooltip, String name, T value, String frameset) { return new GenericSetting(type, tooltip, name, value) { @Override public Text generateRepresentation(String name, String frameset) { Text t = new Text(name + ": " + value); return t; } }; } /* * Changes the recorded password for a user in the key store. */ private static void changePassword(final Map userdata) throws NoSuchAlgorithmException, KeyStoreException, FileNotFoundException, CertificateException, IOException, ClassNotFoundException, SQLException { final String username = userdata.get(AuthenticationTag.Username); final String password = userdata.get(AuthenticationTag.Password); final String newpassword = userdata.get(AuthenticationTag.NewPassword); final SecretKey key = AuthenticatorBrowser.getInstance().getSecretKey(username, password); if (key == null) { MessageBay.errorMessage("The username + existing password combination was incorrect."); } else { AuthenticatorBrowser.getInstance().putKey(username, newpassword, key); MessageBay.displayMessage("Password changed successfully."); } } // // establish properties // final String from = "noreply@expeditee.com"; // final Properties properties = System.getProperties(); // // properties.setProperty("mail.transport.protocol", "smtp"); // properties.setProperty("mail.smtp.host", "smtp.gmail.com"); // properties.setProperty("mail.smtp.port", "465"); // properties.setProperty("mail.smtp.starttls.enable", "true"); // properties.setProperty("mail.smtp.auth", "true"); // properties.setProperty("mail.smtp.debug", "true"); // properties.setProperty("mail.smtp.auth", "true"); // properties.setProperty("mail.smtp.socketFactory.port", "465"); // properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); // properties.setProperty("mail.smtp.socketFactory.fallback", "false"); // // final Session session = Session.getDefaultInstance(properties, new javax.mail.Authenticator() { // @Override // protected PasswordAuthentication getPasswordAuthentication() { // return new PasswordAuthentication("noreply.expeditee", "intergalacticnumber"); // }; // }); // // construct email message // final MimeMessage message = new MimeMessage(session); // message.setFrom(new InternetAddress(from)); // message.addRecipient(Message.RecipientType.TO, new InternetAddress(email)); // message.setSubject("Expeditee Password Recovery"); // message.setText(intergalacticNumber); // // // send email message // Transport.send(message); public static void TickBox(final Text item) { if (item.getBackgroundColor() != Colour.RED) { item.setBackgroundColor(Colour.RED); } else { item.setBackgroundColor(Colour.GREEN); } } /* * Gets all items on a specified frame that contain the specified data. */ public static Collection getByData(final Frame frame, final String data) { final Collection allItems = frame.getAllItems(); allItems.removeIf(i -> i.getData() == null || !i.hasData(data)); return allItems; } public static Collection getByContent(final Frame frame, final String content) { final Collection allItems = frame.getAllItems(); allItems.removeIf(i -> i.getText().compareTo(content) != 0); return allItems; } }