Ban System PlayerLoginEvent outputs Reason null

Discussion in 'Spigot Plugin Development' started by PluginException, Mar 11, 2019.

  1. Hello SpigotMC Community,

    i have a problem with my code here, i've tested so far that i broadcasted the message on the event with the time and reason and there it works but on the ban screen it says not the remaining time rather it says that im permanently banned which isn't true and for the Reason it just outputs null.

    Code (Java):
    @EventHandler(priority = EventPriority.HIGH)
        public void onPlayerJoin(PlayerLoginEvent event) {
            if(!Main.mysql.isConnected()){
                return;
            }
           
            Player player = event.getPlayer();
            String uuid = player.getUniqueId().toString();

            if (!PlayerUUID.playerExists(player.getName())) {
                PlayerUUID.createPlayerData(player.getName(), uuid);
            }
           
            if (Tempban.playerExists(uuid)) {
                if (Tempban.getTempBanned(uuid) == 1) {
                    if (Tempban.getEnd2(uuid) == -1) {
                        event.setKickMessage("§7Du bist von unserem Netzwerk gebannt!\n\n§7Grund: §9" + Tempban.getReason(uuid) + "\n\n§7Verbleibende Zeit: §c" + Tempban.getTime(uuid) + "\n\n§7Entbannungsanträge kannst du im Forum oder im TeamSpeak stellen");
                        return;
                    }
                    if (Tempban.getEnd(uuid) == 0) {
                        Tempban.unban(uuid, 2);
                        return;
                    }

                    event.setKickMessage("§7Du bist von unserem Netzwerk gebannt!\n\n§7Grund: §9" + Tempban.getReason(uuid) + "\n\n§7Verbleibende Zeit: §c" + Tempban.getTime(uuid) + "\n\n§7Entbannungsanträge kannst du im Forum oder im TeamSpeak stellen");
                    event.setResult(Result.KICK_OTHER);
                }
            }
        }
    Code (Text):
     ?b?lSky?3?lRift ?8| ?cDu wurdest PERMANENT vom Server gebannt!

    ?eGrund: ?anull

    ?eZu unrecht gebannt? Schreibe ein Entbannungsantrag im Forum!
     
  2. Have you ever heard of if - else statements rather than using return each time?
     
    • Agree Agree x 2
  3. Show pls the Tempban class
     
  4. The returns are usefull in this case
     
  5. There's no error i think because i broadcasted the information from the same defined String and on the broadcast it works

    Code (Java):

    public class Tempban {

        public static boolean playerExists(String uuid) {
            ResultSet rs = Main.mysql.query("select * from Tempban where UUID= '" + uuid + "'");

            try {
                if (rs.next()) {
                    if (rs.getString("UUID") != null) {
                        MySQL.closeResultset(rs);
                        return true;
                    }
                }
            } catch (SQLException e) {
            }

            MySQL.closeResultset(rs);
            return false;
        }

        public static void unban(String Spielername, Integer banned) {
            Main.mysql.update("UPDATE Tempban SET BANNED= '" + banned + "' WHERE UUID= '" + Spielername + "';");
            Main.mysql.update("DELETE FROM HistoryBan WHERE UUID= '" + Spielername + "'");
        }

        public static Integer getTempBanned(String uuid) {
            ResultSet rs = Main.mysql.query("select * from Tempban where UUID= '" + uuid + "'");
            try {
                if (rs.next()) {
                    Integer i = rs.getInt("BANNED");
                    MySQL.closeResultset(rs);
                    return i;
                }
            } catch (SQLException e) {}
           
            MySQL.closeResultset(rs);
            return 2;
        }

        public static Long getEnd2(String uuid) {
            ResultSet rs = Main.mysql.query("select * from HistoryBan where UUID= '" + uuid + "'");
            try {
                if (rs.next()) {
                    long l = rs.getLong("Length");
                    MySQL.closeResultset(rs);
                    return l;
                }
            } catch (SQLException e) {}
           
            MySQL.closeResultset(rs);
            return null;
        }

        public static Long getEnd(String uuid) {
            ResultSet rs = Main.mysql.query("select * from Tempban where UUID= '" + uuid + "'");
            try {
                if (rs.next()) {
                    long l = rs.getLong("End");
                    MySQL.closeResultset(rs);
                    return l;
                }
            } catch (SQLException e) {}
           
            MySQL.closeResultset(rs);
            return null;
        }

        public static String getReason(String uuid) {
            ResultSet rs = Main.mysql.query("SELECT * from Tempban where UUID= '" + uuid + "'");
            try {
                if (rs.next()) {
                    String s = rs.getString("Reason");
                    MySQL.closeResultset(rs);
                    return s;
                }
            } catch (SQLException e) {}
           
            MySQL.closeResultset(rs);
            return null;
        }
       
        public static String getFrom(String uuid) {
            ResultSet rs = Main.mysql.query("select * from Tempban where UUID= '" + uuid + "'");
            try {
                if (rs.next()) {
                    String s = rs.getString("VON");
                    MySQL.closeResultset(rs);
                    return s;
                }
            } catch (SQLException e) {}
           
            MySQL.closeResultset(rs);
            return null;
        }

        public static Integer getPoints(String uuid) {
            ResultSet rs = Main.mysql.query("select * from Tempban where UUID= '" + uuid + "'");
            try {
                if (rs.next()) {
                    Integer i = rs.getInt("POINTS");
                    MySQL.closeResultset(rs);
                    return i;
                }
            } catch (SQLException e) {}
           
            MySQL.closeResultset(rs);
            return 0;
        }

        public static void setTempban(String Spielername, String Grund, long length, String ip, Integer points) {
            long c = System.currentTimeMillis();
            long millis = length * 1000;
            long ende = c + millis;
            Date date = java.util.Calendar.getInstance().getTime();
            SimpleDateFormat dateFormatter = new SimpleDateFormat("dd.MM.yyyy");
            String dateString = dateFormatter.format(date);

            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
            String uhrzeit = sdf.format(new Date());

            Main.mysql.update("INSERT INTO HistoryBan(UUID,Datum,Uhrzeit,Grund,Length) VALUES ('" + Spielername + "','"
                    + dateString + "', '" + uhrzeit + "','" + Grund + "','" + length + "');");
            Main.mysql.update("INSERT INTO Tempban(UUID,End,Reason,VON,POINTS,BANNED) VALUES ('" + Spielername + "','" + ende
                    + "','" + Grund + "','" + ip + "','" + points + "', '1')");

        }

        public static void setTempban2(String Spielername, String Grund, long length, String ip, Integer points, Integer banned) {
            long c = System.currentTimeMillis();
            long millis = length * 1000;
            long ende = c + millis;
            Date date = java.util.Calendar.getInstance().getTime();
            SimpleDateFormat dateFormatter = new SimpleDateFormat("dd.MM.yyyy");
            String dateString = dateFormatter.format(date);

            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
            String uhrzeit = sdf.format(new Date());

            Main.mysql.update("INSERT INTO HistoryBan(UUID,Datum,Uhrzeit,Grund,Length) VALUES ('" + Spielername + "','"
                    + dateString + "', '" + uhrzeit + "','" + Grund + "','" + length + "');");

            Main.mysql.update("UPDATE Tempban SET UUID= '" + Spielername + "' WHERE UUID= '" + Spielername + "';");
            Main.mysql.update("UPDATE Tempban SET POINTS= '" + points + "' WHERE UUID= '" + Spielername + "';");
            Main.mysql.update("UPDATE Tempban SET BANNED= '" + banned + "' WHERE UUID= '" + Spielername + "';");
            Main.mysql.update("UPDATE Tempban SET VON= '" + ip + "' WHERE UUID= '" + Spielername + "';");
            Main.mysql.update("UPDATE Tempban SET Reason= '" + Grund + "' WHERE UUID= '" + Spielername + "';");
            Main.mysql.update("UPDATE Tempban SET End= '" + ende + "' WHERE UUID= '" + Spielername + "';");
        }
       
        public static void eaBanConsole(CommandSender player, String uuid){
            long c = System.currentTimeMillis();
            long ende = getEnd(uuid);
           
            if(getEnd2(uuid) == -1){
                long length2 = 60 * 60 * 24;
                long c2 = System.currentTimeMillis();
                long millis2 = length2 * 1000;
                long ende2 = c2 + millis2;
               
                Main.mysql.update("UPDATE Tempban SET End= '" + ende2 + "' WHERE UUID= '" + uuid + "';");
                Main.mysql.update("UPDATE HistoryBan SET Length= '" + length2 + "' WHERE UUID= '" + uuid + "';");
               
                player.sendMessage(Main.main.pr + "Der Ban wurde auf §924 Stunden §averkürzt§7.");
            } else {
                long diff = ende - c;
       
                int sekunden = 0;
                int minuten = 0;
                int stunden = 0;
       
                while (diff > 1000) {
                    diff -= 1000;
                    sekunden++;
                }
                while (sekunden > 60) {
                    sekunden -= 60;
                    minuten++;
                }
       
                while (minuten > 60) {
                    minuten -= 60;
                    stunden++;
                }
               
                if(stunden > 24){
                    long length2 = 60 * 60 * 24;
                    long c2 = System.currentTimeMillis();
                    long millis2 = length2 * 1000;
                    long ende2 = c2 + millis2;
                   
                    Main.mysql.update("UPDATE Tempban SET End= '" + ende2 + "' WHERE UUID= '" + uuid + "';");
                    Main.mysql.update("UPDATE HistoryBan SET Length= '" + length2 + "' WHERE UUID= '" + uuid + "';");
                   
                    player.sendMessage(Main.main.pr + "Der Ban wurde auf §924 Stunden §averkürzt§7.");
                } else {
                    player.sendMessage(Main.main.pr + "§cDer Ban ist bereits auf unter 24 Stunden.");
                }
            }
        }

        public static void eaBan(Player player, String uuid){
            long c = System.currentTimeMillis();
            long ende = getEnd(uuid);
           
            if(getEnd2(uuid) == -1){
                long length2 = 60 * 60 * 24;
                long c2 = System.currentTimeMillis();
                long millis2 = length2 * 1000;
                long ende2 = c2 + millis2;
               
                Main.mysql.update("UPDATE Tempban SET End= '" + ende2 + "' WHERE UUID= '" + uuid + "';");
                Main.mysql.update("UPDATE HistoryBan SET Length= '" + length2 + "' WHERE UUID= '" + uuid + "';");
               
                player.sendMessage(Main.main.pr + "Der Ban wurde auf §924 Stunden §averkürzt§7.");
            } else {
                long diff = ende - c;
       
                int sekunden = 0;
                int minuten = 0;
                int stunden = 0;
       
                while (diff > 1000) {
                    diff -= 1000;
                    sekunden++;
                }
                while (sekunden > 60) {
                    sekunden -= 60;
                    minuten++;
                }
       
                while (minuten > 60) {
                    minuten -= 60;
                    stunden++;
                }
               
                if(stunden > 24){
                    long length2 = 60 * 60 * 24;
                    long c2 = System.currentTimeMillis();
                    long millis2 = length2 * 1000;
                    long ende2 = c2 + millis2;
                   
                    Main.mysql.update("UPDATE Tempban SET End= '" + ende2 + "' WHERE UUID= '" + uuid + "';");
                    Main.mysql.update("UPDATE HistoryBan SET Length= '" + length2 + "' WHERE UUID= '" + uuid + "';");
                   
                    player.sendMessage(Main.main.pr + "Der Ban wurde auf §924 Stunden §averkürzt§7.");
                } else {
                    player.sendMessage(Main.main.pr + "§cDer Ban ist bereits auf unter 24 Stunden.");
                }
            }
        }
       
        public static String getTime(String uuid) {
            long c = System.currentTimeMillis();
            long ende = getEnd(uuid);
           
            if(getEnd2(uuid) == -1){
                return "PERMANENT";
            }
           
            long diff = ende - c;

            int sekunden = 0;
            int minuten = 0;
            int stunden = 0;
            int tage = 0;

            while (diff > 1000) {
                diff -= 1000;
                sekunden++;
            }
            while (sekunden > 60) {
                sekunden -= 60;
                minuten++;
            }

            while (minuten > 60) {
                minuten -= 60;
                stunden++;
            }

            while (stunden > 24) {
                stunden -= 24;
                tage++;
            }

            if (tage <= 0 & stunden <= 0 & minuten <= 0 & sekunden <= 0) {
                unban(uuid, 2);
                return null;
            } else if (tage == 0 & stunden == 0 & minuten == 0 & sekunden == 1) {
                return sekunden + " Sekunde";
            } else if (tage == 0 & stunden == 0 & minuten == 0 & sekunden != 1) {
                return sekunden + " Sekunden";
     
    //Shortened

            }
            return null;
        }

    }
     
     
  6. return > endless spaghetti with if else and nested if statements
     
    • Agree Agree x 4
  7. Yeah but that's not the point, it just returns null, that is the problem
     
  8. While with the same exact String it out broadcast the right output
     
  9. Please can you show us your TempBan class.
     
  10. Already send it in here
     
  11. Please be aware of security a bit. Kinda surprised nobody has mentioned this yet, but your code is heavily SQL injectable which means that your entire database can be hacked through your plugin by whoever has permission to use it. More specifically, this line for example:

    I am 99% you'll be putting a command behind this, where you can enter the ban reason through the command. Whoever has permission to use the command will be able to input something malicious, which can be used to execute whatever query they want on the database. The entire database would then be at risk. Data can be deleted, false data can be inserted or editted, or even passwords could be leaked if you have them in the same database.

    Go ahead and enter a simple ' character as ban reason and watch how you'll get an internal server error.

    Please educate yourself on SQL injections and the risk of them, for your own good. Use PreparedStatements to prevent them: https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html

    On top of this, run queries async unless you want to block your main server thread and basically kill it.
     
    • Agree Agree x 2
  12. MiniDigger

    Supporter

    you silently catch exceptions, thats bad, thats why you don't know whats wrong, don't do that.

    this isn't the worst issue here tho: you execute blocking sql statements on the mainthread. this will lag your server to death.
    if I counted properly you execute like 6 sql statements for every player that joins. thats reallly bad. you want to execute your statements async and use callbacks. you also want to reduce the number of statements.
    you always "Select *" anyways, why not just get the entry from the table once, save it as a data object in memory and then do your checks and stuff.
    ontop of that, you want to look into prepared statements
     
    • Agree Agree x 2
  13. Static abuse

    Also the Boolean checks can return rs.next();
    So instead of adding those extra if statements you can put
    Code (Text):
    return rs.next();
     
  14. No i use ID's on these Commands so you can't do something like this
     
  15. So there's absolutely no user input going into that function? Even so, it's just bad practise. You should always follow best security practises even if they cannot be directly exploited. Ignorance and over-confidence is one of the biggest causes of security leaks. Would really recommend you to patch that.
     
  16. MiniDigger

    Supporter

    It's not only about security but also about speed. Prepared statements don't need to be parsed all the time by an competent rdbms
     
  17. You're right! It needs to be even SLOWER!!!
     
  18. Yeah that might be, i have to do this but it's not my issue and i want to know why its outputting null
     
  19. Listen to what they are saying. They are teaching you to

    1. Put a debugging code on your SQLException catch clause!
    So when there is a problem with your sql query you will be informed via the console.
    At least put a e.printStackTrace(); so any error that happens when you query will show up in console.
    This may be the reason you are having a null value.

    2. You should use AsyncPlayerPreLoginEvent to check for bans so this will not lag your server (this is what they mean to run your database queries async) or if you insists on running the check on PlayerLoginEvent/PlayerJoinEvent, use an async runnable.
    Why do they tell you this? Every time a player login your plugin will query for the players data.
    Story short database is not fast so your players will experience lag every time a player joins.
    Or what the others suggested load your ban list to memory on server start.

    3. They are teaching you to have proper database queries so to avoid a freak accident when suddenly you type a command argument with a random character and it deletes your whole database.

    4. When you query for the player data using "SELECT * " you can get all the data you need from the result set make
    a class and store the data there then return the data class. This way you only have to query data once every player join.

    5. I am guessing in this part. there is a problem when you are saving the data to sql or loading data from sql that's why you are getting a null value. Again put a debug code on your "SQLException" catch clause. If no error outputs in console when you do this then you can post an update here.

    6. Additional please avoid using "Main" as your main plugins class name CraftBukkit uses this and you might get confused on the imports.

    7. Learn to close your sql objects in a "finally" clause so even if your code throws an exception your code will still try to close your sql objects.

    8. your ban time calculation is way too complicated to avoid this you can do this
    Lets say you want to ban a player for 1 day
    save the current time as the start of the ban time
    then save how many days you want a player banned

    On player AsyncPlayerPreLoginEvent get the player data
    now to get the time difference

    Code (Text):

    final int banDays = <put the days a player banned>;
    final long banStartTime = <put the start time from the database>;
    final long currentTime = Calendar.getInstance().getTimeMillis();

    //get time difference
    final long timeDiff = currentTime - banStartTime;
    //convert to days
    long daysBanned = timeDiff / 1000 / 60 / 60 / 24;
    //check if the player is still banned
    if (daysBanned <= banDays) {
      return "STILL BANNED";
    }  else {
    //remove player from ban here
    //let the player in
    }

     
    now for checking if a player is permanently banned you can put the time banned to -1
    so you can check

    Code (Text):

    if (banStartTime == -1) {
       return "PERMANENT BAN";
    }
     
     
    #19 RAZERMC, Mar 15, 2019
    Last edited: Mar 15, 2019
  20. I will try to correct these things, im not home at the time so i will do it tommorow.

    Thanks for the answers
     

Share This Page