Advertisement
Guest User

Untitled

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