reupload files

This commit is contained in:
HaHaWTH
2023-07-11 20:45:01 +08:00
parent b014da245d
commit 7e49e26735
465 changed files with 93823 additions and 0 deletions
@@ -0,0 +1,166 @@
package fr.xephi.authme.permission;
/**
* AuthMe admin command permissions.
*/
public enum AdminPermission implements PermissionNode {
/**
* Administrator command to register a new user.
*/
REGISTER("authme.admin.register"),
/**
* Administrator command to unregister an existing user.
*/
UNREGISTER("authme.admin.unregister"),
/**
* Administrator command to force-login an existing user.
*/
FORCE_LOGIN("authme.admin.forcelogin"),
/**
* Administrator command to change the password of a user.
*/
CHANGE_PASSWORD("authme.admin.changepassword"),
/**
* Administrator command to see the last login date and time of a user.
*/
LAST_LOGIN("authme.admin.lastlogin"),
/**
* Administrator command to see all accounts associated with a user.
*/
ACCOUNTS("authme.admin.accounts"),
/**
* Administrator command to get the email address of a user, if set.
*/
GET_EMAIL("authme.admin.getemail"),
/**
* Administrator command to set or change the email address of a user.
*/
CHANGE_EMAIL("authme.admin.changemail"),
/**
* Administrator command to see whether a player has enabled two-factor authentication.
*/
VIEW_TOTP_STATUS("authme.admin.totpviewstatus"),
/**
* Administrator command to disable the two-factor auth of a user.
*/
DISABLE_TOTP("authme.admin.totpdisable"),
/**
* Administrator command to get the last known IP of a user.
*/
GET_IP("authme.admin.getip"),
/**
* Administrator command to see the last recently logged in players.
*/
SEE_RECENT_PLAYERS("authme.admin.seerecent"),
/**
* Administrator command to teleport to the AuthMe spawn.
*/
SPAWN("authme.admin.spawn"),
/**
* Administrator command to set the AuthMe spawn.
*/
SET_SPAWN("authme.admin.setspawn"),
/**
* Administrator command to teleport to the first AuthMe spawn.
*/
FIRST_SPAWN("authme.admin.firstspawn"),
/**
* Administrator command to set the first AuthMe spawn.
*/
SET_FIRST_SPAWN("authme.admin.setfirstspawn"),
/**
* Administrator command to purge old user data.
*/
PURGE("authme.admin.purge"),
/**
* Administrator command to purge the last position of a user.
*/
PURGE_LAST_POSITION("authme.admin.purgelastpos"),
/**
* Administrator command to purge all data associated with banned players.
*/
PURGE_BANNED_PLAYERS("authme.admin.purgebannedplayers"),
/**
* Administrator command to purge a given player.
*/
PURGE_PLAYER("authme.admin.purgeplayer"),
/**
* Administrator command to toggle the AntiBot protection status.
*/
SWITCH_ANTIBOT("authme.admin.switchantibot"),
/**
* Administrator command to convert old or other data to AuthMe data.
*/
CONVERTER("authme.admin.converter"),
/**
* Administrator command to reload the plugin configuration.
*/
RELOAD("authme.admin.reload"),
/**
* Permission to see Antibot messages.
*/
ANTIBOT_MESSAGES("authme.admin.antibotmessages"),
/**
* Permission to use the update messages command.
*/
UPDATE_MESSAGES("authme.admin.updatemessages"),
/**
* Permission to see the other accounts of the players that log in.
*/
SEE_OTHER_ACCOUNTS("authme.admin.seeotheraccounts"),
/**
* Allows to use the backup command.
*/
BACKUP("authme.admin.backup");
/**
* The permission node.
*/
private String node;
/**
* Constructor.
*
* @param node Permission node.
*/
AdminPermission(String node) {
this.node = node;
}
@Override
public String getNode() {
return node;
}
@Override
public DefaultPermission getDefaultPermission() {
return DefaultPermission.OP_ONLY;
}
}
@@ -0,0 +1,61 @@
package fr.xephi.authme.permission;
/**
* Permissions for the debug sections (/authme debug).
*/
public enum DebugSectionPermissions implements PermissionNode {
/** General permission to use the /authme debug command. */
DEBUG_COMMAND("authme.debug.command"),
/** Permission to use the country lookup section. */
COUNTRY_LOOKUP("authme.debug.country"),
/** Permission to use the stats section. */
DATA_STATISTICS("authme.debug.stats"),
/** Permission to use the permission checker. */
HAS_PERMISSION_CHECK("authme.debug.perm"),
/** Permission to use sample validation. */
INPUT_VALIDATOR("authme.debug.valid"),
/** Permission to use the limbo data viewer. */
LIMBO_PLAYER_VIEWER("authme.debug.limbo"),
/** Permission to view permission groups. */
PERM_GROUPS("authme.debug.group"),
/** Permission to view data from the database. */
PLAYER_AUTH_VIEWER("authme.debug.db"),
/** Permission to change nullable status of MySQL columns. */
MYSQL_DEFAULT_CHANGER("authme.debug.mysqldef"),
/** Permission to view spawn information. */
SPAWN_LOCATION("authme.debug.spawn"),
/** Permission to use the test email sender. */
TEST_EMAIL("authme.debug.mail");
private final String node;
/**
* Constructor.
*
* @param node the permission node
*/
DebugSectionPermissions(String node) {
this.node = node;
}
@Override
public String getNode() {
return node;
}
@Override
public DefaultPermission getDefaultPermission() {
return DefaultPermission.OP_ONLY;
}
}
@@ -0,0 +1,42 @@
package fr.xephi.authme.permission;
import org.bukkit.permissions.ServerOperator;
/**
* The default permission to fall back to if there is no support for permission nodes.
*/
public enum DefaultPermission {
/** No one has permission. */
NOT_ALLOWED {
@Override
public boolean evaluate(ServerOperator sender) {
return false;
}
},
/** Only players with OP status have permission. */
OP_ONLY {
@Override
public boolean evaluate(ServerOperator sender) {
return sender != null && sender.isOp();
}
},
/** Everyone is granted permission. */
ALLOWED {
@Override
public boolean evaluate(ServerOperator sender) {
return true;
}
};
/**
* Evaluates whether permission is granted to the sender or not.
*
* @param sender the sender to process
* @return true if the sender has permission, false otherwise
*/
public abstract boolean evaluate(ServerOperator sender);
}
@@ -0,0 +1,21 @@
package fr.xephi.authme.permission;
/**
* Common interface for AuthMe permission nodes.
*/
public interface PermissionNode {
/**
* Return the node of the permission, e.g. "authme.player.unregister".
*
* @return The name of the permission node
*/
String getNode();
/**
* Return the default permission for this node, e.g. "OP_ONLY"
*
* @return The default level of permission
*/
DefaultPermission getDefaultPermission();
}
@@ -0,0 +1,466 @@
package fr.xephi.authme.permission;
import com.google.common.annotations.VisibleForTesting;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.data.limbo.UserGroup;
import fr.xephi.authme.initialization.Reloadable;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.permission.handlers.LuckPermsHandler;
import fr.xephi.authme.permission.handlers.PermissionHandler;
import fr.xephi.authme.permission.handlers.PermissionHandlerException;
import fr.xephi.authme.permission.handlers.PermissionLoadUserException;
import fr.xephi.authme.permission.handlers.PermissionsExHandler;
import fr.xephi.authme.permission.handlers.VaultHandler;
import fr.xephi.authme.permission.handlers.ZPermissionsHandler;
import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.settings.properties.PluginSettings;
import fr.xephi.authme.util.StringUtils;
import org.bukkit.OfflinePlayer;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import java.util.Collection;
import java.util.Collections;
import java.util.UUID;
/**
* PermissionsManager.
* <p>
* A permissions manager, to manage and use various permissions systems.
* This manager supports dynamic plugin hooking and various other features.
* <p>
* Written by Tim Visée.
*
* @author Tim Visée, http://timvisee.com
* @version 0.3
*/
public class PermissionsManager implements Reloadable {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(PermissionsManager.class);
private final Server server;
private final PluginManager pluginManager;
private final Settings settings;
/**
* The permission handler that is currently in use.
* Null if no permission system is hooked.
*/
private PermissionHandler handler = null;
@Inject
PermissionsManager(Server server, PluginManager pluginManager, Settings settings) {
this.server = server;
this.pluginManager = pluginManager;
this.settings = settings;
}
/**
* Check if the permissions manager is currently hooked into any of the supported permissions systems.
*
* @return False if there isn't any permissions system used.
*/
public boolean isEnabled() {
return handler != null;
}
/**
* Setup and hook into the permissions systems.
*/
@PostConstruct
@VisibleForTesting
void setup() {
if (settings.getProperty(PluginSettings.FORCE_VAULT_HOOK)) {
try {
PermissionHandler handler = createPermissionHandler(PermissionsSystemType.VAULT);
if (handler != null) {
// Show a success message and return
this.handler = handler;
logger.info("Hooked into " + PermissionsSystemType.VAULT.getDisplayName() + "!");
return;
}
} catch (PermissionHandlerException e) {
logger.logException("Failed to create Vault hook (forced):", e);
}
} else {
// Loop through all the available permissions system types
for (PermissionsSystemType type : PermissionsSystemType.values()) {
try {
PermissionHandler handler = createPermissionHandler(type);
if (handler != null) {
// Show a success message and return
this.handler = handler;
logger.info("Hooked into " + type.getDisplayName() + "!");
return;
}
} catch (Exception ex) {
// An error occurred, show a warning message
logger.logException("Error while hooking into " + type.getDisplayName(), ex);
}
}
}
// No recognized permissions system found, show a message and return
logger.info("No supported permissions system found! Permissions are disabled!");
}
/**
* Creates a permission handler for the provided permission systems if possible.
*
* @param type the permission systems type for which to create a corresponding permission handler
*
* @return the permission handler, or {@code null} if not possible
*
* @throws PermissionHandlerException during initialization of the permission handler
*/
private PermissionHandler createPermissionHandler(PermissionsSystemType type) throws PermissionHandlerException {
// Try to find the plugin for the current permissions system
Plugin plugin = pluginManager.getPlugin(type.getPluginName());
if (plugin == null) {
return null;
}
// Make sure the plugin is enabled before hooking
if (!plugin.isEnabled()) {
logger.info("Not hooking into " + type.getDisplayName() + " because it's disabled!");
return null;
}
switch (type) {
case LUCK_PERMS:
return new LuckPermsHandler();
case PERMISSIONS_EX:
return new PermissionsExHandler();
case Z_PERMISSIONS:
return new ZPermissionsHandler();
case VAULT:
return new VaultHandler(server);
default:
throw new IllegalStateException("Unhandled permission type '" + type + "'");
}
}
/**
* Break the hook with all permission systems.
*/
private void unhook() {
// Reset the current used permissions system
this.handler = null;
// Print a status message to the console
logger.info("Unhooked from Permissions!");
}
/**
* Reload the permissions manager, and re-hook all permission plugins.
*/
@Override
public void reload() {
// Unhook all permission plugins
unhook();
// Set up the permissions manager again
setup();
}
/**
* Method called when a plugin is being enabled.
*
* @param pluginName The name of the plugin being enabled.
*/
public void onPluginEnable(String pluginName) {
// Check if any known permissions system is enabling
if (PermissionsSystemType.isPermissionSystem(pluginName)) {
logger.info(pluginName + " plugin enabled, dynamically updating permissions hooks!");
setup();
}
}
/**
* Method called when a plugin is being disabled.
*
* @param pluginName The name of the plugin being disabled.
*/
public void onPluginDisable(String pluginName) {
// Check if any known permission system is being disabled
if (PermissionsSystemType.isPermissionSystem(pluginName)) {
logger.info(pluginName + " plugin disabled, updating hooks!");
setup();
}
}
/**
* Return the permissions system that is hooked into.
*
* @return The permissions system, or null.
*/
public PermissionsSystemType getPermissionSystem() {
return isEnabled() ? handler.getPermissionSystem() : null;
}
/**
* Check if the command sender has permission for the given permissions node. If no permissions system is used or
* if the sender is not a player (e.g. console user), the player has to be OP in order to have the permission.
*
* @param sender The command sender.
* @param permissionNode The permissions node to verify.
*
* @return True if the sender has the permission, false otherwise.
*/
public boolean hasPermission(CommandSender sender, PermissionNode permissionNode) {
// Check if the permission node is null
if (permissionNode == null) {
return true;
}
// Return default if sender is not a player or no permission system is in use
if (!(sender instanceof Player) || !isEnabled()) {
return permissionNode.getDefaultPermission().evaluate(sender);
}
Player player = (Player) sender;
return player.hasPermission(permissionNode.getNode());
}
/**
* Check if a player has permission for the given permission node. This is for offline player checks.
* If no permissions system is used, then the player will not have permission.
*
* @param player The offline player
* @param permissionNode The permission node to verify
*
* @return true if the player has permission, false otherwise
*/
public boolean hasPermissionOffline(OfflinePlayer player, PermissionNode permissionNode) {
// Check if the permission node is null
if (permissionNode == null) {
return true;
}
if (!isEnabled()) {
return permissionNode.getDefaultPermission().evaluate(player);
}
return handler.hasPermissionOffline(player.getName(), permissionNode);
}
/**
* Check whether the offline player with the given name has permission for the given permission node.
* This method is used as a last resort when nothing besides the name is known.
*
* @param name The name of the player
* @param permissionNode The permission node to verify
*
* @return true if the player has permission, false otherwise
*/
public boolean hasPermissionOffline(String name, PermissionNode permissionNode) {
if (permissionNode == null) {
return true;
}
if (!isEnabled()) {
return permissionNode.getDefaultPermission().evaluate(null);
}
return handler.hasPermissionOffline(name, permissionNode);
}
/**
* Check whether the current permissions system has group support.
* If no permissions system is hooked, false will be returned.
*
* @return True if the current permissions system supports groups, false otherwise.
*/
public boolean hasGroupSupport() {
return isEnabled() && handler.hasGroupSupport();
}
/**
* Get the permission groups of a player, if available.
*
* @param player The player.
*
* @return Permission groups, or an empty collection if this feature is not supported.
*/
public Collection<UserGroup> getGroups(OfflinePlayer player) {
return isEnabled() ? handler.getGroups(player) : Collections.emptyList();
}
/**
* Get the primary group of a player, if available.
*
* @param player The player.
*
* @return The name of the primary permission group. Or null.
*/
public UserGroup getPrimaryGroup(OfflinePlayer player) {
return isEnabled() ? handler.getPrimaryGroup(player) : null;
}
/**
* Check whether the player is in the specified group.
*
* @param player The player.
* @param groupName The group name.
*
* @return True if the player is in the specified group, false otherwise.
* False is also returned if groups aren't supported by the used permissions system.
*/
public boolean isInGroup(OfflinePlayer player, UserGroup groupName) {
return isEnabled() && handler.isInGroup(player, groupName);
}
/**
* Add the permission group of a player, if supported.
*
* @param player The player
* @param groupName The name of the group.
*
* @return True if succeed, false otherwise.
* False is also returned if this feature isn't supported for the current permissions system.
*/
public boolean addGroup(OfflinePlayer player, UserGroup groupName) {
if (!isEnabled() || StringUtils.isBlank(groupName.getGroupName())) {
return false;
}
return handler.addToGroup(player, groupName);
}
/**
* Add the permission groups of a player, if supported.
*
* @param player The player
* @param groupNames The name of the groups to add.
*
* @return True if at least one group was added, false otherwise.
* False is also returned if this feature isn't supported for the current permissions system.
*/
public boolean addGroups(OfflinePlayer player, Collection<UserGroup> groupNames) {
// If no permissions system is used, return false
if (!isEnabled()) {
return false;
}
// Add each group to the user
boolean result = false;
for (UserGroup group : groupNames) {
if (!group.getGroupName().isEmpty()) {
result |= handler.addToGroup(player, group);
}
}
// Return the result
return result;
}
/**
* Remove the permission group of a player, if supported.
*
* @param player The player
* @param group The name of the group.
*
* @return True if succeed, false otherwise.
* False is also returned if this feature isn't supported for the current permissions system.
*/
public boolean removeGroup(OfflinePlayer player, UserGroup group) {
return isEnabled() && handler.removeFromGroup(player, group);
}
/**
* Remove the permission groups of a player, if supported.
*
* @param player The player
* @param groupNames The name of the groups to remove.
*
* @return True if at least one group was removed, false otherwise.
* False is also returned if this feature isn't supported for the current permissions system.
*/
public boolean removeGroups(OfflinePlayer player, Collection<UserGroup> groupNames) {
// If no permissions system is used, return false
if (!isEnabled()) {
return false;
}
// Add each group to the user
boolean result = false;
for (UserGroup group : groupNames) {
if (!group.getGroupName().isEmpty()) {
result |= handler.removeFromGroup(player, group);
}
}
// Return the result
return result;
}
/**
* Set the permission group of a player, if supported.
* This clears the current groups of the player.
*
* @param player The player
* @param group The name of the group.
*
* @return True if succeed, false otherwise.
* False is also returned if this feature isn't supported for the current permissions system.
*/
public boolean setGroup(OfflinePlayer player, UserGroup group) {
return isEnabled() && handler.setGroup(player, group);
}
/**
* Remove all groups of the specified player, if supported.
* Systems like Essentials GroupManager don't allow all groups to be removed from a player, thus the user will stay
* in its primary group. All the subgroups are removed just fine.
*
* @param player The player to remove all groups from.
*
* @return True if succeed, false otherwise.
* False will also be returned if this feature isn't supported for the used permissions system.
*/
public boolean removeAllGroups(OfflinePlayer player) {
// If no permissions system is used, return false
if (!isEnabled()) {
return false;
}
// Get a list of current groups
Collection<UserGroup> groups = getGroups(player);
// Remove each group
return removeGroups(player, groups);
}
/**
* Loads the permission data of the given player.
*
* @param offlinePlayer the offline player.
* @return true if the load was successful.
*/
public boolean loadUserData(OfflinePlayer offlinePlayer) {
try {
loadUserData(offlinePlayer.getUniqueId());
} catch (PermissionLoadUserException e) {
logger.logException("Unable to load the permission data of user " + offlinePlayer.getName(), e);
return false;
}
return true;
}
/**
* Loads the permission data of the given player unique identifier.
*
* @param uuid the {@link UUID} of the player.
* @throws PermissionLoadUserException if the action failed.
*/
public void loadUserData(UUID uuid) throws PermissionLoadUserException {
if (!isEnabled()) {
return;
}
handler.loadUserData(uuid);
}
}
@@ -0,0 +1,91 @@
package fr.xephi.authme.permission;
/**
* Enum representing the permissions systems AuthMe supports.
*/
public enum PermissionsSystemType {
/**
* LuckPerms.
*/
LUCK_PERMS("LuckPerms", "LuckPerms"),
/**
* Permissions Ex.
*/
PERMISSIONS_EX("PermissionsEx", "PermissionsEx"),
/**
* zPermissions.
*/
Z_PERMISSIONS("zPermissions", "zPermissions"),
/**
* Vault.
*/
VAULT("Vault", "Vault");
/**
* The display name of the permissions system.
*/
private String displayName;
/**
* The name of the permissions system plugin.
*/
private String pluginName;
/**
* Constructor for PermissionsSystemType.
*
* @param displayName Display name of the permissions system.
* @param pluginName Name of the plugin.
*/
PermissionsSystemType(String displayName, String pluginName) {
this.displayName = displayName;
this.pluginName = pluginName;
}
/**
* Get the display name of the permissions system.
*
* @return Display name.
*/
public String getDisplayName() {
return this.displayName;
}
/**
* Return the plugin name.
*
* @return Plugin name.
*/
public String getPluginName() {
return this.pluginName;
}
/**
* Cast the permissions system type to a string.
*
* @return The display name of the permissions system.
*/
@Override
public String toString() {
return getDisplayName();
}
/**
* Check if a given plugin is a permissions system.
*
* @param name The name of the plugin to check.
* @return If the plugin is a valid permissions system.
*/
public static boolean isPermissionSystem(String name) {
for (PermissionsSystemType permissionsSystemType : values()) {
if (permissionsSystemType.pluginName.equals(name)) {
return true;
}
}
return false;
}
}
@@ -0,0 +1,112 @@
package fr.xephi.authme.permission;
/**
* AuthMe player permission nodes, for regular players.
*/
public enum PlayerPermission implements PermissionNode {
/**
* Command permission to login.
*/
LOGIN("authme.player.login"),
/**
* Command permission to logout.
*/
LOGOUT("authme.player.logout"),
/**
* Command permission to register.
*/
REGISTER("authme.player.register"),
/**
* Command permission to unregister.
*/
UNREGISTER("authme.player.unregister"),
/**
* Command permission to change the password.
*/
CHANGE_PASSWORD("authme.player.changepassword"),
/**
* Command permission to see the own email address.
*/
SEE_EMAIL("authme.player.email.see"),
/**
* Command permission to add an email address.
*/
ADD_EMAIL("authme.player.email.add"),
/**
* Command permission to change the email address.
*/
CHANGE_EMAIL("authme.player.email.change"),
/**
* Command permission to recover an account using its email address.
*/
RECOVER_EMAIL("authme.player.email.recover"),
/**
* Command permission to use captcha.
*/
CAPTCHA("authme.player.captcha"),
/**
* Permission for users a login can be forced to.
*/
CAN_LOGIN_BE_FORCED("authme.player.canbeforced"),
/**
* Permission to use to see own other accounts.
*/
SEE_OWN_ACCOUNTS("authme.player.seeownaccounts"),
/**
* Permission to use the email verification codes feature.
*/
VERIFICATION_CODE("authme.player.security.verificationcode"),
/**
* Permission that enables on join quick commands checks for the player.
*/
QUICK_COMMANDS_PROTECTION("authme.player.protection.quickcommandsprotection"),
/**
* Permission to enable two-factor authentication.
*/
ENABLE_TWO_FACTOR_AUTH("authme.player.totpadd"),
/**
* Permission to disable two-factor authentication.
*/
DISABLE_TWO_FACTOR_AUTH("authme.player.totpremove");
/**
* The permission node.
*/
private String node;
/**
* Constructor.
*
* @param node Permission node.
*/
PlayerPermission(String node) {
this.node = node;
}
@Override
public String getNode() {
return node;
}
@Override
public DefaultPermission getDefaultPermission() {
return DefaultPermission.ALLOWED;
}
}
@@ -0,0 +1,79 @@
package fr.xephi.authme.permission;
/**
* Permission nodes that give a player a status (e.g. VIP)
* or grant them more freedom (e.g. less restrictions).
*/
public enum PlayerStatePermission implements PermissionNode {
/**
* Permission node to bypass AntiBot protection.
*/
BYPASS_ANTIBOT("authme.bypassantibot", DefaultPermission.OP_ONLY),
/**
* Permission node to bypass BungeeCord server teleportation.
*/
BYPASS_BUNGEE_SEND("authme.bypassbungeesend", DefaultPermission.NOT_ALLOWED),
/**
* Permission for users to bypass force-survival mode.
*/
BYPASS_FORCE_SURVIVAL("authme.bypassforcesurvival", DefaultPermission.OP_ONLY),
/**
* When the server is full and someone with this permission joins the server, someone will be kicked.
*/
IS_VIP("authme.vip", DefaultPermission.NOT_ALLOWED),
/**
* Permission to be able to register multiple accounts.
*/
ALLOW_MULTIPLE_ACCOUNTS("authme.allowmultipleaccounts", DefaultPermission.OP_ONLY),
/**
* Permission to bypass the purging process.
*/
BYPASS_PURGE("authme.bypasspurge", DefaultPermission.NOT_ALLOWED),
/**
* Permission to bypass the GeoIp country code check.
*/
BYPASS_COUNTRY_CHECK("authme.bypasscountrycheck", DefaultPermission.NOT_ALLOWED),
/**
* Permission to send chat messages before being logged in.
*/
ALLOW_CHAT_BEFORE_LOGIN("authme.allowchatbeforelogin", DefaultPermission.NOT_ALLOWED);
/**
* The permission node.
*/
private String node;
/**
* The default permission level.
*/
private DefaultPermission defaultPermission;
/**
* Constructor.
*
* @param node Permission node
* @param defaultPermission The default permission
*/
PlayerStatePermission(String node, DefaultPermission defaultPermission) {
this.node = node;
this.defaultPermission = defaultPermission;
}
@Override
public String getNode() {
return node;
}
@Override
public DefaultPermission getDefaultPermission() {
return defaultPermission;
}
}
@@ -0,0 +1,23 @@
package fr.xephi.authme.permission.handlers;
import net.luckperms.api.context.ImmutableContextSet;
import net.luckperms.api.model.group.Group;
public class LuckPermGroup {
private Group group;
private ImmutableContextSet contexts;
public LuckPermGroup(Group group, ImmutableContextSet contexts) {
this.group = group;
this.contexts = contexts;
}
public Group getGroup() {
return group;
}
public ImmutableContextSet getContexts() {
return contexts;
}
}
@@ -0,0 +1,227 @@
package fr.xephi.authme.permission.handlers;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.data.limbo.UserGroup;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.permission.PermissionNode;
import fr.xephi.authme.permission.PermissionsSystemType;
import net.luckperms.api.LuckPerms;
import net.luckperms.api.LuckPermsProvider;
import net.luckperms.api.cacheddata.CachedPermissionData;
import net.luckperms.api.context.ContextSetFactory;
import net.luckperms.api.model.data.DataMutateResult;
import net.luckperms.api.model.group.Group;
import net.luckperms.api.model.user.User;
import net.luckperms.api.node.NodeEqualityPredicate;
import net.luckperms.api.node.types.InheritanceNode;
import net.luckperms.api.query.QueryMode;
import net.luckperms.api.query.QueryOptions;
import org.bukkit.OfflinePlayer;
import org.jetbrains.annotations.NotNull;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;
/**
* Handler for LuckPerms.
*
* @see <a href="https://www.spigotmc.org/resources/luckperms-an-advanced-permissions-system.28140/">LuckPerms SpigotMC page</a>
* @see <a href="https://github.com/lucko/LuckPerms">LuckPerms on Github</a>
*/
public class LuckPermsHandler implements PermissionHandler {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(LuckPermsHandler.class);
private LuckPerms luckPerms;
public LuckPermsHandler() throws PermissionHandlerException {
try {
luckPerms = LuckPermsProvider.get();
} catch (IllegalStateException e) {
throw new PermissionHandlerException("Could not get api of LuckPerms", e);
}
}
@Override
public boolean addToGroup(OfflinePlayer player, UserGroup group) {
Group newGroup = luckPerms.getGroupManager().getGroup(group.getGroupName());
if (newGroup == null) {
return false;
}
String playerName = player.getName();
if (playerName == null) {
return false;
}
User user = luckPerms.getUserManager().getUser(playerName);
if (user == null) {
return false;
}
InheritanceNode node = buildGroupNode(group);
DataMutateResult result = user.data().add(node);
if (result == DataMutateResult.FAIL) {
return false;
}
luckPerms.getUserManager().saveUser(user);
return true;
}
@Override
public boolean hasGroupSupport() {
return true;
}
@Override
public boolean hasPermissionOffline(String name, PermissionNode node) {
User user = luckPerms.getUserManager().getUser(name);
if (user == null) {
logger.warning("LuckPermsHandler: tried to check permission for offline user "
+ name + " but it isn't loaded!");
return false;
}
CachedPermissionData permissionData = user.getCachedData()
.getPermissionData(QueryOptions.builder(QueryMode.CONTEXTUAL).build());
return permissionData.checkPermission(node.getNode()).asBoolean();
}
@Override
public boolean isInGroup(OfflinePlayer player, UserGroup group) {
String playerName = player.getName();
if (playerName == null) {
return false;
}
User user = luckPerms.getUserManager().getUser(playerName);
if (user == null) {
logger.warning("LuckPermsHandler: tried to check group for offline user "
+ player.getName() + " but it isn't loaded!");
return false;
}
InheritanceNode inheritanceNode = InheritanceNode.builder(group.getGroupName()).build();
return user.data().contains(inheritanceNode, NodeEqualityPredicate.EXACT).asBoolean();
}
@Override
public boolean removeFromGroup(OfflinePlayer player, UserGroup group) {
String playerName = player.getName();
if (playerName == null) {
return false;
}
User user = luckPerms.getUserManager().getUser(playerName);
if (user == null) {
logger.warning("LuckPermsHandler: tried to remove group for offline user "
+ player.getName() + " but it isn't loaded!");
return false;
}
InheritanceNode groupNode = InheritanceNode.builder(group.getGroupName()).build();
boolean result = user.data().remove(groupNode) != DataMutateResult.FAIL;
luckPerms.getUserManager().saveUser(user);
return result;
}
@Override
public boolean setGroup(OfflinePlayer player, UserGroup group) {
String playerName = player.getName();
if (playerName == null) {
return false;
}
User user = luckPerms.getUserManager().getUser(playerName);
if (user == null) {
logger.warning("LuckPermsHandler: tried to set group for offline user "
+ player.getName() + " but it isn't loaded!");
return false;
}
InheritanceNode groupNode = buildGroupNode(group);
DataMutateResult result = user.data().add(groupNode);
if (result == DataMutateResult.FAIL) {
return false;
}
user.data().clear(node -> {
if (!(node instanceof InheritanceNode)) {
return false;
}
InheritanceNode inheritanceNode = (InheritanceNode) node;
return !inheritanceNode.equals(groupNode);
});
luckPerms.getUserManager().saveUser(user);
return true;
}
@Override
public List<UserGroup> getGroups(OfflinePlayer player) {
String playerName = player.getName();
if (playerName == null) {
return Collections.emptyList();
}
User user = luckPerms.getUserManager().getUser(playerName);
if (user == null) {
logger.warning("LuckPermsHandler: tried to get groups for offline user "
+ player.getName() + " but it isn't loaded!");
return Collections.emptyList();
}
return user.getDistinctNodes().stream()
.filter(node -> node instanceof InheritanceNode)
.map(node -> (InheritanceNode) node)
.map(node -> {
Group group = luckPerms.getGroupManager().getGroup(node.getGroupName());
if (group == null) {
return null;
}
return new LuckPermGroup(group, node.getContexts());
})
.filter(Objects::nonNull)
.sorted((o1, o2) -> sortGroups(user, o1, o2))
.map(g -> new UserGroup(g.getGroup().getName(), g.getContexts().toFlattenedMap()))
.collect(Collectors.toList());
}
@Override
public PermissionsSystemType getPermissionSystem() {
return PermissionsSystemType.LUCK_PERMS;
}
@Override
public void loadUserData(UUID uuid) throws PermissionLoadUserException {
try {
luckPerms.getUserManager().loadUser(uuid).get(5, TimeUnit.SECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException e) {
throw new PermissionLoadUserException("Unable to load the permission data of the user " + uuid, e);
}
}
@NotNull
private InheritanceNode buildGroupNode(UserGroup group) {
ContextSetFactory contextSetFactory = luckPerms.getContextManager().getContextSetFactory();
InheritanceNode.Builder builder = InheritanceNode.builder(group.getGroupName());
if (group.getContextMap() != null) {
group.getContextMap().forEach((k, v) -> builder.withContext((contextSetFactory.immutableOf(k, v))));
}
return builder.build();
}
private int sortGroups(User user, LuckPermGroup o1, LuckPermGroup o2) {
Group group1 = o1.getGroup();
Group group2 = o2.getGroup();
if (group1.getName().equals(user.getPrimaryGroup()) || group2.getName().equals(user.getPrimaryGroup())) {
return group1.getName().equals(user.getPrimaryGroup()) ? 1 : -1;
}
int i = Integer.compare(group2.getWeight().orElse(0), group1.getWeight().orElse(0));
return i != 0 ? i : group1.getName().compareToIgnoreCase(group2.getName());
}
}
@@ -0,0 +1,114 @@
package fr.xephi.authme.permission.handlers;
import fr.xephi.authme.data.limbo.UserGroup;
import fr.xephi.authme.permission.PermissionNode;
import fr.xephi.authme.permission.PermissionsSystemType;
import fr.xephi.authme.util.Utils;
import org.bukkit.OfflinePlayer;
import java.util.Collection;
import java.util.UUID;
public interface PermissionHandler {
/**
* Add the permission group of a player, if supported.
*
* @param player The player
* @param group The name of the group.
*
* @return True if succeed, false otherwise.
* False is also returned if this feature isn't supported for the current permissions system.
*/
boolean addToGroup(OfflinePlayer player, UserGroup group);
/**
* Check whether the current permissions system has group support.
* If no permissions system is hooked, false will be returned.
*
* @return True if the current permissions system supports groups, false otherwise.
*/
boolean hasGroupSupport();
/**
* Check if a player has permission by their name.
* Used to check an offline player's permission.
*
* @param name The player's name.
* @param node The permission node.
*
* @return True if the player has permission.
*/
boolean hasPermissionOffline(String name, PermissionNode node);
/**
* Check whether the player is in the specified group.
*
* @param player The player.
* @param group The group name.
*
* @return True if the player is in the specified group, false otherwise.
* False is also returned if groups aren't supported by the used permissions system.
*/
default boolean isInGroup(OfflinePlayer player, UserGroup group) {
return getGroups(player).contains(group);
}
/**
* Remove the permission group of a player, if supported.
*
* @param player The player
* @param group The name of the group.
*
* @return True if succeed, false otherwise.
* False is also returned if this feature isn't supported for the current permissions system.
*/
boolean removeFromGroup(OfflinePlayer player, UserGroup group);
/**
* Set the permission group of a player, if supported.
* This clears the current groups of the player.
*
* @param player The player
* @param group The name of the group.
*
* @return True if succeed, false otherwise.
* False is also returned if this feature isn't supported for the current permissions system.
*/
boolean setGroup(OfflinePlayer player, UserGroup group);
/**
* Get the permission groups of a player, if available.
*
* @param player The player.
*
* @return Permission groups, or an empty list if this feature is not supported.
*/
Collection<UserGroup> getGroups(OfflinePlayer player);
/**
* Get the primary group of a player, if available.
*
* @param player The player.
*
* @return The name of the primary permission group. Or null.
*/
default UserGroup getPrimaryGroup(OfflinePlayer player) {
Collection<UserGroup> groups = getGroups(player);
if (Utils.isCollectionEmpty(groups)) {
return null;
}
return groups.iterator().next();
}
/**
* Get the permission system that is being used.
*
* @return The permission system.
*/
PermissionsSystemType getPermissionSystem();
default void loadUserData(UUID uuid) throws PermissionLoadUserException {
}
}
@@ -0,0 +1,16 @@
package fr.xephi.authme.permission.handlers;
/**
* Exception during the instantiation of a {@link PermissionHandler}.
*/
@SuppressWarnings("serial")
public class PermissionHandlerException extends Exception {
public PermissionHandlerException(String message) {
super(message);
}
public PermissionHandlerException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -0,0 +1,13 @@
package fr.xephi.authme.permission.handlers;
import java.util.UUID;
/**
* Exception thrown when a {@link PermissionHandler#loadUserData(UUID uuid)} request fails.
*/
public class PermissionLoadUserException extends Exception {
public PermissionLoadUserException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -0,0 +1,90 @@
package fr.xephi.authme.permission.handlers;
import fr.xephi.authme.data.limbo.UserGroup;
import fr.xephi.authme.permission.PermissionNode;
import fr.xephi.authme.permission.PermissionsSystemType;
import org.bukkit.OfflinePlayer;
import ru.tehkode.permissions.PermissionManager;
import ru.tehkode.permissions.PermissionUser;
import ru.tehkode.permissions.bukkit.PermissionsEx;
import java.util.ArrayList;
import java.util.List;
import static java.util.stream.Collectors.toList;
/**
* Handler for PermissionsEx.
*
* @see <a href="https://dev.bukkit.org/projects/permissionsex">PermissionsEx Bukkit page</a>
* @see <a href="https://github.com/PEXPlugins/PermissionsEx">PermissionsEx on Github</a>
*/
public class PermissionsExHandler implements PermissionHandler {
private PermissionManager permissionManager;
public PermissionsExHandler() throws PermissionHandlerException {
permissionManager = PermissionsEx.getPermissionManager();
if (permissionManager == null) {
throw new PermissionHandlerException("Could not get manager of PermissionsEx");
}
}
@Override
public boolean addToGroup(OfflinePlayer player, UserGroup group) {
if (!PermissionsEx.getPermissionManager().getGroupNames().contains(group)) {
return false;
}
PermissionUser user = PermissionsEx.getUser(player.getName());
user.addGroup(group.getGroupName());
return true;
}
@Override
public boolean hasGroupSupport() {
return true;
}
@Override
public boolean hasPermissionOffline(String name, PermissionNode node) {
PermissionUser user = permissionManager.getUser(name);
return user.has(node.getNode());
}
@Override
public boolean isInGroup(OfflinePlayer player, UserGroup group) {
PermissionUser user = permissionManager.getUser(player.getName());
return user.inGroup(group.getGroupName());
}
@Override
public boolean removeFromGroup(OfflinePlayer player, UserGroup group) {
PermissionUser user = permissionManager.getUser(player.getName());
user.removeGroup(group.getGroupName());
return true;
}
@Override
public boolean setGroup(OfflinePlayer player, UserGroup group) {
List<String> groups = new ArrayList<>();
groups.add(group.getGroupName());
PermissionUser user = permissionManager.getUser(player.getName());
user.setParentsIdentifier(groups);
return true;
}
@Override
public List<UserGroup> getGroups(OfflinePlayer player) {
PermissionUser user = permissionManager.getUser(player.getName());
return user.getParentIdentifiers(null).stream()
.map(i -> new UserGroup(i, null))
.collect(toList());
}
@Override
public PermissionsSystemType getPermissionSystem() {
return PermissionsSystemType.PERMISSIONS_EX;
}
}
@@ -0,0 +1,105 @@
package fr.xephi.authme.permission.handlers;
import com.google.common.annotations.VisibleForTesting;
import fr.xephi.authme.data.limbo.UserGroup;
import fr.xephi.authme.permission.PermissionNode;
import fr.xephi.authme.permission.PermissionsSystemType;
import net.milkbowl.vault.permission.Permission;
import org.bukkit.OfflinePlayer;
import org.bukkit.Server;
import org.bukkit.plugin.RegisteredServiceProvider;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static java.util.stream.Collectors.toList;
/**
* Handler for permissions via Vault.
*
* @see <a href="https://dev.bukkit.org/projects/vault">Vault Bukkit page</a>
* @see <a href="https://github.com/milkbowl/Vault">Vault on Github</a>
*/
public class VaultHandler implements PermissionHandler {
private Permission vaultProvider;
public VaultHandler(Server server) throws PermissionHandlerException {
this.vaultProvider = getVaultPermission(server);
}
/**
* Returns the Vault Permission interface.
*
* @param server the bukkit server instance
* @return the vault permission instance
* @throws PermissionHandlerException if the vault permission instance cannot be retrieved
*/
@VisibleForTesting
Permission getVaultPermission(Server server) throws PermissionHandlerException {
// Get the permissions provider service
RegisteredServiceProvider<Permission> permissionProvider = server
.getServicesManager().getRegistration(Permission.class);
if (permissionProvider == null) {
throw new PermissionHandlerException("Could not load permissions provider service");
}
// Get the Vault provider and make sure it's valid
Permission vaultPerms = permissionProvider.getProvider();
if (vaultPerms == null) {
throw new PermissionHandlerException("Could not load Vault permissions provider");
}
return vaultPerms;
}
@Override
public boolean addToGroup(OfflinePlayer player, UserGroup group) {
return vaultProvider.playerAddGroup(null, player, group.getGroupName());
}
@Override
public boolean hasGroupSupport() {
return vaultProvider.hasGroupSupport();
}
@Override
public boolean hasPermissionOffline(String name, PermissionNode node) {
return vaultProvider.has((String) null, name, node.getNode());
}
@Override
public boolean isInGroup(OfflinePlayer player, UserGroup group) {
return vaultProvider.playerInGroup(null, player, group.getGroupName());
}
@Override
public boolean removeFromGroup(OfflinePlayer player, UserGroup group) {
return vaultProvider.playerRemoveGroup(null, player, group.getGroupName());
}
@Override
public boolean setGroup(OfflinePlayer player, UserGroup group) {
for (UserGroup g : getGroups(player)) {
removeFromGroup(player, g);
}
return vaultProvider.playerAddGroup(null, player, group.getGroupName());
}
@Override
public List<UserGroup> getGroups(OfflinePlayer player) {
String[] groups = vaultProvider.getPlayerGroups(null, player);
return groups == null ? Collections.emptyList() : Arrays.stream(groups).map(UserGroup::new).collect(toList());
}
@Override
public UserGroup getPrimaryGroup(OfflinePlayer player) {
return new UserGroup(vaultProvider.getPrimaryGroup(null, player));
}
@Override
public PermissionsSystemType getPermissionSystem() {
return PermissionsSystemType.VAULT;
}
}
@@ -0,0 +1,79 @@
package fr.xephi.authme.permission.handlers;
import fr.xephi.authme.data.limbo.UserGroup;
import fr.xephi.authme.permission.PermissionNode;
import fr.xephi.authme.permission.PermissionsSystemType;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.tyrannyofheaven.bukkit.zPermissions.ZPermissionsService;
import java.util.Collection;
import java.util.Map;
import static java.util.stream.Collectors.toList;
/**
* Handler for zPermissions.
*
* @see <a href="https://dev.bukkit.org/projects/zpermissions">zPermissions Bukkit page</a>
* @see <a href="https://github.com/ZerothAngel/zPermissions">zPermissions on Github</a>
*/
public class ZPermissionsHandler implements PermissionHandler {
private ZPermissionsService zPermissionsService;
public ZPermissionsHandler() throws PermissionHandlerException {
// Set the zPermissions service and make sure it's valid
ZPermissionsService zPermissionsService = Bukkit.getServicesManager().load(ZPermissionsService.class);
if (zPermissionsService == null) {
throw new PermissionHandlerException("Failed to get the ZPermissions service!");
}
this.zPermissionsService = zPermissionsService;
}
@Override
public boolean addToGroup(OfflinePlayer player, UserGroup group) {
return Bukkit.dispatchCommand(Bukkit.getConsoleSender(),
"permissions player " + player.getName() + " addgroup " + group.getGroupName());
}
@Override
public boolean hasGroupSupport() {
return true;
}
@Override
public boolean hasPermissionOffline(String name, PermissionNode node) {
Map<String, Boolean> perms = zPermissionsService.getPlayerPermissions(null, null, name);
return perms.getOrDefault(node.getNode(), false);
}
@Override
public boolean removeFromGroup(OfflinePlayer player, UserGroup group) {
return Bukkit.dispatchCommand(Bukkit.getConsoleSender(),
"permissions player " + player.getName() + " removegroup " + group.getGroupName());
}
@Override
public boolean setGroup(OfflinePlayer player, UserGroup group) {
return Bukkit.dispatchCommand(Bukkit.getConsoleSender(),
"permissions player " + player.getName() + " setgroup " + group.getGroupName());
}
@Override
public Collection<UserGroup> getGroups(OfflinePlayer player) {
return zPermissionsService.getPlayerGroups(player.getName()).stream()
.map(UserGroup::new)
.collect(toList());
}
@Override
public UserGroup getPrimaryGroup(OfflinePlayer player) {
return new UserGroup(zPermissionsService.getPlayerPrimaryGroup(player.getName()));
}
@Override
public PermissionsSystemType getPermissionSystem() {
return PermissionsSystemType.Z_PERMISSIONS;
}
}