Advertisement
Guest User

Untitled

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