source: trunk/src/org/expeditee/auth/account/Create.java@ 1334

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

Refactoring only

File size: 10.4 KB
Line 
1package org.expeditee.auth.account;
2
3import java.io.File;
4import java.io.FileNotFoundException;
5import java.io.FileWriter;
6import java.io.IOException;
7import java.nio.file.Path;
8import java.nio.file.Paths;
9import java.security.KeyPair;
10import java.security.KeyPairGenerator;
11import java.security.KeyStoreException;
12import java.security.NoSuchAlgorithmException;
13import java.security.SecureRandom;
14import java.security.cert.CertificateException;
15import java.sql.SQLException;
16import java.util.Base64;
17import java.util.Collection;
18import java.util.HashMap;
19import java.util.Map;
20import java.util.Random;
21import java.util.function.Consumer;
22
23import javax.crypto.SecretKey;
24import javax.crypto.spec.SecretKeySpec;
25
26import org.apollo.io.AudioPathManager;
27import org.expeditee.agents.ExistingFramesetException;
28import org.expeditee.agents.InvalidFramesetNameException;
29import org.expeditee.auth.Actions;
30import org.expeditee.auth.AuthenticatorBrowser;
31import org.expeditee.auth.tags.AuthenticationTag;
32import org.expeditee.core.Colour;
33import org.expeditee.gui.DisplayController;
34import org.expeditee.gui.Frame;
35import org.expeditee.gui.FrameIO;
36import org.expeditee.gui.MessageBay;
37import org.expeditee.gui.MessageBay.Progress;
38import org.expeditee.io.ExpReader;
39import org.expeditee.items.Item;
40import org.expeditee.items.PermissionPair;
41import org.expeditee.items.Text;
42import org.expeditee.items.UserAppliedPermission;
43import org.expeditee.setting.GenericSetting;
44import org.expeditee.setting.Setting;
45import org.expeditee.setting.TextSetting;
46import org.expeditee.settings.UserSettings;
47import org.expeditee.settings.folders.FolderSettings;
48import org.expeditee.settings.identity.secrets.KeyList;
49import org.ngikm.cryptography.CryptographyConstants;
50
51public class Create implements CryptographyConstants {
52
53 /**
54 * Create a user account using the specified information in userdata. Creates and stores user keys.
55 * @param userdata Should contain username, password and email.
56 */
57 public static void createAccount(Map<AuthenticationTag, String> userdata) throws InvalidFramesetNameException, ExistingFramesetException,
58 KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, ClassNotFoundException, IOException, SQLException {
59 // Track progress
60 String message = "Creating new user account...";
61 int progress = 0;
62 int step = 16;
63
64 // Extract user details
65 String username = userdata.get(AuthenticationTag.Username);
66 String password = userdata.get(AuthenticationTag.Password);
67 String email = userdata.get(AuthenticationTag.Email);
68
69 Progress progressBar = MessageBay.displayProgress(message);
70 try {
71 progressBar.UpdateMessage(message + "Generating Keys.", progress += step);
72 } catch (Exception e) {
73 e.printStackTrace();
74 }
75 DisplayController.refreshBayArea();
76
77 // Generate keys
78 // Personal key
79 Random rand = new SecureRandom();
80 byte[] keyBytes = new byte[16];
81 rand.nextBytes(keyBytes);
82 SecretKey key = new SecretKeySpec(keyBytes, SymmetricAlgorithm);
83 AuthenticatorBrowser.getInstance().putKey(username, password, key);
84 String personalKey = Base64.getEncoder().encodeToString(key.getEncoded());
85 // Public and private keys
86 KeyPairGenerator keyGen = KeyPairGenerator.getInstance(AsymmetricAlgorithm);
87 keyGen.initialize(1024);
88 KeyPair keyPair = keyGen.generateKeyPair();
89 String publicKey = Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded());
90 String privateKey = Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded());
91
92 try {
93 progressBar.UpdateMessage(message + "Creating Profile Frameset.", progress += step);
94 } catch (Exception e) {
95 e.printStackTrace();
96 }
97 DisplayController.refreshBayArea();
98
99 // Update in memory settings
100 System.setProperty("user.name", username);
101 UserSettings.UserName.set(username);
102 UserSettings.ProfileName.set(username);
103 UserSettings.setupDefaultFolders();
104
105 // Establish the initial settings for the created user.
106 Map<String, Setting> initialSettings = new HashMap<String, Setting>();
107 initialSettings.put("settings.identity.secrets.PersonalKey", constructTextSetting("The AES key used to secure your profile frame - do not share with anyone!", "PersonalKey", personalKey));
108 initialSettings.put("settings.identity.secrets.PrivateKey", constructTextSetting("The RSA key used to decrypt things encrypted with your RSA public key - do not share with anyone!", "PrivateKey", privateKey));
109 initialSettings.put("settings.identity.PublicKey", constructTextSetting("The RSA key used to decrypt things encrypted with your RSA public key.", "PublicKey", publicKey));
110 initialSettings.put("settings.identity.Email", constructGenericSetting(String.class, "Your public-facing email address.", "Email", email, username));
111 initialSettings.put("settings.UserSettings.UserName", constructGenericSetting(String.class, "Username", "Username", username, username));
112 initialSettings.put("settings.UserSettings.ProfileName", constructGenericSetting(String.class, "Profilename", "Profilename", username, username));
113 initialSettings.put("settings.UserSettings.HomeFrame", constructGenericSetting(String.class, "The home frame", "HomeFrame", username + 1, username));
114 initialSettings.put("org.expeditee.gui.folders.FolderSettings.FrameDirs", FolderSettings.FrameDirs);
115 initialSettings.put("org.expeditee.gui.folders.FolderSettings.ImageDirs", FolderSettings.ImageDirs);
116 initialSettings.put("org.expeditee.gui.folders.FolderSettings.AudioDirs", FolderSettings.AudioDirs);
117
118 // Record the credentials frame number
119 Map<String, Consumer<Frame>> notifiers = new HashMap<String, Consumer<Frame>>();
120 notifiers.put("settings.identity", frame -> {
121 AuthenticatorBrowser.CREDENTIALS_FRAME = frame.getNumber();
122 frame.addToData("MultiuserCredentials");
123 Collection<Text> textItems = frame.getTextItems();
124 for (Text t: textItems) {
125 if (t.getText().equals("Secrets")) {
126 t.setPermission(new PermissionPair(UserAppliedPermission.followLinks, UserAppliedPermission.denied));
127 break;
128 }
129 }
130 });
131
132 // Create users profile
133 Frame profile = FrameIO.CreateNewProfile(username, initialSettings, notifiers);
134 int lastNumber = FrameIO.getLastNumber(profile.getFramesetName());
135 for (int i = 1; i <= lastNumber; i++) {
136 Frame f = FrameIO.LoadFrame(profile.getFramesetName() + i);
137 Text titleItem = f.getTitleItem();
138 if (i == 1 && titleItem != null) {
139 titleItem.delete();
140 f.setBackgroundColor(new Colour(1, 1, 0.39f));
141 }
142 f.setOwner(username);
143 f.getAllItems().stream().forEach(item -> item.setOwner(username));
144 f.setChanged(true);
145 if (f.getNumber() != AuthenticatorBrowser.CREDENTIALS_FRAME) {
146 f.setEncryptionLabel(AuthenticatorBrowser.PROFILEENCRYPTIONLABEL);
147 }
148 Collection<Item> secretsLink = Actions.getByContent(f, "Secrets");
149 Collection<Item> publicKeyItem = Actions.getByContent(f, "PublicKey");
150 if (!secretsLink.isEmpty() && !publicKeyItem.isEmpty()) {
151 //Then we are on credentials frame
152 f.addToData("MultiuserCredentials");
153 }
154 Text backupPersonalKey = KeyList.PersonalKey.get();
155 Text tempPersonalKey = KeyList.PersonalKey.generateText();
156 tempPersonalKey.setData(personalKey);
157 KeyList.PersonalKey.setSetting(tempPersonalKey);
158 FrameIO.SaveFrame(f);
159 KeyList.PersonalKey.setSetting(backupPersonalKey);
160 }
161
162 if (AuthenticatorBrowser.CREDENTIALS_FRAME == -1) {
163 System.err.println("authActions::Unable to establish credentials frame for new profile frame. Account creation failed.");
164 return;
165 }
166
167 try {
168 progressBar.UpdateMessage(message + "Establishing user credentials.", progress += step);
169 } catch (Exception e) {
170 e.printStackTrace();
171 }
172 DisplayController.refreshBayArea();
173
174 // Create credentials
175 File credentialsDir = new File(profile.getFramesetPath() + username + "-credentials");
176 credentialsDir.mkdir();
177 // credentials.inf file.
178 String credentialsPath = credentialsDir.getAbsolutePath() + File.separator + "credentials.inf";
179 File credentialsFile = new File(credentialsPath);
180 credentialsFile.createNewFile();
181 FileWriter out = new FileWriter(credentialsFile);
182 out.write(AuthenticatorBrowser.CREDENTIALS_FRAME + ".exp");
183 out.flush();
184 out.close();
185 // migrate credentials frame
186 Frame credentialsFrame = FrameIO.LoadFrame(username + AuthenticatorBrowser.CREDENTIALS_FRAME);
187 Path destinationDirectory = Paths.get(credentialsDir.getAbsolutePath());
188 Path destinationFile = destinationDirectory.resolve(AuthenticatorBrowser.CREDENTIALS_FRAME + ExpReader.EXTENTION);
189 FrameIO.migrateFrame(credentialsFrame, destinationFile);
190
191 try {
192 progressBar.UpdateMessage(message + "Creating Individual Space.", progress += step);
193 } catch (Exception e) {
194 e.printStackTrace();
195 }
196 DisplayController.refreshBayArea();
197
198 // Copy private resources to personal area
199 Path personalResources = UserSettings.PublicAndPrivateResources ? FrameIO.setupPersonalResources(username) : Paths.get(FrameIO.PARENT_FOLDER);
200
201 File contactsDir = new File(personalResources.resolve("contacts").toAbsolutePath().toString());
202 contactsDir.mkdir();
203
204 try {
205 progressBar.UpdateMessage(message + "Creating Space For Dead Drops.", progress += step);
206 } catch (Exception e) {
207 e.printStackTrace();
208 }
209 DisplayController.refreshBayArea();
210
211 File deadDropsDir = new File(personalResources.resolve("deaddrops").toAbsolutePath().toString());
212 deadDropsDir.mkdir();
213
214 System.err.println("**** Hardwired call in Apollo's AuthioPathManager");
215 AudioPathManager.activateAndScanAudioDir(); // ****
216
217 try {
218 progressBar.UpdateMessage(message + "Done.", 100);
219 } catch (Exception e) {
220 e.printStackTrace();
221 }
222 DisplayController.refreshBayArea();
223 }
224
225 private static TextSetting constructTextSetting(String tooltip, String text, String data) {
226 return new TextSetting(tooltip, text) {
227 @Override
228 public Text generateText() {
229 Text t = new Text(text);
230 t.setData(data);
231 return t;
232 }
233 };
234 }
235
236 private static <T> GenericSetting<T> constructGenericSetting(Class<T> type, String tooltip, String name, T value, String frameset) {
237 return new GenericSetting<T>(type, tooltip, name, value) {
238 @Override
239 public Text generateRepresentation(String name, String frameset) {
240 Text t = new Text(name + ": " + value);
241 return t;
242 }
243 };
244 }
245}
Note: See TracBrowser for help on using the repository browser.