Skip to content

Commit

Permalink
Added PlaceholdersAPI support & custom placeholders
Browse files Browse the repository at this point in the history
  • Loading branch information
LielAmar committed Aug 27, 2021
1 parent af30e71 commit 0040372
Show file tree
Hide file tree
Showing 18 changed files with 465 additions and 24 deletions.
27 changes: 27 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
### Java ###
# Compiled class file
*.class

# classpath
*.classpath

# project
*.project

# iml files
*.iml

# prefs files
*.prefs

# jar files
*.jar

# target folder
target/

# .idea folder
.idea/

# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
14 changes: 13 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

<groupId>com.lielamar</groupId>
<artifactId>2fa</artifactId>
<version>1.4.4</version>
<version>1.5.0</version>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
Expand Down Expand Up @@ -118,6 +118,11 @@
<id>velocity-repo</id>
<url>https://repo.velocitypowered.com/snapshots/</url>
</repository>

<repository>
<id>placeholderapi</id>
<url>http://repo.extendedclip.com/content/repositories/placeholderapi/</url>
</repository>
</repositories>

<dependencies>
Expand Down Expand Up @@ -172,6 +177,13 @@
<scope>provided</scope>
</dependency>

<dependency>
<groupId>me.clip</groupId>
<artifactId>placeholderapi</artifactId>
<version>2.9.2</version>
<scope>provided</scope>
</dependency>


<dependency>
<groupId>${group-id.googleauth}</groupId>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
package com.lielamar.auth.bukkit;

import com.lielamar.auth.bukkit.handlers.*;
import com.lielamar.auth.bukkit.utils.ServerVersion;
import com.lielamar.auth.shared.handlers.PluginMessagingHandler;
import com.lielamar.auth.shared.storage.StorageHandler;
import com.lielamar.lielsutils.bstats.MetricsSpigot;
import com.lielamar.auth.bukkit.commands.CommandHandler;
import com.lielamar.auth.bukkit.handlers.AuthHandler;
import com.lielamar.auth.bukkit.handlers.BungeecordMessageHandler;
import com.lielamar.auth.bukkit.handlers.ConfigHandler;
import com.lielamar.auth.bukkit.handlers.MessageHandler;
import com.lielamar.auth.bukkit.listeners.DisabledEvents;
import com.lielamar.auth.bukkit.listeners.OnAuthStateChange;
import com.lielamar.auth.bukkit.listeners.OnPlayerConnection;
Expand Down Expand Up @@ -42,8 +39,11 @@ public void onEnable() {
this.setupUpdateChecker();

// Applying 2fa for online players
for(Player pl : Bukkit.getOnlinePlayers())
this.authHandler.playerJoin(pl.getUniqueId());
// We add a 5-tick-delay to ensure the permission plugin is loaded beforehand
Bukkit.getScheduler().runTaskLater(this, () -> {
for(Player pl : Bukkit.getOnlinePlayers())
this.authHandler.playerJoin(pl.getUniqueId());
}, this.configHandler.getReloadDelay());
}


Expand All @@ -52,8 +52,11 @@ private void setupDependencies() {
Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.YELLOW + "[2FA] Your server version is above or equal to 1.16.5. Using the default spigot dependency loader");
} else {
Bukkit.getServer().getConsoleSender().sendMessage(ChatColor.YELLOW + "[2FA] Your server version is below 1.16.5. Using a custom dependency loader");
new DependencyManager(this);
new DependencyHandler(this);
}

if(Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI"))
new TwoFactorAuthenticationPlaceholders(this).register();
}


Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package com.lielamar.auth.bukkit;

import com.lielamar.auth.shared.utils.TimeUtils;
import me.clip.placeholderapi.expansion.PlaceholderExpansion;
import org.bukkit.entity.Player;

