Advertisement
Guest User

Untitled

a guest
Jul 11th, 2017
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 12.05 KB | None | 0 0
  1. import java.io.File;
  2. import java.io.FileWriter;
  3. import java.math.BigInteger;
  4. import java.security.MessageDigest;
  5. import java.util.ArrayList;
  6. import java.util.HashMap;
  7. import java.util.List;
  8. import java.util.Map;
  9. import java.util.Scanner;
  10.  
  11. public class AuthCraft extends Plugin {
  12.  
  13.     private static String NAME = "AuthCraft";
  14.     private static int MAJOR = 1;
  15.     private static int MINOR = 0;
  16.     private static int REVISION = 0;
  17.  
  18.     private PropertiesFile properties;
  19.     /**
  20.      * The file where auths are saved to
  21.      */
  22.     private static String AUTH_FILE = "auths.db";
  23.     /**
  24.      * The users that have authenticated
  25.      */
  26.     public final List<String> authenticated = new ArrayList<String>();
  27.     /**
  28.      * The loaded auth values
  29.      */
  30.     public Map<String, String> authTable = new HashMap<String, String>();
  31.     /**
  32.      * When the last "You need to be identified to do that!" message was sent
  33.      */
  34.     public long lastAlert = 0;
  35.     /**
  36.      * The mode of the server
  37.      */
  38.     public boolean onlineMode;
  39.     /**
  40.      * If registrations are accepted while in offline mode
  41.      */
  42.     public boolean registerInOfflineMode;
  43.     private AuthCraftListener listener = null;
  44.     public boolean onlyAllowedUsersCanRegister;
  45.  
  46.     public void initialize() {
  47.         //log("Registering listeners");
  48.  
  49.         listener = new AuthCraftListener(this);
  50.  
  51.         register(PluginLoader.Hook.BLOCK_CREATED);
  52.         register(PluginLoader.Hook.BLOCK_DESTROYED);
  53.         register(PluginLoader.Hook.CHAT);
  54.         register(PluginLoader.Hook.COMMAND);
  55.         register(PluginLoader.Hook.DISCONNECT);
  56.         register(PluginLoader.Hook.LOGIN);
  57.         register(PluginLoader.Hook.PLAYER_MOVE);
  58.         register(PluginLoader.Hook.DAMAGE);
  59.         register(PluginLoader.Hook.OPEN_INVENTORY);
  60.     }
  61.  
  62.     /**
  63.      * Register a hook
  64.      *
  65.      * @param hook the hook to register
  66.      * @priority the priority to use
  67.      */
  68.     private void register(PluginLoader.Hook hook, PluginListener.Priority priority) {
  69.         //log("MineListener -> " + hook.toString());
  70.  
  71.         etc.getLoader().addListener(hook, listener, this, priority);
  72.     }
  73.  
  74.     /**
  75.      * Register a hook with default priority
  76.      *
  77.      * @param hook the hook to register
  78.      */
  79.     private void register(PluginLoader.Hook hook) {
  80.         register(hook, PluginListener.Priority.MEDIUM);
  81.     }
  82.  
  83.     /**
  84.      * Internal use - log a player in
  85.      *
  86.      * @param player
  87.      *            the player to login
  88.      */
  89.     public boolean _login(Player player) {
  90.         String pname=player.getName();
  91.         if (etc.getDataSource().doesPlayerExist(pname)) {
  92.             Player data=etc.getDataSource().getPlayer(pname);
  93.             player.setAdmin(data.isAdmin());
  94.             player.setCanModifyWorld(data.canBuild());
  95.             player.setCommands(data.getCommands());
  96.             player.setGroups(data.getGroups());
  97.             player.setIgnoreRestrictions(data.canIgnoreRestrictions());                        
  98.             //IF THE REGISTERED FEW TIME AGO, HE MIGHT NOT HAVE A BACKUP
  99.         }
  100.         player.addGroup("login");
  101.         return true;
  102.     }
  103.  
  104.     /**
  105.      * Add an auth to the valid auths table
  106.      *
  107.      * @param username
  108.      * @param password
  109.      */
  110.     public void addAuth(String username, String password) {
  111.         if (authTable.containsKey(username.toLowerCase())) {
  112.             authTable.remove(username);
  113.         }
  114.  
  115.         authTable.put(username.toLowerCase(), password);
  116.         saveAuthEntries();
  117.     }
  118.  
  119.     /**
  120.      * Validate a player's auth
  121.      *
  122.      * @param player
  123.      *            the Player to check
  124.      * @return true if the player is not authenticated. false if the player is
  125.      *         authenticated or not registered
  126.      */
  127.     public boolean checkAuth(Player player)
  128.     {
  129.         return checkAuth(player, false);
  130.     }
  131.    
  132.     public boolean checkAuth(Player player, boolean silent) {      
  133.         if (!authenticated.contains(player.getName().toLowerCase())) {
  134.             if (authTable.containsKey(player.getName().toLowerCase())) {
  135.                 if (!silent && lastAlert == 0
  136.                         || System.currentTimeMillis() - lastAlert > 1000) {
  137.                    
  138.                     player.sendMessage(Colors.Rose
  139.                             + "Wcisnij T i wpisz swoje haslo.");
  140.                     lastAlert = System.currentTimeMillis();
  141.                 }
  142.  
  143.                 return true;
  144.             } else if (onlineMode || registerInOfflineMode) {
  145.                 if (!silent && lastAlert == 0
  146.                         || System.currentTimeMillis() - lastAlert > 1000) {
  147.                     player.sendMessage(Colors.Rose
  148.                             + "Zarejestruj konto wcisniskajac T i wpisujac swoje haslo.");
  149.                     lastAlert = System.currentTimeMillis();
  150.                 }
  151.  
  152.                 return true;
  153.             }
  154.         }
  155.  
  156.         return false;
  157.     }
  158.  
  159.     /**
  160.      * Copy key vars from one Player instance to another
  161.      *
  162.      * @param player1
  163.      *            the player to copy from
  164.      * @param player2
  165.      *            the player to copy to
  166.      * @return the copied player
  167.      */
  168.     private Player copyAccountData(Player player, Player player_) {
  169.         player_.setAdmin(player.isAdmin());
  170.         player_.setCanModifyWorld(player.canModifyWorld());
  171.         player_.setCommands(player.getCommands());
  172.         player_.setGroups(player.getGroups());
  173.         player_.setIgnoreRestrictions(player.canIgnoreRestrictions());
  174.  
  175.         return player_;
  176.     }
  177.  
  178.     /**
  179.      * When the plugin is disabled the plugin will cease to function
  180.      */
  181.     @Override
  182.     public void disable() {
  183.         log(this.NAME + " - Server-side authentication disabled!");
  184.         saveAuthEntries();
  185.     }
  186.  
  187.     /**
  188.      * When the plugin is enabled (including when the server is just started)
  189.      */
  190.     @Override
  191.     public void enable() {
  192.        
  193.         setName(NAME);
  194.         log(this.NAME + " - Server-side authentication enabled.");
  195.  
  196.         properties = new PropertiesFile("server.properties");
  197.         onlineMode = properties.getBoolean("online-mode", true);
  198.         onlyAllowedUsersCanRegister = properties.getBoolean("require-register-command", false);
  199.         registerInOfflineMode = properties.getBoolean("register-offline", false);
  200.  
  201.         loadAuthEntries();
  202.         saveAuthEntries(); // create the file initially if it does not exist
  203.  
  204.         log("Loaded " + authTable.size() + " registrations");
  205.     }
  206.  
  207.     /**
  208.      * The encryption implementation to store passwords [as md5 (default)]
  209.      *
  210.      * @param string
  211.      *            the string to encrypt
  212.      * @default the encrypted string
  213.      */
  214.     public String encrypt(String string) {
  215.         try {
  216.             final MessageDigest m = MessageDigest.getInstance("MD5");
  217.             final byte[] bytes = string.getBytes();
  218.             m.update(bytes, 0, bytes.length);
  219.             final BigInteger i = new BigInteger(1, m.digest());
  220.  
  221.             return String.format("%1$032X", i).toLowerCase();
  222.         } catch (final Exception e) {
  223.         }
  224.  
  225.         return "";
  226.     }
  227.  
  228.     /**
  229.      * Load the saved auths (if there are any!)
  230.      */
  231.     private void loadAuthEntries() {
  232.         final File file = new File(AUTH_FILE);
  233.  
  234.         if (!file.exists()) {
  235.             return;
  236.         }
  237.  
  238.         Scanner reader = null;
  239.         int lineCount = 0;
  240.         try {
  241.             reader = new Scanner(file);
  242.             while (reader.hasNextLine()) {
  243.                 lineCount++;
  244.                 reader.nextLine();
  245.             }
  246.         } catch (final Exception e) {
  247.             e.printStackTrace();
  248.         } finally {
  249.             if (reader != null) {
  250.                 reader.close();
  251.             }
  252.         }
  253.         if (lineCount > 150) {
  254.             authTable = new HashMap<String, String>(lineCount + ((int) (lineCount * 0.40)));
  255.            
  256.         }
  257.  
  258.         try {
  259.             reader = new Scanner(file);
  260.             while (reader.hasNextLine()) {
  261.                 final String line = reader.nextLine();
  262.  
  263.                 if (!line.contains(":")) {
  264.                     /*
  265.                      * Invalid!
  266.                      */
  267.                     continue;
  268.                 }
  269.  
  270.                 final String[] in = line.split(":");
  271.  
  272.                 if (in.length != 2) {
  273.                     continue;
  274.                 }
  275.  
  276.                 final String username = in[0].toLowerCase();
  277.                 final String password = in[1];
  278.  
  279.                 addAuth(username, password);
  280.             }
  281.         } catch (final Exception e) {
  282.             e.printStackTrace();
  283.         } finally {
  284.             if (reader != null) {
  285.                 reader.close();
  286.             }
  287.         }
  288.     }
  289.  
  290.     /**
  291.      * Log a message
  292.      *
  293.      * @param str
  294.      *            the string to log
  295.      */
  296.     public void log(String str) {
  297.         System.out.println("[" + getName() + "] [v" + MAJOR + "." + MINOR + "."
  298.                 + REVISION + "] " + str);
  299.     }
  300.  
  301.     /**
  302.      * Get all of the inherited groups for a player
  303.      *
  304.      * @param player the player to get the inherited groups for
  305.      * @return the array of inherited groups
  306.      */
  307.     public ArrayList<String> getInherited(String group_) {
  308.         ArrayList<String> list = new ArrayList<String>();
  309.  
  310.         Group group = etc.getDataSource().getGroup(group_);
  311.  
  312.         if (group == null) {
  313.             return null;
  314.         }
  315.         if (group.Name.equals(etc.getInstance().getDefaultGroup().Name)) {
  316.             return list;
  317.         }
  318.  
  319.         for (String g : group.InheritedGroups) {
  320.             if (g.length() == 0) {
  321.                 continue;
  322.             }
  323.  
  324.             list.add(g);
  325.  
  326.             for (String _g : getInherited(g)) {
  327.                 list.add(_g);
  328.             }
  329.         }
  330.  
  331.         return list;
  332.     }
  333.  
  334.     /**
  335.      * Save the auths
  336.      */
  337.     public void saveAuthEntries() {
  338.         final File file = new File(AUTH_FILE);
  339.  
  340.         if (file.exists()) {
  341.             file.delete();
  342.         }
  343.  
  344.         FileWriter writer = null;
  345.  
  346.         try {
  347.             file.createNewFile();
  348.  
  349.             writer = new FileWriter(file);
  350.  
  351.             for (final String username : authTable.keySet()) {
  352.                 final String password = authTable.get(username);
  353.  
  354.                 writer.write(username + ":" + password + "\r\n");
  355.                 writer.flush();
  356.             }
  357.  
  358.             writer.close();
  359.         } catch (final Exception e) {
  360.             e.printStackTrace();
  361.         }
  362.  
  363.     }
  364.  
  365.     /**
  366.      * Transform a string into one char
  367.      *
  368.      * @param str
  369.      *            The string to transform
  370.      * @param chr
  371.      *            The char to transform all chars to (ie '*')
  372.      * @return the transformed string
  373.      */
  374.     public String transform(String str, char chr) {
  375.         final char[] charArray = str.toCharArray();
  376.  
  377.         for (int i = 0; i < charArray.length; i++) {
  378.             charArray[i] = '*';
  379.         }
  380.  
  381.         return new String(charArray);
  382.     }
  383.  
  384.     /**
  385.      * Update the player cache
  386.      *
  387.      * @param player
  388.      *            the player to update
  389.      */
  390.     public void updatePlayerCache(Player player) {
  391.         player.setCanModifyWorld(false); // lock them down!!
  392.         player.setIgnoreRestrictions(false);
  393.         player.setAdmin(false);
  394.         if (canRegister(player)) {
  395.             player.setCommands(new String[]{"register", "login"});
  396.         } else {
  397.             player.setCommands(new String[0]);
  398.         }
  399.         player.setGroups(new String[0]);
  400.         if (etc.getDataSource().doesPlayerExist(player.getName())) {
  401.             Player p = etc.getInstance().getDataSource().getPlayer(player.getName());
  402.             if (p.canBuild()) {
  403.                 player.setCanModifyWorld(true);
  404.                 //playerCache.put(player.getName().toLowerCase(), new InventoryBackup(player));
  405.             }
  406.         }
  407.  
  408.     }
  409.     public boolean canRegister(Player player){
  410.         return !onlyAllowedUsersCanRegister || player.canUseCommand("/register");
  411.     }
  412. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement