Guest User

Untitled

a guest
Jul 10th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.95 KB | None | 0 0
  1. package com.speljohan.rsbot.gui;
  2.  
  3. import java.awt.Component;
  4. import java.awt.GridBagConstraints;
  5. import java.awt.GridBagLayout;
  6. import java.awt.Insets;
  7. import java.awt.event.ActionEvent;
  8. import java.awt.event.ActionListener;
  9. import java.awt.event.MouseEvent;
  10. import java.awt.event.MouseListener;
  11. import java.io.BufferedReader;
  12. import java.io.BufferedWriter;
  13. import java.io.File;
  14. import java.io.FileNotFoundException;
  15. import java.io.FileReader;
  16. import java.io.FileWriter;
  17. import java.io.IOException;
  18. import java.io.UnsupportedEncodingException;
  19. import java.net.InetAddress;
  20. import java.net.NetworkInterface;
  21. import java.security.MessageDigest;
  22. import java.security.NoSuchAlgorithmException;
  23. import java.util.Map;
  24. import java.util.TreeMap;
  25.  
  26. import javax.naming.NamingException;
  27. import javax.swing.JButton;
  28. import javax.swing.JCheckBox;
  29. import javax.swing.JDialog;
  30. import javax.swing.JLabel;
  31. import javax.swing.JList;
  32. import javax.swing.JOptionPane;
  33. import javax.swing.JPanel;
  34. import javax.swing.JPasswordField;
  35. import javax.swing.JScrollPane;
  36. import javax.swing.JSpinner;
  37. import javax.swing.JTextField;
  38. import javax.swing.ListSelectionModel;
  39. import javax.swing.SpinnerNumberModel;
  40.  
  41. import com.speljohan.rsbot.util.GlobalConfiguration;
  42.  
  43. /**
  44. * This will handle the management of Accounts for the Bot.<br>
  45. * Information will be stored in a file specified by fileName.<br>
  46. * Format for accounts should be:<br>
  47. * &nbsp;&nbsp; Name:Password[:Pin] <br>
  48. * Pin may be omitted if no Pin on Account
  49. *
  50. * @author Fusion89k
  51. */
  52. // The brackets [] are there to denote optional.
  53. public class AccountManager extends JDialog implements ActionListener {
  54. private static final long serialVersionUID = 6401178388485322197L;
  55. private JList names;
  56. private GridBagConstraints c;
  57. public final static String sepChar = ":",
  58. fileName = GlobalConfiguration.Paths.getAccountsFile();
  59. private final String emptyName = "No Accounts Found";
  60. static String key;
  61. private static Map<String, String> accounts;
  62. private static AccountManager instance;
  63.  
  64. static {
  65. //try {
  66. // InetAddress address = InetAddress.getLocalHost();
  67. // NetworkInterface ni = NetworkInterface.getByInetAddress(address);
  68. // key = new String(ni.getHardwareAddress());
  69. //} catch (Exception e) {
  70. key = System.getProperty("user.name")
  71. + System.getProperty("user.language");
  72. //}
  73. try {
  74. accounts = loadAccounts();
  75. } catch (NamingException e) {
  76. e.printStackTrace();
  77. }
  78. }
  79.  
  80. /**
  81. * Allows addition of an account
  82. *
  83. * @param info
  84. * Account info in format of name:pass[:pin]
  85. */
  86. public static void addAccount(String info) throws NamingException {
  87. if (!info.contains(sepChar))
  88. throw new NamingException(info + " is not in the correct format.");
  89. String[] parts = info.split(sepChar);
  90. accounts.put(fixName(parts[0]), crypt(parts[1], true));
  91. if (parts.length > 2)
  92. accounts.put(fixName(parts[0]), crypt(parts[1], true) + sepChar
  93. + parts[2]);
  94. saveAccounts();
  95. }
  96.  
  97. /**
  98. * Encrypts/Decrypts a string using a SHA1 hash of (String) key from other
  99. * users computers
  100. *
  101. * @author Jacmob
  102. */
  103. private static String crypt(String start, boolean en) {
  104. String delim = "a";
  105. if (start == null)
  106. return null;
  107. byte[] hashedkey;
  108. byte[] password;
  109. int i;
  110. try {
  111. hashedkey = SHA1(key);
  112. } catch (NoSuchAlgorithmException e) {
  113. e.printStackTrace();
  114. return start;
  115. } catch (UnsupportedEncodingException e) {
  116. e.printStackTrace();
  117. return start;
  118. }
  119. if (en) {
  120. String end = "";
  121. password = start.getBytes();
  122. for (i = 0; i < hashedkey.length; i++) {
  123. if (i < start.length()) {
  124. end += (hashedkey[i] + password[i]) + delim;
  125. } else {
  126. end += hashedkey[i] + delim;
  127. }
  128. }
  129. return end.substring(0, end.length() - delim.length());
  130. } else {
  131. String[] temp = start.split(delim);
  132. password = new byte[temp.length];
  133. for (i = 0; i < hashedkey.length; i++) {
  134. int temp2 = Integer.parseInt(temp[i]);
  135. if (hashedkey[i] == temp2)
  136. break;
  137. else
  138. password[i] = (byte) (temp2 - hashedkey[i]);
  139. }
  140. return new String(password, 0, i);
  141. }
  142. }
  143.  
  144. /**
  145. * Will convert account files from the old format to the new format
  146. *
  147. * Old Format - key=value, key=value,[key=value,]
  148. *
  149. * New Format - name:pass[:pin]
  150. *
  151. * @return A mapping of name password/pin pairs
  152. */
  153. private static Map<String, String> fixAccounts() throws NamingException {
  154. String endResult = "";
  155. try {
  156. BufferedReader in = new BufferedReader(new FileReader(fileName));
  157. String temp;
  158. while ((temp = in.readLine()) != null) {
  159. if (temp.contains("USERNAME")) {
  160. String pass = null, name = null, pin = null;
  161. // Old Format key=value,
  162. for (String part : temp.split(",")) {
  163. // Splits Keys and Values
  164. String[] pieces = part.split("=", 2);
  165. if (pieces[0].equals("PASSWORD"))// Key
  166. pass = crypt(pieces[1], true);
  167. else if (pieces[0].equals("USERNAME"))// Key
  168. name = pieces[1];
  169. else if (pieces[0].equals("PIN"))// Key
  170. pin = pieces[1];
  171. }
  172. try {
  173. // Converts to new format name:pass[:pin]
  174. endResult += name + sepChar + pass
  175. + (pin != null ? (sepChar + pin) : "");
  176. } catch (NullPointerException e) {
  177. // Will only happen if one of the keys is not found
  178. try {
  179. return loadAccounts();
  180. } catch (NamingException e1) {
  181. e1.printStackTrace();
  182. }
  183. }
  184. endResult += System.getProperty("line.separator");
  185. }
  186. }
  187. in.close();
  188. // Writes the new format to the file
  189. BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
  190. out.append(endResult);
  191. out.close();
  192. } catch (FileNotFoundException e) {
  193. e.printStackTrace();
  194. } catch (IOException e) {
  195. e.printStackTrace();
  196. }
  197. // Reload the accounts
  198. return loadAccounts();
  199. }
  200.  
  201. /**
  202. * Capitalizes the first character and replaces spaces with underscores
  203. * Purely esthetic
  204. *
  205. * @param name
  206. * Name to fix
  207. * @return Fixed name
  208. */
  209. private static String fixName(String name) {
  210. if (name.charAt(0) > 91)
  211. name = ((char) ((int) name.charAt(0) - 32)) + name.substring(1);
  212. while (name.contains(" "))
  213. name = name.substring(0, name.indexOf(" ")) + "_"
  214. + name.substring(name.indexOf(" ") + 1);
  215. return name;
  216. }
  217.  
  218. /**
  219. * Access the list of names for loaded accounts
  220. *
  221. * @return Array of the Names
  222. */
  223. public static String[] getAccountNames() {
  224. return accounts.keySet().toArray(new String[0]);
  225. }
  226.  
  227. /**
  228. * Access the password of the given account
  229. *
  230. * @param name
  231. * Name of account to access password of
  232. * @return Unencrypted Password
  233. */
  234. public static String getPassword(String name) {
  235. String password = accounts.get(name);
  236. if (password != null && password.contains(sepChar))
  237. password = password.split(sepChar, 2)[0];
  238. return crypt(password, false);
  239. }
  240.  
  241. /**
  242. * Access the pin for the given account
  243. *
  244. * @param name
  245. * Name of the account
  246. * @return Pin or -1 if no pin
  247. */
  248. public static String getPin(String name) {
  249. String all = accounts.get(name);
  250. if (all.contains(sepChar))
  251. return all.split(sepChar, 2)[1];
  252. return "-1";
  253. }
  254.  
  255. /**
  256. * Loads the accounts from the file
  257. */
  258. private static Map<String, String> loadAccounts() throws NamingException {
  259. TreeMap<String, String> accounts = new TreeMap<String, String>();
  260. File accountFile = new File(fileName);
  261. if (accountFile.exists()) {
  262. try {
  263. BufferedReader in = new BufferedReader(new FileReader(
  264. accountFile));
  265. String temp;// Used to store the lines from the file
  266. while ((temp = in.readLine()) != null) {
  267. if (temp.isEmpty())
  268. continue;
  269. // Means that it is in old format
  270. if (temp.contains("USERNAME"))
  271. return fixAccounts();
  272. // If for some reason the format is not as expected
  273. if (!temp.contains(sepChar))
  274. throw new NamingException("Invliad Storage of: " + temp);
  275. String[] parts = temp.split(sepChar, 2);
  276. for (String s : parts)
  277. if (s.isEmpty())
  278. throw new NamingException("Invliad Storage of: "
  279. + temp);
  280. // Formats the name
  281. parts[0] = fixName(parts[0]);
  282. // Checks Pin Validity
  283. try {
  284. if (parts.length > 2
  285. && (parts[2].length() != 4 || Integer
  286. .parseInt(parts[2]) >= 0))
  287. throw new NamingException("Invalid Pin: "
  288. + parts[2] + " On Account: " + parts[0]);
  289. } catch (NumberFormatException e) {
  290. throw new NamingException("Invalid Pin: " + parts[2]
  291. + " On Account: " + parts[0]);
  292. }
  293. accounts.put(parts[0], parts[1]);
  294. }
  295. in.close();
  296. } catch (FileNotFoundException e) {// From File Loading
  297. e.printStackTrace();
  298. } catch (IOException e) {// From Reader traversal
  299. e.printStackTrace();
  300. }
  301. }
  302. return accounts;
  303. }
  304.  
  305. /**
  306. * Writes the accounts to the file
  307. */
  308. private static void saveAccounts() {
  309. File accountFile = new File(fileName);
  310. try {
  311. BufferedWriter out = new BufferedWriter(new FileWriter(accountFile));
  312. for (String s : accounts.keySet()) {
  313. if (accounts.get(s).isEmpty())
  314. continue;
  315. out.append(s + sepChar + accounts.get(s));
  316. out.newLine();
  317. }
  318. out.close();
  319. } catch (IOException e) {
  320. e.printStackTrace();
  321. }
  322. }
  323.  
  324. /**
  325. * Returns SHA1 hash of a String.
  326. */
  327. private static byte[] SHA1(String in) throws NoSuchAlgorithmException,
  328. UnsupportedEncodingException {
  329. MessageDigest md;
  330. md = MessageDigest.getInstance("SHA-1");
  331. byte[] sha1hash = new byte[40];
  332. md.update(in.getBytes("iso-8859-1"), 0, in.length());
  333. sha1hash = md.digest();
  334. return sha1hash;
  335. }
  336.  
  337. private AccountManager() {
  338. super(BotGUI.getFrames()[0], "Account Manager", true);
  339. if (accounts.size() < 1)
  340. accounts.put(emptyName, "");
  341. }
  342.  
  343. /**
  344. * Enables AccountManager to be a Singleton
  345. *
  346. * @return The instance of the AccountManager
  347. */
  348. public static AccountManager getInstance() {
  349. if (instance == null)
  350. return (instance = new AccountManager());
  351. else
  352. return instance;
  353. }
  354.  
  355. /**
  356. * Controls all of the button and checkBox actions of the program
  357. */
  358. public void actionPerformed(ActionEvent event) {
  359. JDialog parentFrame;
  360. Component comp = ((Component) event.getSource()).getParent();
  361. while (!(comp instanceof JDialog))
  362. comp = comp.getParent();
  363. parentFrame = (JDialog) comp;
  364. if (event.getSource() instanceof JButton) {
  365. switch (((JButton) event.getSource()).getText().charAt(0)) {
  366. case 'A':// Add Accounts
  367. if (event.getActionCommand().contains("dd"))
  368. addAccount();
  369. else {// Update the List with the new Account
  370. JPanel pane = (JPanel) ((JButton) event.getSource())
  371. .getParent();
  372. String name = null, pass = null, pin = "";
  373. for (Component c : pane.getComponents()) {
  374. if (c instanceof JPasswordField)
  375. pass = ((JTextField) c).getText();
  376. else if (c instanceof JTextField)
  377. name = ((JTextField) c).getText();
  378. else if (c instanceof JSpinner)
  379. pin += ((JSpinner) c).getValue();
  380. }
  381. if (name.isEmpty() || pass.isEmpty()) {
  382. JOptionPane.showMessageDialog(null, "Empty Fields");
  383. return;
  384. }
  385. accounts.put(fixName(name), crypt(pass, true)
  386. + (pin.isEmpty() ? "" : sepChar + pin));
  387. refreshList();
  388. names.validate();
  389. parentFrame.dispose();
  390. }
  391. break;
  392. case 'D':// Delete Accounts
  393. if (accounts.get(names.getSelectedValue()).isEmpty())
  394. return;
  395. int yes = JOptionPane.showConfirmDialog(this,
  396. "Are you sure you want to delete "
  397. + names.getSelectedValue() + "?", "Delete",
  398. JOptionPane.YES_NO_OPTION);
  399. if (yes == 0) {
  400. accounts.remove(names.getSelectedValue());
  401. refreshList();
  402. names.validate();
  403. }
  404. break;
  405. case 'S':// Save Accounts
  406. saveAccounts();
  407. break;
  408. }
  409. } else if (event.getSource() instanceof JCheckBox) {
  410. // CheckBox for Pins add and remove JSpinners
  411. JCheckBox jcb = ((JCheckBox) event.getSource());
  412. if (jcb.isSelected()) {
  413. // Add Spinners
  414. c = new GridBagConstraints();
  415. c.gridy = 2;
  416. c.gridx = 1;
  417. c.weightx = 1;
  418. c.insets = new Insets(0, 0, 5, 5);
  419. JSpinner[] spins = new JSpinner[4];
  420. for (int i = 0; i < spins.length; i++) {
  421. spins[i] = new JSpinner(new SpinnerNumberModel(0, 0, 9, 1));
  422. jcb.getParent().add(spins[i], c);
  423. c.gridx = GridBagConstraints.RELATIVE;
  424. }
  425. parentFrame.pack();
  426. } else {
  427. // Remove Spinners
  428. for (Component c : jcb.getParent().getComponents())
  429. if (c instanceof JSpinner)
  430. jcb.getParent().remove(c);
  431. parentFrame.validate();
  432. }
  433. }
  434. }
  435.  
  436. /**
  437. * Gets the necessary information from the user to make a new account
  438. */
  439. private void addAccount() {
  440. JDialog addFrame = new JDialog(this, "New", true);
  441. JPanel pane = new JPanel(new GridBagLayout());
  442. c = new GridBagConstraints();
  443. JTextField userName = new JTextField(8);
  444. JPasswordField userPass = new JPasswordField(8);
  445. userPass.setEchoChar('*');
  446. c.gridwidth = 2;
  447. c.fill = GridBagConstraints.HORIZONTAL;
  448. c.insets = new Insets(5, 5, 0, 7);
  449. pane.add(new JLabel("User Name: ", JLabel.CENTER), c);
  450. c.gridx = GridBagConstraints.RELATIVE;
  451. c.gridwidth = 3;
  452. c.insets = new Insets(5, 0, 0, 5);
  453. pane.add(userName, c);
  454. c.insets = new Insets(5, 5, 5, 7);
  455. c.gridwidth = 2;
  456. c.gridx = 0;
  457. c.gridy = 1;
  458. pane.add(new JLabel("Password: ", JLabel.CENTER), c);
  459. c.insets = new Insets(5, 0, 5, 5);
  460. c.gridwidth = 3;
  461. c.gridx = GridBagConstraints.RELATIVE;
  462. pane.add(userPass, c);
  463. JCheckBox pinCheck = new JCheckBox("Pin");
  464. pinCheck.addActionListener(this);
  465. c = new GridBagConstraints();
  466. c.gridy = 2;
  467. c.insets = new Insets(0, 5, 5, 5);
  468. pane.add(pinCheck, c);
  469.  
  470. JButton save = new JButton("Add");
  471. save.setActionCommand("Update");
  472. save.addActionListener(this);
  473. c.gridy = 3;
  474. c.gridwidth = GridBagConstraints.REMAINDER;
  475. pane.add(save, c);
  476.  
  477. addFrame.setResizable(false);
  478. addFrame.add(pane);
  479. addFrame.pack();
  480. addFrame.setLocationRelativeTo(this);
  481. addFrame.setVisible(true);
  482. }
  483.  
  484. /**
  485. * Creates and Displays the main GUI
  486. *
  487. * This GUI has the list and the main buttons
  488. */
  489. public void showGUI() {
  490. getContentPane().removeAll();
  491. c = new GridBagConstraints();
  492. // Main Panel with everything
  493. JPanel pane = new JPanel(new GridBagLayout());
  494. // Makes the List
  495. names = new JList(accounts.keySet().toArray(new String[0]));
  496. // Only one selection at a time
  497. names.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
  498. // Will display the password and pin when double clicked or right
  499. // clicked
  500. names.addMouseListener(new MouseListener() {
  501. public void mouseClicked(MouseEvent click) {
  502. if (click.getClickCount() > 1
  503. || click.getButton() == MouseEvent.BUTTON3) {
  504. String clicked = accounts
  505. .get(((JList) click.getComponent())
  506. .getSelectedValue());
  507. if (clicked.isEmpty())
  508. return;
  509. String pass = clicked.contains(sepChar) ? clicked
  510. .substring(0, clicked.indexOf(sepChar)) : clicked;
  511. pass = crypt(pass, false);
  512. String info = "Password: " + pass;
  513. if (clicked.contains(sepChar)) {
  514. info += "\nPin: "
  515. + clicked.substring(
  516. clicked.indexOf(sepChar) + 1, clicked
  517. .length());
  518. }
  519. JOptionPane.showMessageDialog(null, info);
  520. }
  521. }
  522.  
  523. public void mouseEntered(MouseEvent click) {
  524. }
  525.  
  526. public void mouseExited(MouseEvent click) {
  527. }
  528.  
  529. public void mousePressed(MouseEvent click) {
  530. }
  531.  
  532. public void mouseReleased(MouseEvent click) {
  533. }
  534. });
  535.  
  536. // Enables scrolling through the List
  537. JScrollPane scroll = new JScrollPane(names);
  538.  
  539. JButton add = new JButton("Add");// Button 1
  540. JButton del = new JButton("Delete");// Button 2
  541. JButton save = new JButton("Save");// Button 3
  542.  
  543. add.addActionListener(this);
  544. del.addActionListener(this);
  545. save.addActionListener(this);
  546. // Positions Everything Correctly on the panel
  547. c.gridy = 0;
  548. c.gridwidth = GridBagConstraints.REMAINDER;
  549. c.fill = GridBagConstraints.BOTH;
  550. pane.add(scroll, c);
  551. c.gridwidth = 1;
  552. c.gridy = 1;
  553. c.gridx = 0;
  554. c.fill = GridBagConstraints.NONE;
  555. c.insets = new Insets(5, 5, 5, 5);
  556. c.anchor = GridBagConstraints.CENTER;
  557. pane.add(add, c);
  558. c.gridx = GridBagConstraints.RELATIVE;
  559. pane.add(del, c);
  560. pane.add(save, c);
  561. names.setSelectedIndex(0);
  562. add(pane);
  563. pack();
  564. setLocationRelativeTo(getOwner());
  565. setVisible(true);
  566. setResizable(false);
  567. }
  568.  
  569. /**
  570. * Resets the Model for the List to reflect changes made to the accounts Map
  571. */
  572. private void refreshList() {
  573. if (accounts.keySet().size() > 1
  574. && accounts.keySet().contains(emptyName))
  575. accounts.remove(emptyName);
  576. else if (accounts.keySet().size() < 1)
  577. accounts.put(emptyName, "");
  578. names.setListData(accounts.keySet().toArray(new String[0]));
  579. names.getParent().validate();
  580. }
  581. }
Add Comment
Please, Sign In to add comment