source: trunk/src/org/expeditee/auth/account/Authenticate.java@ 1303

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

Moved the static field USER_NOBODY to AuthenticatorBrowser from Browser as it makes more sense there.
Added functionality to log out, equiv to closing Expeditee and starting it again.

File size: 7.6 KB
Line 
1package org.expeditee.auth.account;
2
3import java.io.File;
4import java.io.IOException;
5import java.nio.file.Path;
6import java.nio.file.Paths;
7import java.security.InvalidKeyException;
8import java.security.KeyFactory;
9import java.security.KeyStoreException;
10import java.security.NoSuchAlgorithmException;
11import java.security.PrivateKey;
12import java.security.cert.CertificateException;
13import java.security.spec.InvalidKeySpecException;
14import java.security.spec.PKCS8EncodedKeySpec;
15import java.sql.SQLException;
16import java.text.ParseException;
17import java.util.ArrayList;
18import java.util.Base64;
19import java.util.Collection;
20import java.util.List;
21import java.util.Map;
22
23import javax.crypto.BadPaddingException;
24import javax.crypto.IllegalBlockSizeException;
25import javax.crypto.NoSuchPaddingException;
26import javax.crypto.SecretKey;
27
28import org.expeditee.auth.Actions;
29import org.expeditee.auth.AuthenticatorBrowser;
30import org.expeditee.auth.Mail;
31import org.expeditee.auth.Mail.MailEntry;
32import org.expeditee.auth.gui.MailBay;
33import org.expeditee.auth.tags.AuthenticationTag;
34import org.expeditee.auth.tags.Constants;
35import org.expeditee.gui.Browser;
36import org.expeditee.gui.DisplayController;
37import org.expeditee.gui.Frame;
38import org.expeditee.gui.FrameIO;
39import org.expeditee.gui.MessageBay;
40import org.expeditee.items.Item;
41import org.expeditee.items.Text;
42import org.expeditee.settings.Settings;
43import org.expeditee.settings.UserSettings;
44import org.expeditee.settings.identity.secrets.KeyList;
45import org.ngikm.cryptography.CryptographyConstants;
46
47public class Authenticate implements CryptographyConstants {
48
49 public static AuthenticationResult login(Map<AuthenticationTag, String> userdata) {
50 String username = userdata.get(AuthenticationTag.Username);
51 String password = userdata.get(AuthenticationTag.Password);
52
53 if (username.equals(AuthenticatorBrowser.USER_NOBODY)) {
54 return AuthenticationResult.ErrorLoginNobody;
55 }
56
57 SecretKey personalKey = null;
58 try {
59 personalKey = AuthenticatorBrowser.getInstance().getSecretKey(username, password);
60 } catch (Exception e) {
61 return AuthenticationResult.ErrorLoginUsernamePasswordCombo;
62 }
63
64 UserSettings.UserName.set(username);
65 if (!username.equals(AuthenticatorBrowser.ADMINACCOUNT)) {
66 // Set the personal key to bootstrap the encrypted frame loading.
67 Text personalKeyText = KeyList.PersonalKey.generateText();
68 personalKeyText.setData(Base64.getEncoder().encodeToString(personalKey.getEncoded()));
69 KeyList.PersonalKey.setSetting(personalKeyText);
70
71 // Load in and cache the profile frame using the personal key fetched from keystore.
72 FrameIO.ClearCache();
73 Frame oneFrame = FrameIO.LoadProfile(username);
74 for (int i = 1; i <= FrameIO.getLastNumber(oneFrame.getFramesetName()); i++) {
75 Frame f = FrameIO.LoadFrame(oneFrame.getFramesetName() + i);
76 if (f != null && f.getData() != null && f.getData().contains("MultiuserCredentials")) {
77 AuthenticatorBrowser.CREDENTIALS_FRAME = f.getNumber();
78 }
79 }
80
81 // Update were we get our frames.
82 UserSettings.setupDefaultFolders();
83 MessageBay.updateFramesetLocation();
84 MailBay.disconnect();
85
86 // Parse the users profile to refresh settings.
87 Text settingsLink = new Text("settings");
88 settingsLink.setLink(oneFrame.getFramesetName() + "2");
89 Settings.parseSettings(settingsLink);
90
91 // At this point we at least login, but maybe with problems.
92 AuthenticationResult res = AuthenticationResult.SuccessLogin;
93
94 // Check mail and update last read files.
95 MailBay.clear();
96 try {
97 AuthenticatorBrowser.getInstance().loadMailDatabase();
98 Text keyItem = KeyList.PrivateKey.get();
99 if (keyItem.getData() != null) {
100 // Check mail.
101 String keyEncoded = keyItem.getData().get(0);
102 byte[] keyBytes = Base64.getDecoder().decode(keyEncoded);
103 PrivateKey key = KeyFactory.getInstance(AsymmetricAlgorithm).generatePrivate(new PKCS8EncodedKeySpec(keyBytes));
104 List<MailEntry> mailForLoggingInUser = Mail.getEntries(UserSettings.UserName.get(), key);
105 for (MailEntry mail: mailForLoggingInUser) {
106 MailBay.addMessage(mail.timestamp, mail.message, mail.message2, mail.options);
107 }
108
109 // Update last read files.
110 Path deadDropPath = Paths.get(FrameIO.DEAD_DROPS_PATH);
111 for (File connectionDir: deadDropPath.toFile().listFiles()) {
112 if (connectionDir.isDirectory()) {
113 Path deaddropforcontactPath = Paths.get(connectionDir.getAbsolutePath());
114 AuthenticatorBrowser.getInstance().updateLastReadMailTime(deaddropforcontactPath);
115 }
116 }
117 } else {
118 res.additionalInfo.add("No private key present: your communication with other Expeditee users will be limited until this is resolved.");
119 }
120 } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | ClassNotFoundException
121 | SQLException | ParseException | IOException | InvalidKeyException | NoSuchPaddingException |
122 IllegalBlockSizeException | BadPaddingException e) {
123 res.additionalInfo.add("An error occured while attempting to load in mail sent to you by other Expeditee users. See the exception for more information.");
124 e.printStackTrace();
125 } catch (InvalidKeySpecException e) {
126 res.additionalInfo.add("Stored data cannot be used to create a private key. See exception for more information.");
127 e.printStackTrace();
128 }
129
130 Collection<Item> usernameFields = Actions.getByData(FrameIO.LoadFrame(Constants.FRAME_MULTIUSER1), "txtUsername");
131 usernameFields.forEach(usernameField -> usernameField.setText(username));
132
133 Frame requestedFrame = FrameIO.LoadFrame(Browser.getStartFrame());
134 Frame homeFrame = FrameIO.LoadFrame("home1");
135 Frame choice = requestedFrame != null ? requestedFrame : homeFrame != null ? homeFrame : oneFrame;
136 DisplayController.setCurrentFrame(choice, true);
137 }
138
139 return AuthenticationResult.SuccessLogin;
140 }
141
142 public static AuthenticationResult logout() {
143 // Set user to nobody.
144 UserSettings.UserName.set(AuthenticatorBrowser.USER_NOBODY);
145
146 // Update were we get our frames.
147 UserSettings.setupDefaultFolders();
148 MessageBay.updateFramesetLocation();
149 MailBay.disconnect();
150
151 // Reset all of the settings.
152 Settings.resetAllSettings();
153
154 // Display login frame
155 Frame auth1 = FrameIO.LoadFrame("authentication1");
156 DisplayController.setCurrentFrame(auth1, true);
157
158 return AuthenticationResult.SuccessLogout;
159 }
160
161 public enum AuthenticationResult {
162
163 SuccessLogin, SuccessLogout, ErrorLoginNobody, ErrorLoginUsernamePasswordCombo;
164
165 private List<String> additionalInfo = new ArrayList<String>();
166
167 public String toString() {
168 switch (this) {
169 case SuccessLogin:
170 StringBuilder sb = new StringBuilder();
171 sb.append("Logged in as: " + UserSettings.UserName.get());
172 if (additionalInfo.isEmpty()) {
173 return sb.toString();
174 } else {
175 String nl = System.getProperty("line.separator");
176 sb.append("However: " + nl);
177 for (String info: additionalInfo) {
178 sb.append(info + nl);
179 }
180 return sb.toString();
181 }
182 case SuccessLogout:
183 return "You are now logged out of Expeditee.";
184 case ErrorLoginNobody:
185 return "You cannot log into Expeditee as the user \'nobody\'";
186 case ErrorLoginUsernamePasswordCombo:
187 return "The username + password combination was incorrect.";
188 }
189
190 String message = "Was the list of possible enum results updated without nessasary changes to thh toString() function?";
191 throw new IllegalArgumentException(message);
192 }
193 }
194}
Note: See TracBrowser for help on using the repository browser.