Advertisement
Guest User

Untitled

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