public class TwoFactorAuthenticationPlaceholders extends PlaceholderExpansion {

private final TwoFactorAuthentication plugin;

public TwoFactorAuthenticationPlaceholders(TwoFactorAuthentication plugin) {
this.plugin = plugin;
}


@Override
public String getIdentifier() {
return "2FA";
}

@Override
public String getAuthor() {
return plugin.getDescription().getAuthors().get(0);
}

@Override
public String getVersion() {
return plugin.getDescription().getVersion();
}


@Override
public String onPlaceholderRequest(Player player, String identifier) {
switch(identifier.toLowerCase()) {
case "is_enabled":
return plugin.getAuthHandler().is2FAEnabled(player.getUniqueId()) ? "Enabled" : "Disabled";
case "time_since_enabled":
return TimeUtils.parseTime(System.currentTimeMillis() - plugin.getAuthHandler().getStorageHandler().getEnableDate(player.getUniqueId()));
case "key":
return plugin.getAuthHandler().getStorageHandler().getKey(player.getUniqueId());
case "is_required":
return player.hasPermission("2fa.demand") ? "Required" : "Not Required";
}

return null;
}
}
11 changes: 11 additions & 0 deletions src/main/java/com/lielamar/auth/bukkit/handlers/ConfigHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,17 @@ public void reload() {
} else
super.ipHashType = config.getString("ip-hash");

if(!config.contains("player-reload-delay")) {
config.set("player-reload-delay", super.reloadDelay);
config.addComments("player-reload-delay", new String[] {
"# How much delay should the plugin apply to loading players when the server reloads",
"# This is useful when you have multiple databases with different latencies",
"# You can use it to ensure your permissions plugin loads before the players are reloaded",
"# * It's best to set the value to 0 if you use the same storage type AND storage (server/file), because you won't have latency differences anyways"
});
} else
super.reloadDelay = config.getInt("player-reload-delay");

