Changeset 1334 for trunk


Ignore:
Timestamp:
04/29/19 13:13:48 (5 years ago)
Author:
bln4
Message:

Refactoring only

Location:
trunk/src/org/expeditee/auth
Files:
1 added
1 deleted
3 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/org/expeditee/auth/Actions.java

    r1331 r1334  
    33import java.io.File;
    44import java.io.FileNotFoundException;
    5 import java.io.FileWriter;
    65import java.io.IOException;
    76import java.nio.file.Files;
     
    1110import java.security.InvalidKeyException;
    1211import java.security.KeyFactory;
    13 import java.security.KeyPair;
    14 import java.security.KeyPairGenerator;
    1512import java.security.KeyStoreException;
    1613import java.security.NoSuchAlgorithmException;
    1714import java.security.PrivateKey;
    1815import java.security.PublicKey;
    19 import java.security.SecureRandom;
    2016import java.security.cert.CertificateException;
    2117import java.security.spec.InvalidKeySpecException;
     
    2925import java.util.Map;
    3026import java.util.Optional;
    31 import java.util.Random;
    32 import java.util.function.Consumer;
    3327import java.util.stream.Collectors;
    3428
     
    3731import javax.crypto.NoSuchPaddingException;
    3832import javax.crypto.SecretKey;
    39 import javax.crypto.spec.SecretKeySpec;
    40 
    41 import org.apollo.io.AudioPathManager;
     33
    4234import org.expeditee.agents.ExistingFramesetException;
    4335import org.expeditee.agents.InvalidFramesetNameException;
     
    4537import org.expeditee.auth.account.Authenticate;
    4638import org.expeditee.auth.account.Authenticate.AuthenticationResult;
     39import org.expeditee.auth.account.Create;
    4740import org.expeditee.auth.gui.MailBay;
    4841import org.expeditee.auth.tags.AuthenticationTag;
    49 import org.expeditee.auth.tags.Constants;
    5042import org.expeditee.core.Colour;
    5143import org.expeditee.gui.DisplayController;
     
    5345import org.expeditee.gui.FrameIO;
    5446import org.expeditee.gui.MessageBay;
    55 import org.expeditee.gui.MessageBay.Progress;
    56 import org.expeditee.io.ExpReader;
    5747import org.expeditee.items.Item;
    58 import org.expeditee.items.PermissionPair;
    5948import org.expeditee.items.Text;
    60 import org.expeditee.items.UserAppliedPermission;
    61 import org.expeditee.setting.GenericSetting;
    62 import org.expeditee.setting.Setting;
    63 import org.expeditee.setting.TextSetting;
    6449import org.expeditee.settings.UserSettings;
    65 import org.expeditee.settings.folders.FolderSettings;
    6650import org.expeditee.settings.identity.secrets.KeyList;
    6751import org.expeditee.stats.Formatter;
     
    174158                        // A profile already existing with 'username' means an account cannot be created with that username.                   
    175159                        if (FrameIO.getProfilesList().contains(userData.get(AuthenticationTag.Username))) {
    176                                 MessageBay.errorMessage(Constants.ERROR_PROFILE_NAME_PREEXISTS);
     160                                MessageBay.errorMessage("A Expeditee profile with this username already exists, please choose another.");
    177161                                return;
    178162                        }
     
    180164                        // The chosen username must be a valid frameset name.
    181165                        if (!FrameIO.isValidFramesetName(userData.get(AuthenticationTag.Username))) {
    182                                 MessageBay.errorMessage(Constants.ERROR_INVALID_USERNAME);
     166                                MessageBay.errorMessage("The provided username must begin and end with a letter and contain only letters and numbers inbetween, please choose another.");
    183167                                return;
    184168                        }
     
    186170                        // The passwords provided must match
    187171                        if (userData.get(AuthenticationTag.Password).compareTo(userData.get(AuthenticationTag.PasswordAgain)) != 0) {
    188                                 MessageBay.errorMessage(Constants.ERROR_MISMATCH_PASSWORDS);
     172                                MessageBay.errorMessage("The provided passwords do not match, please fix this and try again.");
    189173                                return;
    190174                        }
     
    192176                        // The emails provided must match
    193177                        if (userData.get(AuthenticationTag.Email).compareTo(userData.get(AuthenticationTag.EmailAgain)) != 0) {
    194                                 MessageBay.errorMessage(Constants.ERROR_MISMATCH_EMAILS);
     178                                MessageBay.errorMessage("The provided emails do not match, please fix this and try again.");
    195179                                return;
    196180                        }
    197181                       
    198                         createAccount(userData);
     182                        Create.createAccount(userData);
    199183                        Authenticate.login(userData);
    200184                        AuthenticatorBrowser.Authenticated = true;
    201185                } else {
    202                         MessageBay.errorMessage(Constants.ERROR_INSUFFICIENT_INFORMATION_PROVIDED);
     186                        MessageBay.errorMessage("Please fill out all the supplied text boxes.");
    203187                }
    204188        }
     
    223207                        AuthenticatorBrowser.Authenticated = true;
    224208                } else {
    225                         MessageBay.errorMessage(Constants.ERROR_INSUFFICIENT_INFORMATION_PROVIDED);
     209                        MessageBay.errorMessage("Please fill out all the supplied text boxes.");
    226210                }
    227211        }
     
    248232               
    249233                if (!AuthenticatorBrowser.Authenticated) {
    250                         MessageBay.errorMessage(Constants.ERROR_MUST_BE_LOGGED_IN);
     234                        MessageBay.errorMessage("You must be logged in to perform this action.");
    251235                } else {
    252236                        final Optional<Map<AuthenticationTag, String>> userdata = AuthenticationTag.fetchUserData(textItems, false, AuthenticationTag.Password, AuthenticationTag.NewPassword, AuthenticationTag.NewPasswordAgain);
     
    254238                                final Map<AuthenticationTag, String> userData = userdata.get();
    255239                                if (userData.get(AuthenticationTag.NewPassword).compareTo(userData.get(AuthenticationTag.NewPasswordAgain)) != 0) {
    256                                         MessageBay.errorMessage(Constants.ERROR_MISMATCH_PASSWORDS);
     240                                        MessageBay.errorMessage("The provided passwords do not match, please fix this and try again.");
    257241                                } else {
    258242                                        userData.put(AuthenticationTag.Username, UserSettings.UserName.get());
     
    260244                                }
    261245                        } else {
    262                                 MessageBay.errorMessage(Constants.ERROR_INSUFFICIENT_INFORMATION_PROVIDED);
     246                                MessageBay.errorMessage("Please fill out all the supplied text boxes.");
    263247                        }
    264248                }
     
    267251        public static void AuthGotoAccountManagement() {
    268252                if (AuthenticatorBrowser.Authenticated) {
    269                         DisplayController.setCurrentFrame(FrameIO.LoadFrame(Constants.FRAME_MULTIUSER1), false);
    270                 } else {
    271                         DisplayController.setCurrentFrame(FrameIO.LoadFrame(Constants.FRAME_AUTHENTICATION1), false);
     253                        DisplayController.setCurrentFrame(FrameIO.LoadFrame("multiuser1"), false);
     254                } else {
     255                        DisplayController.setCurrentFrame(FrameIO.LoadFrame("authentication1"), false);
    272256                }
    273257        }
     
    284268                       
    285269                        if (toShare == null) {
    286                                 MessageBay.errorMessage(Constants.ERROR_INSUFFICIENT_INFORMATION);
     270                                MessageBay.errorMessage("Insufficient information provided to complete this action.");
    287271                                return;
    288272                        }
     
    297281         */
    298282        public static void AuthGotoColleagueSubmissionFrame() {
    299                 Frame destination = FrameIO.LoadFrame(Constants.FRAME_COLLEAGUE_SUBMISSION_FRAME);
     283                Frame destination = FrameIO.LoadFrame("authentication7");
    300284                DisplayController.setCurrentFrame(destination, true);
    301                 Collection<Item> toHide = getByData(destination, Constants.DATA_SHOW_ON_PROGRESS);
     285                Collection<Item> toHide = getByData(destination, "ShowOnProgress");
    302286                for (Item i: toHide) {
    303287                        i.setVisible(false);
     
    321305               
    322306                if (!AuthenticatorBrowser.Authenticated) {
    323                         MessageBay.errorMessage(Constants.ERROR_MUST_BE_LOGGED_IN);
     307                        MessageBay.errorMessage("You must be logged in to perform this action.");
    324308                        return;
    325309                }
     
    340324                                boolean success = submitPWColleagues(userData);
    341325                                if (success) {
    342                                         Collection<Item> toShow = getByData(currentFrame, Constants.DATA_SHOW_ON_PROGRESS);
     326                                        Collection<Item> toShow = getByData(currentFrame, "ShowOnProgress");
    343327                                        for (Item i: toShow) {
    344328                                                i.setVisible(true);
     
    383367        }
    384368       
    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 = 16;
    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                         frame.addToData("MultiuserCredentials");
    455                         Collection<Text> textItems = frame.getTextItems();
    456                         for (Text t: textItems) {
    457                                 if (t.getText().equals("Secrets")) {
    458                                         t.setPermission(new PermissionPair(UserAppliedPermission.followLinks, UserAppliedPermission.denied));
    459                                         break;
    460                                 }
    461                         }
    462                 });
    463                
    464                 // Create users profile
    465                 Frame profile = FrameIO.CreateNewProfile(username, initialSettings, notifiers);
    466                 int lastNumber = FrameIO.getLastNumber(profile.getFramesetName());
    467                 for (int i = 1; i <= lastNumber; i++) {
    468                         Frame f = FrameIO.LoadFrame(profile.getFramesetName() + i);
    469                         Text titleItem = f.getTitleItem();
    470                         if (i == 1 && titleItem != null) {
    471                                 titleItem.delete();
    472                                 f.setBackgroundColor(new Colour(1, 1, 0.39f));
    473                         }
    474                         f.setOwner(username);
    475                         f.getAllItems().stream().forEach(item -> item.setOwner(username));
    476                         f.setChanged(true);
    477                         if (f.getNumber() != AuthenticatorBrowser.CREDENTIALS_FRAME) {
    478                                 f.setEncryptionLabel(AuthenticatorBrowser.PROFILEENCRYPTIONLABEL);
    479                         }
    480                         Collection<Item> secretsLink = getByContent(f, "Secrets");
    481                         Collection<Item> publicKeyItem = getByContent(f, "PublicKey");
    482                         if (!secretsLink.isEmpty() && !publicKeyItem.isEmpty()) {
    483                                 //Then we are on credentials frame
    484                                 f.addToData("MultiuserCredentials");
    485                         }
    486                         Text backupPersonalKey = KeyList.PersonalKey.get();
    487                         Text tempPersonalKey = KeyList.PersonalKey.generateText();
    488                         tempPersonalKey.setData(personalKey);
    489                         KeyList.PersonalKey.setSetting(tempPersonalKey);
    490                         FrameIO.SaveFrame(f);
    491                         KeyList.PersonalKey.setSetting(backupPersonalKey);
    492                 }
    493                
    494                 if (AuthenticatorBrowser.CREDENTIALS_FRAME == -1) {
    495                         System.err.println("authActions::Unable to establish credentials frame for new profile frame.  Account creation failed.");
    496                         return;
    497                 }
    498                
    499                 try {
    500                         progressBar.UpdateMessage(message + "Establishing user credentials.", progress += step);
    501                 } catch (Exception e) {
    502                         e.printStackTrace();
    503                 }
    504                 DisplayController.refreshBayArea();
    505                                
    506                 // Create credentials
    507                 File credentialsDir = new File(profile.getFramesetPath() + username + "-credentials");
    508                 credentialsDir.mkdir();
    509                 //      credentials.inf file.
    510                 String credentialsPath =  credentialsDir.getAbsolutePath() + File.separator + "credentials.inf";
    511                 File credentialsFile = new File(credentialsPath);
    512                 credentialsFile.createNewFile();
    513                 FileWriter out = new FileWriter(credentialsFile);
    514                 out.write(AuthenticatorBrowser.CREDENTIALS_FRAME + ".exp");
    515                 out.flush();
    516                 out.close();
    517                 //      migrate credentials frame
    518                 Frame credentialsFrame = FrameIO.LoadFrame(username + AuthenticatorBrowser.CREDENTIALS_FRAME);
    519                 Path destinationDirectory = Paths.get(credentialsDir.getAbsolutePath());
    520                 Path destinationFile = destinationDirectory.resolve(AuthenticatorBrowser.CREDENTIALS_FRAME + ExpReader.EXTENTION);
    521                 FrameIO.migrateFrame(credentialsFrame, destinationFile);
    522 
    523                 try {
    524                         progressBar.UpdateMessage(message + "Creating Individual Space.", progress += step);
    525                 } catch (Exception e) {
    526                         e.printStackTrace();
    527                 }
    528                 DisplayController.refreshBayArea();
    529                
    530                 // Copy private resources to personal area
    531                 Path personalResources = UserSettings.PublicAndPrivateResources ? FrameIO.setupPersonalResources(username) : Paths.get(FrameIO.PARENT_FOLDER);
    532                
    533                 File contactsDir = new File(personalResources.resolve("contacts").toAbsolutePath().toString());
    534                 contactsDir.mkdir();
    535 
    536                 try {
    537                         progressBar.UpdateMessage(message + "Creating Space For Dead Drops.", progress += step);
    538                 } catch (Exception e) {
    539                         e.printStackTrace();
    540                 }
    541                 DisplayController.refreshBayArea();
    542                
    543                 File deadDropsDir = new File(personalResources.resolve("deaddrops").toAbsolutePath().toString());
    544                 deadDropsDir.mkdir();
    545                
    546                 System.err.println("**** Hardwired call in Apollo's AuthioPathManager");
    547                 AudioPathManager.activateAndScanAudioDir(); // ****
    548                
    549                 try {
    550                         progressBar.UpdateMessage(message + "Done.", 100);
    551                 } catch (Exception e) {
    552                         e.printStackTrace();
    553                 }
    554                 DisplayController.refreshBayArea();
    555                
    556         }
    557 
    558369        /*
    559370         * Function to share a specified frameset.
     
    613424                        return true;
    614425                }
    615         }
    616 
    617                
    618         private static TextSetting constructTextSetting(String tooltip, String text, String data) {
    619                 return new TextSetting(tooltip, text) {
    620                         @Override
    621                         public Text generateText() {
    622                                 Text t = new Text(text);
    623                                 t.setData(data);
    624                                 return t;
    625                         }
    626                 };
    627         }
    628 
    629         private static <T> GenericSetting<T> constructGenericSetting(Class<T> type, String tooltip, String name, T value, String frameset) {
    630                 return new GenericSetting<T>(type, tooltip, name, value) {
    631                         @Override
    632                         public Text generateRepresentation(String name, String frameset) {
    633                                 Text t = new Text(name + ": " + value);
    634                                 return t;
    635                         }
    636                 };
    637426        }
    638427       
  • trunk/src/org/expeditee/auth/AuthenticatorBrowser.java

    r1304 r1334  
    4444
    4545import org.expeditee.actions.Actions;
    46 import org.expeditee.auth.tags.Constants;
    4746import org.expeditee.core.Dimension;
    4847import org.expeditee.core.Point;
     
    182181                final File keyStoreFile = new File(FrameIO.PARENT_FOLDER + KEYSTOREFILENAME);
    183182                if (!keyStoreFile.exists()) {
    184                         keyStore.load(null, Constants.CREDENTIALS_KEYSTORE_PASSWORD.toCharArray());
     183                        keyStore.load(null, "ExpediteeAuthPassword".toCharArray());
    185184                } else {
    186185                        try (final InputStream in = new FileInputStream(FrameIO.PARENT_FOLDER + KEYSTOREFILENAME)) {
    187                                 keyStore.load(in, Constants.CREDENTIALS_KEYSTORE_PASSWORD.toCharArray());
     186                                keyStore.load(in, "ExpediteeAuthPassword".toCharArray());
    188187                        }
    189188                }
     
    324323                final KeyStore.ProtectionParameter entryPassword = new KeyStore.PasswordProtection(password.toCharArray());
    325324                keyStore.setEntry(label, entry, entryPassword);
    326                 keyStore.store(new FileOutputStream(FrameIO.PARENT_FOLDER + KEYSTOREFILENAME), Constants.CREDENTIALS_KEYSTORE_PASSWORD.toCharArray());
     325                keyStore.store(new FileOutputStream(FrameIO.PARENT_FOLDER + KEYSTOREFILENAME), "ExpediteeAuthPassword".toCharArray());
    327326        }
    328327       
     
    335334                        } else if (entry.getSecretKey().getEncoded() == TRUE) {
    336335                                keyStore.deleteEntry(email + username);
    337                                 keyStore.store(new FileOutputStream(FrameIO.PARENT_FOLDER + KEYSTOREFILENAME), Constants.CREDENTIALS_KEYSTORE_PASSWORD.toCharArray());
     336                                keyStore.store(new FileOutputStream(FrameIO.PARENT_FOLDER + KEYSTOREFILENAME), "ExpediteeAuthPassword".toCharArray());
    338337                                return true;
    339338                        } else { return false; }
     
    354353                final KeyStore.ProtectionParameter entryPassword = new KeyStore.PasswordProtection(intergalacticNumber.toCharArray());
    355354                keyStore.setEntry(email + username, entry, entryPassword);
    356                 keyStore.store(new FileOutputStream(FrameIO.PARENT_FOLDER + KEYSTOREFILENAME), Constants.CREDENTIALS_KEYSTORE_PASSWORD.toCharArray());
     355                keyStore.store(new FileOutputStream(FrameIO.PARENT_FOLDER + KEYSTOREFILENAME), "ExpediteeAuthPassword".toCharArray());
    357356               
    358357                return intergalacticNumber;
     
    392391                KeyStore.ProtectionParameter entryPassword = new KeyStore.PasswordProtection(KeyList.PersonalKey.get().getText().toCharArray());
    393392                keyStore.setEntry(username + "colleaguesRequested", entry, entryPassword);
    394                 keyStore.store(new FileOutputStream(FrameIO.PARENT_FOLDER + KEYSTOREFILENAME), Constants.CREDENTIALS_KEYSTORE_PASSWORD.toCharArray());
     393                keyStore.store(new FileOutputStream(FrameIO.PARENT_FOLDER + KEYSTOREFILENAME), "ExpediteeAuthPassword".toCharArray());
    395394        }
    396395       
     
    399398                KeyStore.ProtectionParameter entryPassword = new KeyStore.PasswordProtection(KeyList.PersonalKey.get().getText().toCharArray());
    400399                keyStore.setEntry(username + "colleaguesRequested", entry, entryPassword);
    401                 keyStore.store(new FileOutputStream(FrameIO.PARENT_FOLDER + KEYSTOREFILENAME), Constants.CREDENTIALS_KEYSTORE_PASSWORD.toCharArray());
     400                keyStore.store(new FileOutputStream(FrameIO.PARENT_FOLDER + KEYSTOREFILENAME), "ExpediteeAuthPassword".toCharArray());
    402401        }
    403402       
  • trunk/src/org/expeditee/auth/account/Authenticate.java

    r1324 r1334  
    2727import org.expeditee.auth.gui.MailBay;
    2828import org.expeditee.auth.tags.AuthenticationTag;
    29 import org.expeditee.auth.tags.Constants;
    3029import org.expeditee.gui.Browser;
    3130import org.expeditee.gui.DisplayController;
     
    119118                        }
    120119                       
    121                         Collection<Item> usernameFields = Actions.getByData(FrameIO.LoadFrame(Constants.FRAME_MULTIUSER1), "txtUsername");
     120                        Collection<Item> usernameFields = Actions.getByData(FrameIO.LoadFrame("multiuser1"), "txtUsername");
    122121                        usernameFields.forEach(usernameField -> usernameField.setText(username));
    123122                       
Note: See TracChangeset for help on using the changeset viewer.