ConfigurationSection disabledEventsSection = config.getConfigurationSection("disabled-events");
try {
if(disabledEventsSection != null) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.lielamar.auth.bukkit;
package com.lielamar.auth.bukkit.handlers;

import com.lielamar.auth.bukkit.TwoFactorAuthentication;
import net.byteflux.libby.BukkitLibraryManager;
import net.byteflux.libby.Library;
import org.bukkit.Bukkit;
Expand All @@ -9,9 +10,9 @@
import java.io.IOException;
import java.util.Properties;

public class DependencyManager {
public class DependencyHandler {

public DependencyManager(Plugin plugin) {
public DependencyHandler(Plugin plugin) {
try {
Properties properties = new Properties();
properties.load(TwoFactorAuthentication.class.getClassLoader().getResourceAsStream("project.properties"));
Expand Down
Original file line number Diff line number Diff line change
@@ -1,23 +1,34 @@
package com.lielamar.auth.bukkit.handlers;

import com.lielamar.lielsutils.files.FileManager;
import me.clip.placeholderapi.PlaceholderAPI;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

public class MessageHandler extends com.lielamar.auth.shared.handlers.MessageHandler {

private static boolean PLACEHOLDER_API_ENABLED;

private final FileManager.Config config;

public MessageHandler(FileManager fileManager) {
PLACEHOLDER_API_ENABLED = Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI");

this.config = fileManager.getConfig(super.messagesFileName);

this.reload();
}

@Override
protected void sendRaw(Object player, final String message) {
if(player instanceof CommandSender)
((CommandSender)player).sendMessage(ChatColor.translateAlternateColorCodes('&', message));
protected void sendRaw(Object sender, String message) {
if(sender instanceof CommandSender) {
if(PLACEHOLDER_API_ENABLED && sender instanceof Player)
message = PlaceholderAPI.setPlaceholders((Player) sender, message);

((CommandSender)sender).sendMessage(ChatColor.translateAlternateColorCodes('&', message));
}
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.lielamar.auth.shared.storage.StorageHandler;
import com.warrenstrange.googleauth.GoogleAuthenticator;
import com.warrenstrange.googleauth.GoogleAuthenticatorKey;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;
Expand Down Expand Up @@ -112,6 +113,7 @@ public boolean approveKey(UUID uuid, Integer code) {
if(key != null && new GoogleAuthenticator().authorize(key, code) && (authStates.get(uuid).equals(AuthState.PENDING_SETUP) || authStates.get(uuid).equals(AuthState.DEMAND_SETUP))) {
changeState(uuid, AuthState.AUTHENTICATED);
getStorageHandler().setKey(uuid, key);
getStorageHandler().setEnableDate(uuid, System.currentTimeMillis());
pendingKeys.remove(uuid);
authentications++;
return true;
Expand All @@ -128,6 +130,7 @@ public void resetKey(UUID uuid) {
pendingKeys.remove(uuid);
changeState(uuid, AuthState.DISABLED);
getStorageHandler().removeKey(uuid);
getStorageHandler().setEnableDate(uuid, -1);
}

public boolean cancelKey(UUID uuid) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ public abstract class ConfigHandler {

protected String ipHashType = "SHA256";

protected long reloadDelay = 0;

protected Map<Class<? extends Event>, Boolean> disabledEvents = new HashMap<>();
protected List<String> whitelistedCommands = new ArrayList<>();
protected List<String> blacklistedCommands = new ArrayList<>();
Expand Down Expand Up @@ -75,6 +77,8 @@ public abstract class ConfigHandler {

public String getIpHashType() { return this.ipHashType; }

public long getReloadDelay() { return this.reloadDelay; }

public Map<Class<? extends Event>, Boolean> getDisabledEvents() { return this.disabledEvents; }
public List<String> getWhitelistedCommands() { return this.whitelistedCommands; }
public List<String> getBlacklistedCommands() { return this.blacklistedCommands; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,27 +7,27 @@ public abstract class MessageHandler {

protected final String messagesFileName = "messages.yml";

public void sendMessage(Object player, TwoFAMessages message, Pair<?, ?>... args) {
this.sendMessage(player, true, message, args);
public void sendMessage(Object sender, TwoFAMessages message, Pair<?, ?>... args) {
this.sendMessage(sender, true, message, args);
}

/**
* Sends the value of the provided {TwoFAMessage} object to the given player
*
* @param player Player to send the message to
* @param sender Sender to send the message to
* @param prefix Whether to send the prefix as well
* @param message TwoFAMessage object to send its value
* @param args Array of pairs of arguments to switch in the message
*/
public void sendMessage(Object player, boolean prefix, TwoFAMessages message, Pair<?, ?>... args) {
public void sendMessage(Object sender, boolean prefix, TwoFAMessages message, Pair<?, ?>... args) {
String raw = message.getMessage();
String rawPrefix = TwoFAMessages.PREFIX.getMessage();

if(raw != null && raw.length() > 0) {
for(Pair<?, ?> pair : args)
raw = raw.replaceAll(pair.getKey().toString(), pair.getValue().toString());

this.sendRaw(player, (prefix ? rawPrefix : "") + raw);
this.sendRaw(sender, (prefix ? rawPrefix : "") + raw);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,14 @@ public abstract class StorageHandler {
public abstract boolean hasIP(UUID uuid);



public abstract long setEnableDate(UUID uuid, long enableDate);

public abstract long getEnableDate(UUID uuid);

public abstract boolean hasEnableDate(UUID uuid);


/**
* Sets up the Storage connection of the database
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ private File createFile(UUID uuid) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("key", JSONObject.NULL);
jsonObject.put("ip", JSONObject.NULL);
jsonObject.put("enable_date", -1);
JSONUtils.write(jsonObject, new FileOutputStream(file));
}
} else {
Expand All @@ -54,6 +55,10 @@ private File createFile(UUID uuid) {
jsonObject.put("ip", JSONObject.NULL);
changed = true;
}
if(!jsonObject.has("enable_date")) {
jsonObject.put("enable_date", -1);
changed = true;
}

if(changed)
JSONUtils.write(jsonObject, new FileOutputStream(file));
Expand Down Expand Up @@ -150,4 +155,44 @@ public String getIP(UUID uuid) {
public boolean hasIP(UUID uuid) {
return getIP(uuid) != null;
}


@Override
public long setEnableDate(UUID uuid, long enableDate) {
try {
File file = getFile(uuid);
JSONObject jsonObject = JSONUtils.read(new FileInputStream(file));

if(enableDate == -1) jsonObject.put("enable_date", JSONObject.NULL);
else jsonObject.put("enable_date", enableDate);

JSONUtils.write(jsonObject, new FileOutputStream(file));

return enableDate;
} catch(IOException exception) {
exception.printStackTrace();
}

return -1;
}

@Override
public long getEnableDate(UUID uuid) {
try {
File file = getFile(uuid);
JSONObject jsonObject = JSONUtils.read(new FileInputStream(file));

if(!jsonObject.has("enable_date")) return -1;

return jsonObject.getLong("enable_date");
} catch (IOException exception) {
exception.printStackTrace();
}
return -1;
}

@Override
public boolean hasEnableDate(UUID uuid) {
return getEnableDate(uuid) != -1;
}
}
Loading

0 comments on commit 0040372

Please sign in to comment.