Compare commits

...

56 Commits

Author SHA1 Message Date
Cai Xukun ebf8d55d60 Add b9 hash 2023-04-24 02:33:13 +08:00
Cai Xukun 9bb99ed355 Update maven.yml 2023-04-23 21:54:56 +08:00
Cai Xukun eaa30cc5eb upload b8 sha 2023-04-23 19:48:19 +08:00
Cai Xukun 4046105e87 upload b7 hash 2023-04-23 00:47:29 +08:00
Cai Xukun e782cccf72 Add files via upload 2023-04-22 21:31:47 +08:00
Cai Xukun eaa0fba587 Add files via upload 2023-04-22 21:29:16 +08:00
Cai Xukun cc248c3459 Add files via upload 2023-04-22 21:15:26 +08:00
Cai Xukun ab24793861 Add files via upload 2023-04-22 21:13:12 +08:00
Cai Xukun 25ebbf6f20 Add files via upload 2023-04-22 20:49:30 +08:00
Cai Xukun d3e463165d Update B6 sha file 2023-04-22 19:20:25 +08:00
Cai Xukun a459e6bad8 Add files via upload 2023-04-22 19:16:00 +08:00
Cai Xukun 6a91130aa8 Merge branch 'Stabrinai:master' into master 2023-04-20 20:38:12 +08:00
Sattera d25949fc3b 更新 2023-04-19 16:13:38 +08:00
HaHaWTH f63f00fade Update maven.yml 2023-04-06 21:43:55 +08:00
HaHaWTH 19c18987f6 Update maven.yml 2023-04-06 21:14:09 +08:00
HaHaWTH db1650c27f Update maven.yml 2023-04-06 20:59:28 +08:00
HaHaWTH f45696f82f Update maven.yml 2023-04-06 20:56:39 +08:00
HaHaWTH 1c1879ea01 Update maven.yml 2023-04-06 20:48:00 +08:00
HaHaWTH 812762db25 Merge branch 'Stabrinai:master' into master 2023-04-06 20:36:22 +08:00
Sattera a4bf7adb60 添加对 floodgate 的支持 2023-04-06 09:42:12 +08:00
Sattera 11c5237950 Merge remote-tracking branch 'origin/master'
# Conflicts:
#	src/main/java/fr/xephi/authme/listener/PlayerListener.java
2023-04-06 09:38:13 +08:00
Sattera bc43afe3d0 添加对 floodgate 的支持 2023-04-06 09:37:57 +08:00
HaHaWTH ced3d17537 Update README.md 2023-04-06 02:19:03 +08:00
HaHaWTH d9b3c59f30 Update maven.yml 2023-04-06 01:58:08 +08:00
HaHaWTH 8c286ceceb Update maven.yml 2023-04-06 01:54:54 +08:00
HaHaWTH 2ce6b066cc Update maven.yml 2023-04-06 01:52:50 +08:00
HaHaWTH 585b69ecd2 Update maven.yml 2023-04-06 01:50:33 +08:00
HaHaWTH 17187b05c1 Update maven.yml 2023-04-06 01:49:05 +08:00
HaHaWTH 6f193f05ce Update maven.yml 2023-04-06 01:47:55 +08:00
HaHaWTH a626265b09 Update maven.yml 2023-04-06 01:42:51 +08:00
HaHaWTH bda8613f93 Update .gitignore 2023-04-06 01:19:09 +08:00
HaHaWTH 44136bb91f Update maven.yml 2023-04-06 01:08:45 +08:00
HaHaWTH 69514738f7 Update maven.yml 2023-04-06 01:01:54 +08:00
HaHaWTH 220b31bb99 Update maven.yml 2023-04-06 00:59:20 +08:00
HaHaWTH 3b58a0acc9 Update maven.yml 2023-04-06 00:57:06 +08:00
HaHaWTH 5efa360cb2 Update README.md 2023-04-06 00:25:56 +08:00
HaHaWTH 2269c93dee Update maven.yml 2023-04-06 00:22:41 +08:00
HaHaWTH bf6233c024 Update maven.yml 2023-04-05 23:32:01 +08:00
HaHaWTH 3cc6f535a8 Update maven.yml 2023-04-05 22:01:32 +08:00
HaHaWTH 95d9edddeb Merge branch 'Stabrinai:master' into master 2023-04-05 21:05:10 +08:00
Sattera 4a559a7ccf Merge remote-tracking branch 'origin/master'
# Conflicts:
#	src/main/java/fr/xephi/authme/listener/PlayerListener.java
2023-04-05 20:25:10 +08:00
Sattera baaabb22d4 添加对 floodgate 的支持 2023-04-05 20:24:55 +08:00
HaHaWTH 9e39f4a186 Create maven-publish.yml 2023-04-05 18:56:36 +08:00
Sattera c2b7a693b2 添加对 floodgate 的支持 2023-04-04 09:08:07 +08:00
Sattera 0e1e65c7f7 取消 /cp 指令的邮箱验证 2023-03-28 08:59:03 +08:00
Sattera d33f838f3a 添加 keybindings.use 节点控制 下蹲 + 切副手 打开菜单 //自用内容 2023-03-22 10:02:29 +08:00
Sabrita 393449e08e 默认删除qq邮箱支持 2023-03-01 22:20:03 +08:00
Sabrita bdf7816306 更改十分钟内注册逻辑 2023-02-28 13:22:15 +08:00
Sabrita e109094472 删测测试项 默认开启用户名限制并增加默认限制用户 2023-02-28 13:13:17 +08:00
Sabrita ea1af80ea4 修复构建 2023-02-28 12:51:55 +08:00
Sabrita 674d72c113 优化 import 。更改默认配置 2023-02-28 12:36:56 +08:00
Sabrita 912646c041 增加服务器被关闭时的邮箱通知 2023-02-27 19:57:00 +08:00
Sabrita 4ca879b08a 删除 wecome 提醒 2023-02-27 19:10:04 +08:00
Sabrita 2d4b2381ff 默认使用邮箱注册 2023-02-27 18:45:28 +08:00
Sabrita bbfce5bcfd 删除测试库
删除 wecome 增加新代码
2023-02-27 18:34:29 +08:00
Sabrita cfca8ccd85 删除测试库
删除 wecome 增加新代码
2023-02-27 18:34:06 +08:00
397 changed files with 1070 additions and 35038 deletions
+34
View File
@@ -0,0 +1,34 @@
# This workflow will build a package using Maven and then publish it to GitHub packages when a release is created
# For more information see: https://github.com/actions/setup-java/blob/main/docs/advanced-usage.md#apache-maven-with-a-settings-path
name: Maven Package
on:
release:
types: [created]
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- uses: actions/checkout@v3
- name: Set up JDK 11
uses: actions/setup-java@v3
with:
java-version: '11'
distribution: 'temurin'
server-id: github # Value of the distributionManagement/repository/id field of the pom.xml
settings-path: ${{ github.workspace }} # location for the settings.xml file
- name: Build with Maven
run: mvn -B package --file pom.xml
- name: Publish to GitHub Packages Apache Maven
run: mvn deploy -s $GITHUB_WORKSPACE/settings.xml
env:
GITHUB_TOKEN: ${{ github.token }}
+4 -3
View File
@@ -7,11 +7,11 @@ on:
- master
jobs:
build_and_test:
Build:
strategy:
matrix:
jdkversion: [11]
runs-on: ubuntu-latest
runs-on: windows-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-java@v3
@@ -19,5 +19,6 @@ jobs:
distribution: 'temurin'
java-version: ${{ matrix.jdkversion }}
cache: 'maven'
- name: Build with Maven
- name: 使用Maven构建
run: mvn -V -B clean package --file pom.xml
+1 -1
View File
@@ -24,7 +24,7 @@ hs_err_pid*
# Include the project's code style settings file
!.idea/codeStyleSettings.xml
/target/class/
# File-based project format:
*.ipr
*.iws
+4 -4
View File
@@ -1,12 +1,12 @@
# AuthMeReloaded
**"The best authentication plugin for the Bukkit modding API!"**
# AuthMeReReloaded
**"A Fork of Authme that contains many bug fixes!"**
**请前往Releases下载最新版本**
<img src="wallpaper.png?raw=true" alt="AuthMeLogo"/>
| Type | Badges |
|-------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| **General:** | ![](https://tokei.rs/b1/github/AuthMe/AuthMeReloaded?category=code) ![](https://tokei.rs/b1/github/AuthMe/AuthMeReloaded?category=files) |
| **Code quality:** | [![Code Climate](https://codeclimate.com/github/AuthMe/AuthMeReloaded/badges/gpa.svg)](https://codeclimate.com/github/AuthMe/AuthMeReloaded) [![Coverage status](https://coveralls.io/repos/AuthMe-Team/AuthMeReloaded/badge.svg?branch=master&service=github)](https://coveralls.io/github/AuthMe-Team/AuthMeReloaded?branch=master) |
| **代码质量:** | [![Code Climate](https://codeclimate.com/github/AuthMe/AuthMeReloaded/badges/gpa.svg)](https://codeclimate.com/github/AuthMe/AuthMeReloaded) [![Coverage status](https://coveralls.io/repos/AuthMe-Team/AuthMeReloaded/badge.svg?branch=master&service=github)](https://coveralls.io/github/AuthMe-Team/AuthMeReloaded?branch=master) |
| **Jenkins CI:** | [![Jenkins Status](https://img.shields.io/website-up-down-green-red/http/shields.io.svg?label=ci.codemc.org)](https://ci.codemc.org/) [![Build Status](https://ci.codemc.org/buildStatus/icon?job=AuthMe/AuthMeReloaded)](https://ci.codemc.org/job/AuthMe/job/AuthMeReloaded) ![Build Tests](https://img.shields.io/jenkins/t/https/ci.codemc.org/job/AuthMe/job/AuthMeReloaded.svg) |
| **Other CIs:** | [![Build Status](https://www.travis-ci.com/AuthMe/AuthMeReloaded.svg?branch=master)](https://www.travis-ci.com/AuthMe/AuthMeReloaded) |
+1
View File
@@ -0,0 +1 @@
423084f2a50c27f62d1b5c85a95e78b9bc3df49d5bd9cefd6fe1aa9227b856c1
+1
View File
@@ -0,0 +1 @@
410df26b12703b82987b9d739c19211346418f1c954d214827805c13b5f82c98
+1
View File
@@ -0,0 +1 @@
20569ebc44a9847da0946de5a3bf2cd2b7855dffb03abc9d29204afcaa64b8bb
+1
View File
@@ -0,0 +1 @@
dcfa0100552e76b761cc4f8c77a1f18c3c0d1b0635517d9a920bc7f7a2ba887d
-7
View File
@@ -304,13 +304,6 @@ settings:
forceKickAfterRegister: false
# Does AuthMe need to enforce a /login after a successful registration?
forceLoginAfterRegister: false
# Enable to display the welcome message (welcome.txt) after a login
# You can use colors in this welcome.txt + some replaced strings:
# {PLAYER}: player name, {ONLINE}: display number of online players,
# {MAXPLAYERS}: display server slots, {IP}: player ip, {LOGINS}: number of players logged,
# {WORLD}: player current world, {SERVER}: server name
# {VERSION}: get current bukkit version, {COUNTRY}: player country
useWelcomeMessage: true
# Broadcast the welcome message to the server or only to the player?
# set true for server or false for player
broadcastWelcomeMessage: false
+31 -11
View File
@@ -47,7 +47,7 @@
<licenses>
<license>
<name>The GNU General Public Licence version 3 (GPLv3)</name>
<name>The GNU Public Licence version 3 (GPLv3)</name>
<url>https://www.gnu.org/licenses/gpl-3.0.html</url>
<distribution>repo</distribution>
</license>
@@ -196,6 +196,11 @@
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.3.0</version>
<configuration>
<nonFilteredFileExtensions>
<nonFilteredFileExtension>mmdb</nonFilteredFileExtension>
</nonFilteredFileExtensions>
</configuration>
</plugin>
<!-- Compile and include classes -->
<plugin>
@@ -593,11 +598,26 @@
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>opencollab-snapshot</id>
<url>https://repo.opencollab.dev/maven-snapshots/</url>
<releases>
<enabled>false</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<dependencies>
<!-- Java Libraries -->
<dependency>
<groupId>org.geysermc.floodgate</groupId>
<artifactId>api</artifactId>
<version>2.2.0-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<!-- Jalu Injector -->
<dependency>
<groupId>ch.jalu</groupId>
@@ -649,7 +669,7 @@
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.8.1</version> <!-- Log4J version bundled in 1.12.2 -->
<version>2.20.0</version> <!-- Log4J version bundled in 1.12.2 -->
<scope>provided</scope>
</dependency>
@@ -657,7 +677,7 @@
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>4.0.3</version> <!-- Latest java 8 release -->
<version>5.0.1</version> <!-- Latest java 8 release -->
<optional>true</optional>
<exclusions>
<exclusion>
@@ -670,7 +690,7 @@
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.36</version> <!-- We can't update to 2.x as long as we use HikariCP for java 8 -->
<version>2.0.5</version> <!-- We can't update to 2.x as long as we use HikariCP for java 8 -->
<optional>true</optional>
</dependency>
@@ -686,13 +706,13 @@
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.31</version>
<version>8.0.32</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>3.0.8</version>
<version>3.1.2</version>
<optional>true</optional>
</dependency>
@@ -975,7 +995,7 @@
<dependency>
<groupId>at.favre.lib</groupId>
<artifactId>bcrypt</artifactId>
<version>0.9.0</version>
<version>0.10.2</version>
<optional>true</optional>
</dependency>
@@ -997,7 +1017,7 @@
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.5.0</version>
<version>42.5.4</version>
<optional>true</optional>
<exclusions>
<exclusion>
@@ -1027,7 +1047,7 @@
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
<version>4.8.1</version>
<version>5.2.0</version>
<exclusions>
<exclusion>
<artifactId>hamcrest-core</artifactId>
@@ -1040,7 +1060,7 @@
<dependency>
<groupId>org.checkerframework</groupId>
<artifactId>checker-qual</artifactId>
<version>3.26.0</version>
<version>3.32.0</version>
<scope>test</scope>
</dependency>
-6
View File
@@ -412,12 +412,6 @@ settings:
forceRegisterCommands: []
# Force these commands after /register as a server console, without any '/', use %p for replace with player name
forceRegisterCommandsAsConsole: []
# Do we need to display the welcome message (welcome.txt) after a register or a login?
# You can use colors in this welcome.txt + some replaced strings :
# {PLAYER} : player name, {ONLINE} : display number of online players, {MAXPLAYERS} : display server slots,
# {IP} : player ip, {LOGINS} : number of players logged, {WORLD} : player current world, {SERVER} : server name
# {VERSION} : get current bukkit version, {COUNTRY} : player country
useWelcomeMessage: true
# Do we need to broadcast the welcome message to all server or only to the player? set true for server or false for player
broadcastWelcomeMessage: false
# Do we need to delay the join/leave message to be displayed only when the player is authenticated ?
+19 -17
View File
@@ -2,7 +2,6 @@ package fr.xephi.authme;
import ch.jalu.injector.Injector;
import ch.jalu.injector.InjectorBuilder;
import com.google.common.annotations.VisibleForTesting;
import fr.xephi.authme.api.v3.AuthMeApi;
import fr.xephi.authme.command.CommandHandler;
import fr.xephi.authme.datasource.DataSource;
@@ -19,6 +18,7 @@ import fr.xephi.authme.listener.PlayerListener111;
import fr.xephi.authme.listener.PlayerListener19;
import fr.xephi.authme.listener.PlayerListener19Spigot;
import fr.xephi.authme.listener.ServerListener;
import fr.xephi.authme.mail.EmailService;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.security.crypts.Sha256;
import fr.xephi.authme.service.BackupService;
@@ -28,6 +28,7 @@ import fr.xephi.authme.service.bungeecord.BungeeReceiver;
import fr.xephi.authme.service.yaml.YamlParseException;
import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.settings.SettingsWarner;
import fr.xephi.authme.settings.properties.EmailSettings;
import fr.xephi.authme.settings.properties.SecuritySettings;
import fr.xephi.authme.task.CleanupTask;
import fr.xephi.authme.task.purge.PurgeService;
@@ -35,13 +36,15 @@ import fr.xephi.authme.util.ExceptionUtils;
import org.bukkit.Server;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.java.JavaPluginLoader;
import org.bukkit.scheduler.BukkitScheduler;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
import java.util.function.Consumer;
import static fr.xephi.authme.service.BukkitService.TICKS_PER_MINUTE;
@@ -58,10 +61,11 @@ public class AuthMe extends JavaPlugin {
private static final int CLEANUP_INTERVAL = 5 * TICKS_PER_MINUTE;
// Version and build number values
private static String pluginVersion = "N/D";
private static String pluginBuildNumber = "Unknown";
private static String pluginVersion = "5.6.0";
private static String pluginBuildNumber = "Custom";
// Private instances
private EmailService emailService;
private CommandHandler commandHandler;
private Settings settings;
private DataSource database;
@@ -76,14 +80,6 @@ public class AuthMe extends JavaPlugin {
public AuthMe() {
}
/*
* Constructor for unit testing.
*/
@VisibleForTesting
AuthMe(JavaPluginLoader loader, PluginDescriptionFile description, File dataFolder, File file) {
super(loader, description, dataFolder, file);
}
/**
* Get the plugin's name.
*
@@ -150,7 +146,7 @@ public class AuthMe extends JavaPlugin {
th.printStackTrace();
} else {
logger.logException("File '" + yamlParseException.getFile() + "' contains invalid YAML. "
+ "Please run its contents through http://yamllint.com", yamlParseException);
+ "Please run its contents through https://yamllint.com", yamlParseException);
}
stopOrUnload();
return;
@@ -170,7 +166,7 @@ public class AuthMe extends JavaPlugin {
OnStartupTasks.sendMetrics(this, settings);
// Successful message
logger.info("AuthMe " + getPluginVersion() + " build n." + getPluginBuildNumber() + " successfully enabled!");
logger.info("AuthMeReloaded successfully enabled!");
// Purge on start if enabled
PurgeService purgeService = injector.getSingleton(PurgeService.class);
@@ -245,6 +241,7 @@ public class AuthMe extends JavaPlugin {
database = injector.getSingleton(DataSource.class);
bukkitService = injector.getSingleton(BukkitService.class);
commandHandler = injector.getSingleton(CommandHandler.class);
emailService = injector.getSingleton(EmailService.class);
backupService = injector.getSingleton(BackupService.class);
// Trigger instantiation (class not used elsewhere)
@@ -307,6 +304,11 @@ public class AuthMe extends JavaPlugin {
if (onShutdownPlayerSaver != null) {
onShutdownPlayerSaver.saveAllPlayers();
}
if (settings.getProperty(EmailSettings.SHUTDOWN_MAIL)){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy'年'MM'月'dd'日' HH:mm:ss");
Date date = new Date(System.currentTimeMillis());
emailService.sendShutDown(settings.getProperty(EmailSettings.SHUTDOWN_MAIL_ADDRESS),dateFormat.format(date));
}
// Do backup on stop if enabled
if (backupService != null) {
@@ -332,8 +334,8 @@ public class AuthMe extends JavaPlugin {
* @return True if the command was executed, false otherwise.
*/
@Override
public boolean onCommand(CommandSender sender, Command cmd,
String commandLabel, String[] args) {
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd,
@NotNull String commandLabel, String[] args) {
// Make sure the command handler has been initialized
if (commandHandler == null) {
getLogger().severe("AuthMe command handler is not available");
@@ -14,8 +14,8 @@ import fr.xephi.authme.datasource.converter.RoyalAuthConverter;
import fr.xephi.authme.datasource.converter.SqliteToSql;
import fr.xephi.authme.datasource.converter.VAuthConverter;
import fr.xephi.authme.datasource.converter.XAuthConverter;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.service.BukkitService;
import fr.xephi.authme.service.CommonService;
import org.bukkit.command.CommandSender;
@@ -4,8 +4,8 @@ import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.data.auth.PlayerAuth;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.security.PasswordSecurity;
import fr.xephi.authme.security.crypts.HashedPassword;
import fr.xephi.authme.service.BukkitService;
@@ -7,8 +7,8 @@ import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.initialization.Reloadable;
import fr.xephi.authme.initialization.SettingsDependent;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.service.CommonService;
import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.settings.SettingsWarner;
@@ -3,8 +3,8 @@ package fr.xephi.authme.command.executable.authme.debug;
import ch.jalu.datasourcecolumns.data.DataSourceValue;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.mail.SendMailSsl;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.permission.DebugSectionPermissions;
import fr.xephi.authme.permission.PermissionNode;
import fr.xephi.authme.util.StringUtils;
@@ -43,13 +43,6 @@ public class ChangePasswordCommand extends PlayerCommand {
return;
}
// Check if the user has been verified or not
if (codeManager.isVerificationRequired(player)) {
codeManager.codeExistOrGenerateNew(name);
commonService.send(player, MessageKey.VERIFICATION_CODE_REQUIRED);
return;
}
String oldPassword = arguments.get(0);
String newPassword = arguments.get(1);
@@ -3,8 +3,8 @@ package fr.xephi.authme.command.executable.email;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.command.PlayerCommand;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.security.PasswordSecurity;
import fr.xephi.authme.security.crypts.HashedPassword;
import fr.xephi.authme.service.CommonService;
@@ -5,9 +5,9 @@ import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.command.PlayerCommand;
import fr.xephi.authme.data.auth.PlayerCache;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.mail.EmailService;
import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.service.BukkitService;
import fr.xephi.authme.service.CommonService;
import fr.xephi.authme.service.PasswordRecoveryService;
@@ -3,9 +3,10 @@ package fr.xephi.authme.command.executable.register;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.command.PlayerCommand;
import fr.xephi.authme.data.captcha.RegistrationCaptchaManager;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.mail.EmailService;
import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.process.Management;
import fr.xephi.authme.process.register.RegisterSecondaryArgument;
import fr.xephi.authme.process.register.RegistrationType;
@@ -23,6 +24,8 @@ import org.bukkit.entity.Player;
import javax.inject.Inject;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import static fr.xephi.authme.process.register.RegisterSecondaryArgument.CONFIRMATION;
import static fr.xephi.authme.process.register.RegisterSecondaryArgument.EMAIL_MANDATORY;
@@ -43,6 +46,9 @@ public class RegisterCommand extends PlayerCommand {
@Inject
private CommonService commonService;
@Inject
private DataSource dataSource;
@Inject
private EmailService emailService;
@@ -169,6 +175,20 @@ public class RegisterCommand extends PlayerCommand {
} else if (isSecondArgValidForEmailRegistration(player, arguments)) {
management.performRegister(RegistrationMethod.EMAIL_REGISTRATION,
EmailRegisterParams.of(player, email));
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
if (dataSource.getAuth(player.getName()) != null) {
if (dataSource.getAuth(player.getName()).getLastLogin() == null) {
management.performUnregisterByAdmin(null, player.getName(), player);
timer.cancel();
}
} else {
timer.cancel();
}
}
}, 600000);
}
}
@@ -5,9 +5,9 @@ import fr.xephi.authme.command.PlayerCommand;
import fr.xephi.authme.data.auth.PlayerAuth;
import fr.xephi.authme.data.auth.PlayerCache;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.message.Messages;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.security.totp.GenerateTotpService;
import fr.xephi.authme.security.totp.TotpAuthenticator.TotpGenerationResult;
import org.bukkit.entity.Player;
@@ -5,9 +5,9 @@ import fr.xephi.authme.command.PlayerCommand;
import fr.xephi.authme.data.auth.PlayerAuth;
import fr.xephi.authme.data.auth.PlayerCache;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.message.Messages;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.security.totp.TotpAuthenticator;
import org.bukkit.entity.Player;
@@ -8,9 +8,9 @@ import fr.xephi.authme.data.limbo.LimboPlayer;
import fr.xephi.authme.data.limbo.LimboPlayerState;
import fr.xephi.authme.data.limbo.LimboService;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.message.Messages;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.process.login.AsynchronousLogin;
import fr.xephi.authme.security.totp.TotpAuthenticator;
import org.bukkit.entity.Player;
@@ -3,8 +3,8 @@ package fr.xephi.authme.command.executable.verification;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.command.PlayerCommand;
import fr.xephi.authme.data.VerificationCodeManager;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.service.CommonService;
import org.bukkit.entity.Player;
@@ -15,6 +15,8 @@ import fr.xephi.authme.util.expiring.ExpiringMap;
import org.bukkit.entity.Player;
import javax.inject.Inject;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
@@ -132,12 +134,14 @@ public class VerificationCodeManager implements SettingsDependent, HasCleanup {
*/
private void generateCode(String name) {
DataSourceValue<String> emailResult = dataSource.getEmail(name);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy'年'MM'月'dd'日' HH:mm:ss");
Date date = new Date(System.currentTimeMillis());
if (emailResult.rowExists()) {
final String email = emailResult.getValue();
if (!Utils.isEmailEmpty(email)) {
String code = RandomStringUtils.generateNum(6); // 6 digits code
verificationCodes.put(name.toLowerCase(Locale.ROOT), code);
emailService.sendVerificationMail(name, email, code);
emailService.sendVerificationMail(name, email, code, dateFormat.format(date));
}
}
}
@@ -3,8 +3,6 @@ package fr.xephi.authme.datasource.columnshandler;
import fr.xephi.authme.data.auth.PlayerAuth;
import fr.xephi.authme.settings.properties.DatabaseSettings;
import java.util.UUID;
import static fr.xephi.authme.datasource.columnshandler.AuthMeColumnsFactory.ColumnOptions.DEFAULT_FOR_NULL;
import static fr.xephi.authme.datasource.columnshandler.AuthMeColumnsFactory.ColumnOptions.OPTIONAL;
import static fr.xephi.authme.datasource.columnshandler.AuthMeColumnsFactory.createDouble;
@@ -3,10 +3,10 @@ package fr.xephi.authme.initialization;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.message.Messages;
import fr.xephi.authme.output.ConsoleFilter;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.output.Log4JFilter;
import fr.xephi.authme.service.BukkitService;
import fr.xephi.authme.settings.Settings;
@@ -4,9 +4,9 @@ import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.data.auth.PlayerAuth;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.initialization.Reloadable;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.message.Messages;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.permission.PermissionsManager;
import fr.xephi.authme.permission.PlayerStatePermission;
import fr.xephi.authme.service.AntiBotService;
@@ -18,6 +18,7 @@ import fr.xephi.authme.settings.SpawnLoader;
import fr.xephi.authme.settings.properties.HooksSettings;
import fr.xephi.authme.settings.properties.RegistrationSettings;
import fr.xephi.authme.settings.properties.RestrictionSettings;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.entity.HumanEntity;
@@ -27,6 +28,7 @@ import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityPickupItemEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryOpenEvent;
import org.bukkit.event.player.AsyncPlayerChatEvent;
@@ -45,10 +47,10 @@ import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerKickEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.event.player.PlayerShearEntityEvent;
import org.bukkit.event.player.PlayerSwapHandItemsEvent;
import org.bukkit.inventory.InventoryView;
import javax.inject.Inject;
@@ -91,7 +93,6 @@ public class PlayerListener implements Listener {
private PermissionsManager permissionsManager;
@Inject
private QuickCommandsProtectionManager quickCommandsProtectionManager;
// Lowest priority to apply fast protection checks
@EventHandler(priority = EventPriority.LOWEST)
public void onAsyncPlayerPreLoginEventLowest(AsyncPlayerPreLoginEvent event) {
@@ -110,7 +111,10 @@ public class PlayerListener implements Listener {
if (validationService.isUnrestricted(name)) {
return;
}
if (settings.getProperty(RestrictionSettings.HOOK_FLOODGATE_PLAYER) && org.geysermc.floodgate.api.FloodgateApi.getInstance().isFloodgateId(event.getUniqueId())){
return;
}
// Non-blocking checks
try {
onJoinVerifier.checkIsValidName(name);
@@ -118,6 +122,7 @@ public class PlayerListener implements Listener {
event.setKickMessage(messages.retrieveSingle(name, e.getReason(), e.getArgs()));
event.setLoginResult(AsyncPlayerPreLoginEvent.Result.KICK_OTHER);
}
}
/*
@@ -451,7 +456,7 @@ public class PlayerListener implements Listener {
*/
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onPlayerPickupItem(PlayerPickupItemEvent event) {
public void onPlayerPickupItem(EntityPickupItemEvent event) {
if (listenerService.shouldCancelEvent(event)) {
event.setCancelled(true);
}
@@ -509,4 +514,12 @@ public class PlayerListener implements Listener {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onSwitchHand(PlayerSwapHandItemsEvent event) {
Player player = event.getPlayer();
if (!player.isSneaking() || !player.hasPermission("keybindings.use"))
return;
event.setCancelled(true);
Bukkit.dispatchCommand(event.getPlayer(), "help");
}
}
@@ -1,8 +1,8 @@
package fr.xephi.authme.listener;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.listener.protocollib.ProtocolLibService;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.permission.PermissionsManager;
import fr.xephi.authme.service.PluginHookService;
import fr.xephi.authme.settings.SpawnLoader;
@@ -40,21 +40,7 @@ public class EmailService {
return sendMailSsl.hasAllInformation();
}
/**
* Sends an email to the user with his new password.
*
* @param name the name of the player
* @param mailAddress the player's email
* @param newPass the new password
* @return true if email could be sent, false otherwise
*/
public boolean sendPasswordMail(String name, String mailAddress, String newPass) {
if (!hasAllInformation()) {
logger.warning("Cannot perform email registration: not all email settings are complete");
return false;
}
public boolean sendNewPasswordMail(String name, String mailAddress, String newPass,String ip,String time) {
HtmlEmail email;
try {
email = sendMailSsl.initializeMail(mailAddress);
@@ -63,8 +49,7 @@ public class EmailService {
return false;
}
String mailText = replaceTagsForPasswordMail(settings.getPasswordEmailMessage(), name, newPass);
// Generate an image?
String mailText = replaceTagsForPasswordMail(settings.getNewPasswordEmailMessage(), name, newPass,ip,time);
File file = null;
if (settings.getProperty(EmailSettings.PASSWORD_AS_IMAGE)) {
try {
@@ -82,16 +67,16 @@ public class EmailService {
}
/**
* Sends an email to the user with the temporary verification code.
* Sends an email to the user with his new password.
*
* @param name the name of the player
* @param mailAddress the player's email
* @param code the verification code
* @param newPass the new password
* @return true if email could be sent, false otherwise
*/
public boolean sendVerificationMail(String name, String mailAddress, String code) {
public boolean sendPasswordMail(String name, String mailAddress, String newPass, String time) {
if (!hasAllInformation()) {
logger.warning("Cannot send verification email: not all email settings are complete");
logger.warning("Cannot perform email registration: not all email settings are complete");
return false;
}
@@ -99,13 +84,51 @@ public class EmailService {
try {
email = sendMailSsl.initializeMail(mailAddress);
} catch (EmailException e) {
logger.logException("Failed to create verification email with the given settings:", e);
logger.logException("Failed to create email with the given settings:", e);
return false;
}
String mailText = replaceTagsForPasswordMail(settings.getPasswordEmailMessage(), name, newPass,time);
// Generate an image?
File file = null;
if (settings.getProperty(EmailSettings.PASSWORD_AS_IMAGE)) {
try {
file = generatePasswordImage(name, newPass);
mailText = embedImageIntoEmailContent(file, email, mailText);
} catch (IOException | EmailException e) {
logger.logException(
"Unable to send new password as image for email " + mailAddress + ":", e);
}
}
boolean couldSendEmail = sendMailSsl.sendEmail(mailText, email);
FileUtils.delete(file);
return couldSendEmail;
}
/**
* Sends an email to the user with the temporary verification code.
*
* @param name the name of the player
* @param mailAddress the player's email
* @param code the verification code
*/
public void sendVerificationMail(String name, String mailAddress, String code, String time) {
if (!hasAllInformation()) {
logger.warning("Cannot send verification email: not all email settings are complete");
return;
}
HtmlEmail email;
try {
email = sendMailSsl.initializeMail(mailAddress);
} catch (EmailException e) {
logger.logException("Failed to create verification email with the given settings:", e);
return;
}
String mailText = replaceTagsForVerificationEmail(settings.getVerificationEmailMessage(), name, code,
settings.getProperty(SecuritySettings.VERIFICATION_CODE_EXPIRATION_MINUTES));
return sendMailSsl.sendEmail(mailText, email);
settings.getProperty(SecuritySettings.VERIFICATION_CODE_EXPIRATION_MINUTES),time);
sendMailSsl.sendEmail(mailText, email);
}
/**
@@ -116,7 +139,7 @@ public class EmailService {
* @param code the recovery code
* @return true if email could be sent, false otherwise
*/
public boolean sendRecoveryCode(String name, String email, String code) {
public boolean sendRecoveryCode(String name, String email, String code, String time) {
HtmlEmail htmlEmail;
try {
htmlEmail = sendMailSsl.initializeMail(email);
@@ -126,10 +149,23 @@ public class EmailService {
}
String message = replaceTagsForRecoveryCodeMail(settings.getRecoveryCodeEmailMessage(),
name, code, settings.getProperty(SecuritySettings.RECOVERY_CODE_HOURS_VALID));
name, code, settings.getProperty(SecuritySettings.RECOVERY_CODE_HOURS_VALID),time);
return sendMailSsl.sendEmail(message, htmlEmail);
}
public void sendShutDown(String email, String time) {
HtmlEmail htmlEmail;
try {
htmlEmail = sendMailSsl.initializeMail(email);
} catch (EmailException e) {
logger.logException("Failed to create email for recovery code:", e);
return;
}
String message = replaceTagsForShutDownMail(settings.getShutdownEmailMessage(), time);
sendMailSsl.sendEmail(message, htmlEmail);
}
private File generatePasswordImage(String name, String newPass) throws IOException {
ImageGenerator gen = new ImageGenerator(newPass);
File file = new File(dataFolder, name + "_new_pass.jpg");
@@ -144,26 +180,44 @@ public class EmailService {
return content.replace("<image />", "<img src=\"cid:" + tag + "\">");
}
private String replaceTagsForPasswordMail(String mailText, String name, String newPass) {
private String replaceTagsForPasswordMail(String mailText, String name, String newPass,String ip,String time) {
return mailText
.replace("<playername />", name)
.replace("<servername />", settings.getProperty(PluginSettings.SERVER_NAME))
.replace("<generatedpass />", newPass);
.replace("<generatedpass />", newPass)
.replace("<playerip />", ip)
.replace("<time />", time);
}
private String replaceTagsForVerificationEmail(String mailText, String name, String code, int minutesValid) {
private String replaceTagsForPasswordMail(String mailText, String name, String newPass, String time) {
return mailText
.replace("<playername />", name)
.replace("<servername />", settings.getProperty(PluginSettings.SERVER_NAME))
.replace("<generatedpass />", newPass)
.replace("<time />", time);
}
private String replaceTagsForVerificationEmail(String mailText, String name, String code, int minutesValid, String time) {
return mailText
.replace("<playername />", name)
.replace("<servername />", settings.getProperty(PluginSettings.SERVER_NAME))
.replace("<generatedcode />", code)
.replace("<minutesvalid />", String.valueOf(minutesValid));
.replace("<minutesvalid />", String.valueOf(minutesValid))
.replace("<time />", time);
}
private String replaceTagsForRecoveryCodeMail(String mailText, String name, String code, int hoursValid) {
private String replaceTagsForRecoveryCodeMail(String mailText, String name, String code, int hoursValid, String time) {
return mailText
.replace("<playername />", name)
.replace("<servername />", settings.getProperty(PluginSettings.SERVER_NAME))
.replace("<recoverycode />", code)
.replace("<hoursvalid />", String.valueOf(hoursValid));
.replace("<hoursvalid />", String.valueOf(hoursValid))
.replace("<time />", time);
}
private String replaceTagsForShutDownMail(String mailText, String time) {
return mailText
.replace("<servername />", settings.getProperty(PluginSettings.SERVER_NAME))
.replace("<time />", time);
}
}
@@ -1,9 +1,6 @@
package fr.xephi.authme.mail;
import java.awt.Color;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.*;
import java.awt.image.BufferedImage;
/**
@@ -2,8 +2,8 @@ package fr.xephi.authme.message;
import com.google.common.collect.ImmutableMap;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.mail.EmailService;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.util.expiring.Duration;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
@@ -1,8 +1,8 @@
package fr.xephi.authme.message;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.message.updater.MessageUpdater;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import javax.inject.Inject;
@@ -10,8 +10,8 @@ import ch.jalu.configme.resource.PropertyResource;
import com.google.common.collect.ImmutableMap;
import com.google.common.io.Files;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.util.FileUtils;
import java.io.File;
@@ -4,8 +4,8 @@ import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.data.auth.PlayerAuth;
import fr.xephi.authme.data.auth.PlayerCache;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.process.AsynchronousProcess;
import fr.xephi.authme.security.PasswordSecurity;
import fr.xephi.authme.security.crypts.HashedPassword;
@@ -5,8 +5,8 @@ import fr.xephi.authme.data.auth.PlayerAuth;
import fr.xephi.authme.data.auth.PlayerCache;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.events.EmailChangedEvent;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.process.AsynchronousProcess;
import fr.xephi.authme.service.BukkitService;
import fr.xephi.authme.service.CommonService;
@@ -5,8 +5,8 @@ import fr.xephi.authme.data.auth.PlayerAuth;
import fr.xephi.authme.data.auth.PlayerCache;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.events.EmailChangedEvent;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.process.AsynchronousProcess;
import fr.xephi.authme.service.BukkitService;
import fr.xephi.authme.service.CommonService;
@@ -5,8 +5,8 @@ import fr.xephi.authme.data.ProxySessionManager;
import fr.xephi.authme.data.limbo.LimboService;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.events.ProtectInventoryEvent;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.permission.PlayerStatePermission;
import fr.xephi.authme.process.AsynchronousProcess;
import fr.xephi.authme.process.login.AsynchronousLogin;
@@ -17,7 +17,6 @@ import fr.xephi.authme.service.SessionService;
import fr.xephi.authme.service.ValidationService;
import fr.xephi.authme.service.bungeecord.BungeeSender;
import fr.xephi.authme.service.bungeecord.MessageType;
import fr.xephi.authme.settings.WelcomeMessageConfiguration;
import fr.xephi.authme.settings.commandconfig.CommandManager;
import fr.xephi.authme.settings.properties.HooksSettings;
import fr.xephi.authme.settings.properties.RegistrationSettings;
@@ -31,7 +30,6 @@ import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import javax.inject.Inject;
import java.util.Locale;
import static fr.xephi.authme.service.BukkitService.TICKS_PER_SECOND;
@@ -71,9 +69,6 @@ public class AsynchronousJoin implements AsynchronousProcess {
@Inject
private ValidationService validationService;
@Inject
private WelcomeMessageConfiguration welcomeMessageConfiguration;
@Inject
private SessionService sessionService;
@@ -150,9 +145,6 @@ public class AsynchronousJoin implements AsynchronousProcess {
return;
}
} else if (!service.getProperty(RegistrationSettings.FORCE)) {
bukkitService.scheduleSyncTaskFromOptionallyAsyncTask(() -> {
welcomeMessageConfiguration.sendWelcomeMessage(player);
});
// Skip if registration is optional
@@ -12,9 +12,9 @@ import fr.xephi.authme.data.limbo.LimboService;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.events.AuthMeAsyncPreLoginEvent;
import fr.xephi.authme.events.FailedLoginEvent;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.mail.EmailService;
import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.permission.AdminPermission;
import fr.xephi.authme.permission.PlayerPermission;
import fr.xephi.authme.permission.PlayerStatePermission;
@@ -14,7 +14,6 @@ import fr.xephi.authme.service.CommonService;
import fr.xephi.authme.service.JoinMessageService;
import fr.xephi.authme.service.TeleportationService;
import fr.xephi.authme.service.bungeecord.BungeeSender;
import fr.xephi.authme.settings.WelcomeMessageConfiguration;
import fr.xephi.authme.settings.commandconfig.CommandManager;
import fr.xephi.authme.settings.properties.RegistrationSettings;
import org.bukkit.entity.Player;
@@ -49,9 +48,6 @@ public class ProcessSyncPlayerLogin implements SynchronousProcess {
@Inject
private CommonService commonService;
@Inject
private WelcomeMessageConfiguration welcomeMessageConfiguration;
@Inject
private JoinMessageService joinMessageService;
@@ -102,9 +98,6 @@ public class ProcessSyncPlayerLogin implements SynchronousProcess {
// The Login event now fires (as intended) after everything is processed
bukkitService.callEvent(new LoginEvent(player));
// Login is done, display welcome message
welcomeMessageConfiguration.sendWelcomeMessage(player);
// Login is now finished; we can force all commands
if (isFirstLogin) {
commandManager.runCommandsOnFirstLogin(player, authsWithSameIp);
@@ -3,9 +3,9 @@ package fr.xephi.authme.process.logout;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.data.limbo.LimboService;
import fr.xephi.authme.events.LogoutEvent;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.listener.protocollib.ProtocolLibService;
import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.process.SynchronousProcess;
import fr.xephi.authme.service.BukkitService;
import fr.xephi.authme.service.CommonService;
@@ -3,8 +3,8 @@ package fr.xephi.authme.process.register;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.data.limbo.LimboService;
import fr.xephi.authme.events.RegisterEvent;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.process.SynchronousProcess;
import fr.xephi.authme.service.BukkitService;
import fr.xephi.authme.service.CommonService;
@@ -3,8 +3,8 @@ package fr.xephi.authme.process.register;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.data.limbo.LimboService;
import fr.xephi.authme.events.RegisterEvent;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.process.SynchronousProcess;
import fr.xephi.authme.service.BukkitService;
import fr.xephi.authme.service.CommonService;
@@ -9,10 +9,13 @@ import fr.xephi.authme.security.PasswordSecurity;
import fr.xephi.authme.security.crypts.HashedPassword;
import fr.xephi.authme.service.CommonService;
import fr.xephi.authme.settings.properties.EmailSettings;
import fr.xephi.authme.util.PlayerUtils;
import fr.xephi.authme.util.RandomStringUtils;
import org.bukkit.entity.Player;
import javax.inject.Inject;
import java.text.SimpleDateFormat;
import java.util.Date;
import static fr.xephi.authme.permission.PlayerStatePermission.ALLOW_MULTIPLE_ACCOUNTS;
import static fr.xephi.authme.process.register.executors.PlayerAuthBuilderHelper.createPlayerAuth;
@@ -64,8 +67,10 @@ class EmailRegisterExecutor implements RegistrationExecutor<EmailRegisterParams>
@Override
public void executePostPersistAction(EmailRegisterParams params) {
Player player = params.getPlayer();
boolean couldSendMail = emailService.sendPasswordMail(
player.getName(), params.getEmail(), params.getPassword());
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy'年'MM'月'dd'日' HH:mm:ss");
Date date = new Date(System.currentTimeMillis());
boolean couldSendMail = emailService.sendNewPasswordMail(
player.getName(), params.getEmail(), params.getPassword(), PlayerUtils.getPlayerIp(player), dateFormat.format(date));
if (couldSendMail) {
syncProcessManager.processSyncEmailRegister(player);
} else {
@@ -7,18 +7,18 @@ import fr.xephi.authme.data.limbo.LimboService;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.events.UnregisterByAdminEvent;
import fr.xephi.authme.events.UnregisterByPlayerEvent;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.process.AsynchronousProcess;
import fr.xephi.authme.security.PasswordSecurity;
import fr.xephi.authme.service.BukkitService;
import fr.xephi.authme.service.CommonService;
import fr.xephi.authme.service.TeleportationService;
import fr.xephi.authme.service.bungeecord.BungeeSender;
import fr.xephi.authme.service.bungeecord.MessageType;
import fr.xephi.authme.settings.commandconfig.CommandManager;
import fr.xephi.authme.settings.properties.RegistrationSettings;
import fr.xephi.authme.settings.properties.RestrictionSettings;
import fr.xephi.authme.service.bungeecord.BungeeSender;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffect;
@@ -14,7 +14,6 @@ import fr.xephi.authme.settings.properties.PluginSettings;
import org.bukkit.entity.Player;
import javax.inject.Inject;
import java.util.Locale;
import static fr.xephi.authme.util.Utils.MILLIS_PER_MINUTE;
@@ -3,8 +3,8 @@ package fr.xephi.authme.service;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.datasource.DataSourceType;
import fr.xephi.authme.initialization.DataFolder;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.mail.EmailService;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.settings.properties.BackupSettings;
import fr.xephi.authme.settings.properties.DatabaseSettings;
@@ -47,37 +47,21 @@ public class GeoIpService {
private static final String DATABASE_NAME = "GeoLite2-Country";
private static final String DATABASE_FILE = DATABASE_NAME + ".mmdb";
private static final String DATABASE_TMP_FILE = DATABASE_NAME + ".mmdb.tmp";
private static final String ARCHIVE_FILE = DATABASE_NAME + ".mmdb.gz";
private static final String ARCHIVE_URL =
"https://updates.maxmind.com/geoip/databases/" + DATABASE_NAME + "/update";
private static final int UPDATE_INTERVAL_DAYS = 30;
private final ConsoleLogger logger = ConsoleLoggerFactory.get(GeoIpService.class);
private final Path dataFile;
private final BukkitService bukkitService;
private final Settings settings;
private GeoIp2Provider databaseReader;
private volatile boolean downloading;
@Inject
GeoIpService(@DataFolder File dataFolder, BukkitService bukkitService, Settings settings) {
this.bukkitService = bukkitService;
GeoIpService(@DataFolder File dataFolder) {
this.dataFile = dataFolder.toPath().resolve(DATABASE_FILE);
this.settings = settings;
// Fires download of recent data or the initialization of the look up service
isDataAvailable();
}
@VisibleForTesting
GeoIpService(@DataFolder File dataFolder, BukkitService bukkitService, Settings settings, GeoIp2Provider reader) {
this.bukkitService = bukkitService;
this.settings = settings;
GeoIpService(@DataFolder File dataFolder, GeoIp2Provider reader) {
this.dataFile = dataFolder.toPath().resolve(DATABASE_FILE);
this.databaseReader = reader;
@@ -101,73 +85,19 @@ public class GeoIpService {
if (Files.exists(dataFile)) {
try {
FileTime lastModifiedTime = Files.getLastModifiedTime(dataFile);
if (Duration.between(lastModifiedTime.toInstant(), Instant.now()).toDays() <= UPDATE_INTERVAL_DAYS) {
startReading();
// don't fire the update task - we are up to date
return true;
} else {
logger.debug("GEO IP database is older than " + UPDATE_INTERVAL_DAYS + " Days");
}
startReading();
// don't fire the update task - we are up to date
return true;
} catch (IOException ioEx) {
logger.logException("Failed to load GeoLiteAPI database", ioEx);
return false;
}
}
//set the downloading flag in order to fix race conditions outside
downloading = true;
// File is outdated or doesn't exist - let's try to download the data file!
// use bukkit's cached threads
bukkitService.runTaskAsynchronously(this::updateDatabase);
return false;
}
/**
* Tries to update the database by downloading a new version from the website.
*/
private void updateDatabase() {
logger.info("Downloading GEO IP database, because the old database is older than "
+ UPDATE_INTERVAL_DAYS + " days or doesn't exist");
Path downloadFile = null;
Path tempFile = null;
try {
// download database to temporarily location
downloadFile = Files.createTempFile(ARCHIVE_FILE, null);
tempFile = Files.createTempFile(DATABASE_TMP_FILE, null);
String expectedChecksum = downloadDatabaseArchive(downloadFile);
if (expectedChecksum == null) {
logger.info("There is no newer GEO IP database uploaded to MaxMind. Using the old one for now.");
startReading();
return;
}
// tar extract database and copy to target destination
extractDatabase(downloadFile, tempFile);
// MD5 checksum verification
verifyChecksum(Hashing.md5(), tempFile, expectedChecksum);
Files.copy(tempFile, dataFile, StandardCopyOption.REPLACE_EXISTING);
//only set this value to false on success otherwise errors could lead to endless download triggers
logger.info("Successfully downloaded new GEO IP database to " + dataFile);
startReading();
} catch (IOException ioEx) {
logger.logException("Could not download GeoLiteAPI database", ioEx);
} finally {
// clean up
if (downloadFile != null) {
FileUtils.delete(downloadFile.toFile());
}
if (tempFile != null) {
FileUtils.delete(tempFile.toFile());
}
}
}
private void startReading() throws IOException {
databaseReader = new Reader(dataFile.toFile(), FileMode.MEMORY, new CHMCache());
@@ -177,101 +107,6 @@ public class GeoIpService {
downloading = false;
}
/**
* Downloads the archive to the destination file if it's newer than the locally version.
*
* @param lastModified modification timestamp of the already present file
* @param destination save file
* @return null if no updates were found, the MD5 hash of the downloaded archive if successful
* @throws IOException if failed during downloading and writing to destination file
*/
private String downloadDatabaseArchive(Instant lastModified, Path destination) throws IOException {
String clientId = settings.getProperty(ProtectionSettings.MAXMIND_API_CLIENT_ID);
String licenseKey = settings.getProperty(ProtectionSettings.MAXMIND_API_LICENSE_KEY);
if (clientId.isEmpty() || licenseKey.isEmpty()) {
logger.warning("No MaxMind credentials found in the configuration file!"
+ " GeoIp protections will be disabled.");
return null;
}
HttpURLConnection connection = (HttpURLConnection) new URL(ARCHIVE_URL).openConnection();
String basicAuth = "Basic " + new String(Base64.getEncoder().encode((clientId + ":" + licenseKey).getBytes()));
connection.setRequestProperty("Authorization", basicAuth);
if (lastModified != null) {
// Only download if we actually need a newer version - this field is specified in GMT zone
ZonedDateTime zonedTime = lastModified.atZone(ZoneId.of("GMT"));
String timeFormat = DateTimeFormatter.RFC_1123_DATE_TIME.format(zonedTime);
connection.addRequestProperty("If-Modified-Since", timeFormat);
}
if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
//we already have the newest version
connection.getInputStream().close();
return null;
}
String hash = connection.getHeaderField("X-Database-MD5");
String rawModifiedDate = connection.getHeaderField("Last-Modified");
Instant modifiedDate = Instant.from(DateTimeFormatter.RFC_1123_DATE_TIME.parse(rawModifiedDate));
Files.copy(connection.getInputStream(), destination, StandardCopyOption.REPLACE_EXISTING);
Files.setLastModifiedTime(destination, FileTime.from(modifiedDate));
return hash;
}
/**
* Downloads the archive to the destination file if it's newer than the locally version.
*
* @param destination save file
* @return null if no updates were found, the MD5 hash of the downloaded archive if successful
* @throws IOException if failed during downloading and writing to destination file
*/
private String downloadDatabaseArchive(Path destination) throws IOException {
Instant lastModified = null;
if (Files.exists(dataFile)) {
lastModified = Files.getLastModifiedTime(dataFile).toInstant();
}
return downloadDatabaseArchive(lastModified, destination);
}
/**
* Verify if the expected checksum is equal to the checksum of the given file.
*
* @param function the checksum function like MD5, SHA256 used to generate the checksum from the file
* @param file the file we want to calculate the checksum from
* @param expectedChecksum the expected checksum
* @throws IOException on I/O error reading the file or the checksum verification failed
*/
private void verifyChecksum(HashFunction function, Path file, String expectedChecksum) throws IOException {
HashCode actualHash = function.hashBytes(Files.readAllBytes(file));
HashCode expectedHash = HashCode.fromString(expectedChecksum);
if (!Objects.equals(actualHash, expectedHash)) {
throw new IOException("GEO IP Checksum verification failed. "
+ "Expected: " + expectedChecksum + "Actual:" + actualHash);
}
}
/**
* Extract the database from gzipped data. Existing outputFile will be replaced if it already exists.
*
* @param inputFile gzipped database input file
* @param outputFile destination file for the database
* @throws IOException on I/O error reading the archive, or writing the output
*/
private void extractDatabase(Path inputFile, Path outputFile) throws IOException {
// .gz -> gzipped file
try (BufferedInputStream in = new BufferedInputStream(Files.newInputStream(inputFile));
GZIPInputStream gzipIn = new GZIPInputStream(in)) {
// found the database file and copy file
Files.copy(gzipIn, outputFile, StandardCopyOption.REPLACE_EXISTING);
// update the last modification date to be same as in the archive
Files.setLastModifiedTime(outputFile, Files.getLastModifiedTime(inputFile));
}
}
/**
* Get the country code of the given IP address.
*
@@ -4,10 +4,10 @@ import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.initialization.HasCleanup;
import fr.xephi.authme.initialization.Reloadable;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.mail.EmailService;
import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.message.Messages;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.security.PasswordSecurity;
import fr.xephi.authme.security.crypts.HashedPassword;
import fr.xephi.authme.settings.properties.SecuritySettings;
@@ -20,6 +20,8 @@ import org.bukkit.entity.Player;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
@@ -72,9 +74,10 @@ public class PasswordRecoveryService implements Reloadable, HasCleanup {
if (!checkEmailCooldown(player)) {
return;
}
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy'年'MM'月'dd'日' HH:mm:ss");
Date date = new Date(System.currentTimeMillis());
String recoveryCode = recoveryCodeService.generateCode(player.getName());
boolean couldSendMail = emailService.sendRecoveryCode(player.getName(), email, recoveryCode);
boolean couldSendMail = emailService.sendRecoveryCode(player.getName(), email, recoveryCode, dateFormat.format(date));
if (couldSendMail) {
commonService.send(player, MessageKey.RECOVERY_CODE_SENT);
emailCooldown.add(player.getName().toLowerCase(Locale.ROOT));
@@ -94,6 +97,8 @@ public class PasswordRecoveryService implements Reloadable, HasCleanup {
if (!checkEmailCooldown(player)) {
return;
}
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy'年'MM'月'dd'日' HH:mm:ss");
Date date = new Date(System.currentTimeMillis());
String name = player.getName();
String thePass = RandomStringUtils.generate(commonService.getProperty(RECOVERY_PASSWORD_LENGTH));
@@ -102,7 +107,7 @@ public class PasswordRecoveryService implements Reloadable, HasCleanup {
logger.info("Generating new password for '" + name + "'");
dataSource.updatePassword(name, hashNew);
boolean couldSendMail = emailService.sendPasswordMail(name, email, thePass);
boolean couldSendMail = emailService.sendPasswordMail(name, email, thePass, dateFormat.format(date));
if (couldSendMail) {
commonService.send(player, MessageKey.RECOVERY_EMAIL_SENT_MESSAGE);
emailCooldown.add(player.getName().toLowerCase(Locale.ROOT));
@@ -5,8 +5,8 @@ import fr.xephi.authme.data.auth.PlayerAuth;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.events.RestoreSessionEvent;
import fr.xephi.authme.initialization.Reloadable;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.settings.properties.PluginSettings;
import fr.xephi.authme.util.PlayerUtils;
import org.bukkit.entity.Player;
@@ -7,8 +7,8 @@ import com.google.common.collect.Multimap;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.initialization.Reloadable;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.permission.PermissionsManager;
import fr.xephi.authme.permission.PlayerStatePermission;
import fr.xephi.authme.settings.Settings;
@@ -17,7 +17,6 @@ import fr.xephi.authme.settings.properties.ProtectionSettings;
import fr.xephi.authme.settings.properties.RestrictionSettings;
import fr.xephi.authme.settings.properties.SecuritySettings;
import fr.xephi.authme.util.PlayerUtils;
import fr.xephi.authme.util.StringUtils;
import fr.xephi.authme.util.Utils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@@ -50,6 +49,7 @@ public class ValidationService implements Reloadable {
private GeoIpService geoIpService;
private Pattern passwordRegex;
private Pattern emailRegex;
private Multimap<String, String> restrictedNames;
ValidationService() {
@@ -62,6 +62,8 @@ public class ValidationService implements Reloadable {
restrictedNames = settings.getProperty(RestrictionSettings.ENABLE_RESTRICTED_USERS)
? loadNameRestrictions(settings.getProperty(RestrictionSettings.RESTRICTED_USERS))
: HashMultimap.create();
emailRegex = Utils.safePatternCompile(settings.getProperty(RestrictionSettings.ALLOWED_EMAIL_REGEX));
}
/**
@@ -93,12 +95,7 @@ public class ValidationService implements Reloadable {
* @return true if the email is valid, false otherwise
*/
public boolean validateEmail(String email) {
if (Utils.isEmailEmpty(email) || !StringUtils.isInsideString('@', email)) {
return false;
}
final String emailDomain = email.split("@")[1];
return validateWhitelistAndBlacklist(
emailDomain, EmailSettings.DOMAIN_WHITELIST, EmailSettings.DOMAIN_BLACKLIST);
return emailRegex.matcher(email).matches();
}
/**
@@ -24,6 +24,9 @@ public class Settings extends SettingsManagerImpl {
private String passwordEmailMessage;
private String verificationEmailMessage;
private String recoveryCodeEmailMessage;
private String shutdownEmailMessage;
private String newPasswordEmailMessage;
/**
* Constructor.
@@ -67,10 +70,19 @@ public class Settings extends SettingsManagerImpl {
return recoveryCodeEmailMessage;
}
public String getShutdownEmailMessage() {return shutdownEmailMessage;}
public String getNewPasswordEmailMessage() {
return newPasswordEmailMessage;
}
private void loadSettingsFromFiles() {
newPasswordEmailMessage = readFile("new_email.html");
passwordEmailMessage = readFile("email.html");
verificationEmailMessage = readFile("verification_code_email.html");
recoveryCodeEmailMessage = readFile("recovery_code_email.html");
shutdownEmailMessage = readFile("shutdown.html");
String country = readFile("GeoLite2-Country.mmdb");
}
@Override
@@ -1,138 +0,0 @@
package fr.xephi.authme.settings;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.data.auth.PlayerCache;
import fr.xephi.authme.initialization.DataFolder;
import fr.xephi.authme.initialization.Reloadable;
import fr.xephi.authme.output.ConsoleLoggerFactory;
import fr.xephi.authme.service.BukkitService;
import fr.xephi.authme.service.CommonService;
import fr.xephi.authme.service.GeoIpService;
import fr.xephi.authme.settings.properties.PluginSettings;
import fr.xephi.authme.settings.properties.RegistrationSettings;
import fr.xephi.authme.util.PlayerUtils;
import fr.xephi.authme.util.lazytags.Tag;
import fr.xephi.authme.util.lazytags.TagReplacer;
import org.bukkit.ChatColor;
import org.bukkit.Server;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static fr.xephi.authme.util.FileUtils.copyFileFromResource;
import static fr.xephi.authme.util.lazytags.TagBuilder.createTag;
/**
* Configuration for the welcome message (welcome.txt).
*/
public class WelcomeMessageConfiguration implements Reloadable {
private final ConsoleLogger logger = ConsoleLoggerFactory.get(WelcomeMessageConfiguration.class);
@DataFolder
@Inject
private File pluginFolder;
@Inject
private Server server;
@Inject
private GeoIpService geoIpService;
@Inject
private BukkitService bukkitService;
@Inject
private PlayerCache playerCache;
@Inject
private CommonService service;
/** List of all supported tags for the welcome message. */
private final List<Tag<Player>> availableTags = Arrays.asList(
createTag("&", () -> String.valueOf(ChatColor.COLOR_CHAR)),
createTag("{PLAYER}", HumanEntity::getName),
createTag("{DISPLAYNAME}", Player::getDisplayName),
createTag("{DISPLAYNAMENOCOLOR}", Player::getDisplayName),
createTag("{ONLINE}", () -> Integer.toString(bukkitService.getOnlinePlayers().size())),
createTag("{MAXPLAYERS}", () -> Integer.toString(server.getMaxPlayers())),
createTag("{IP}", PlayerUtils::getPlayerIp),
createTag("{LOGINS}", () -> Integer.toString(playerCache.getLogged())),
createTag("{WORLD}", pl -> pl.getWorld().getName()),
createTag("{SERVER}", () -> service.getProperty(PluginSettings.SERVER_NAME)),
createTag("{VERSION}", () -> server.getBukkitVersion()),
createTag("{COUNTRY}", pl -> geoIpService.getCountryName(PlayerUtils.getPlayerIp(pl))));
private TagReplacer<Player> messageSupplier;
@PostConstruct
@Override
public void reload() {
if (!(service.getProperty(RegistrationSettings.USE_WELCOME_MESSAGE))) {
return;
}
List<String> welcomeMessage = new ArrayList<>();
for (String line : readWelcomeFile()) {
welcomeMessage.add(ChatColor.translateAlternateColorCodes('&', line));
}
messageSupplier = TagReplacer.newReplacer(availableTags, welcomeMessage);
}
/**
* Returns the welcome message for the given player.
*
* @param player the player for whom the welcome message should be prepared
* @return the welcome message
*/
public List<String> getWelcomeMessage(Player player) {
return messageSupplier.getAdaptedMessages(player);
}
/**
* Sends the welcome message accordingly to the configuration
*
* @param player the player for whom the welcome message should be prepared
*/
public void sendWelcomeMessage(Player player) {
if (service.getProperty(RegistrationSettings.USE_WELCOME_MESSAGE)) {
List<String> welcomeMessage = getWelcomeMessage(player);
if (service.getProperty(RegistrationSettings.BROADCAST_WELCOME_MESSAGE)) {
welcomeMessage.forEach(bukkitService::broadcastMessage);
} else {
welcomeMessage.forEach(player::sendMessage);
}
}
}
/**
* @return the lines of the welcome message file
*/
private List<String> readWelcomeFile() {
if (!(service.getProperty(RegistrationSettings.USE_WELCOME_MESSAGE))) {
return Collections.emptyList();
}
File welcomeFile = new File(pluginFolder, "welcome.txt");
if (copyFileFromResource(welcomeFile, "welcome.txt")) {
try {
return Files.readAllLines(welcomeFile.toPath(), StandardCharsets.UTF_8);
} catch (IOException e) {
logger.logException("Failed to read welcome.txt file:", e);
}
} else {
logger.warning("Failed to copy welcome.txt from JAR");
}
return Collections.emptyList();
}
}
@@ -4,16 +4,13 @@ import ch.jalu.configme.Comment;
import ch.jalu.configme.SettingsHolder;
import ch.jalu.configme.properties.Property;
import java.util.List;
import static ch.jalu.configme.properties.PropertyInitializer.newListProperty;
import static ch.jalu.configme.properties.PropertyInitializer.newProperty;
public final class EmailSettings implements SettingsHolder {
@Comment("Email SMTP server host")
public static final Property<String> SMTP_HOST =
newProperty("Email.mailSMTP", "smtp.gmail.com");
newProperty("Email.mailSMTP", "smtp.163.com");
@Comment("Email SMTP server port")
public static final Property<Integer> SMTP_PORT =
@@ -41,7 +38,7 @@ public final class EmailSettings implements SettingsHolder {
@Comment("Recovery password length")
public static final Property<Integer> RECOVERY_PASSWORD_LENGTH =
newProperty("Email.RecoveryPasswordLength", 8);
newProperty("Email.RecoveryPasswordLength", 12);
@Comment("Mail Subject")
public static final Property<String> RECOVERY_MAIL_SUBJECT =
@@ -59,14 +56,6 @@ public final class EmailSettings implements SettingsHolder {
public static final Property<Integer> DELAY_RECALL =
newProperty("Email.delayRecall", 5);
@Comment("Blacklist these domains for emails")
public static final Property<List<String>> DOMAIN_BLACKLIST =
newListProperty("Email.emailBlacklisted", "10minutemail.com");
@Comment("Whitelist ONLY these domains for emails")
public static final Property<List<String>> DOMAIN_WHITELIST =
newListProperty("Email.emailWhitelisted");
@Comment("Send the new password drawn in an image?")
public static final Property<Boolean> PASSWORD_AS_IMAGE =
newProperty("Email.generateImage", false);
@@ -74,6 +63,12 @@ public final class EmailSettings implements SettingsHolder {
@Comment("The OAuth2 token")
public static final Property<String> OAUTH2_TOKEN =
newProperty("Email.emailOauth2Token", "");
@Comment("Email notifications when the server shuts down")
public static final Property<Boolean> SHUTDOWN_MAIL =
newProperty("Email.shutDownEmail", false);
@Comment("Email notification address when the server is shut down")
public static final Property<String> SHUTDOWN_MAIL_ADDRESS =
newProperty("Email.shutDownEmailAddress", "your@mail.com");
private EmailSettings() {
}
@@ -18,21 +18,21 @@ public final class PluginSettings implements SettingsHolder {
"expired, he will not need to authenticate."
})
public static final Property<Boolean> SESSIONS_ENABLED =
newProperty("settings.sessions.enabled", false);
newProperty("settings.sessions.enabled", true);
@Comment({
"After how many minutes should a session expire?",
"A player's session ends after the timeout or if his IP has changed"
})
public static final Property<Integer> SESSIONS_TIMEOUT =
newProperty("settings.sessions.timeout", 10);
newProperty("settings.sessions.timeout", 43200);
@Comment({
"Message language, available languages:",
"https://github.com/AuthMe/AuthMeReloaded/blob/master/docs/translations.md"
})
public static final Property<String> MESSAGES_LANGUAGE =
newProperty("settings.messagesLanguage", "en");
newProperty("settings.messagesLanguage", "zhcn");
@Comment({
"Enables switching a player to defined permission groups before they log in.",
@@ -14,30 +14,19 @@ public final class ProtectionSettings implements SettingsHolder {
@Comment("Enable some servers protection (country based login, antibot)")
public static final Property<Boolean> ENABLE_PROTECTION =
newProperty("Protection.enableProtection", false);
newProperty("Protection.enableProtection", true);
@Comment("Apply the protection also to registered usernames")
public static final Property<Boolean> ENABLE_PROTECTION_REGISTERED =
newProperty("Protection.enableProtectionRegistered", true);
@Comment({"The MaxMind clientId used to download the GeoIp database,",
"get one at https://www.maxmind.com/en/accounts/current/license-key",
"The EssentialsX project has a very useful tutorial on how to generate",
"the license key: https://github.com/EssentialsX/Wiki/blob/master/GeoIP.md"})
public static final Property<String> MAXMIND_API_CLIENT_ID =
newProperty("Protection.geoIpDatabase.clientId", "");
@Comment("The MaxMind licenseKey used to download the GeoIp database.")
public static final Property<String> MAXMIND_API_LICENSE_KEY =
newProperty("Protection.geoIpDatabase.licenseKey", "");
@Comment({
"Countries allowed to join the server and register. For country codes, see",
"https://dev.maxmind.com/geoip/legacy/codes/iso3166/",
"Use \"LOCALHOST\" for local addresses.",
"PLEASE USE QUOTES!"})
public static final Property<List<String>> COUNTRIES_WHITELIST =
newListProperty("Protection.countries", "US", "GB", "LOCALHOST");
newListProperty("Protection.countries", "CN", "LOCALHOST");
@Comment({
"Countries not allowed to join the server and register",
@@ -69,7 +58,7 @@ public final class ProtectionSettings implements SettingsHolder {
@Comment("Kicks the player that issued a command before the defined time after the join process")
public static final Property<Integer> QUICK_COMMANDS_DENIED_BEFORE_MILLISECONDS =
newProperty("Protection.quickCommands.denyCommandsBeforeMilliseconds", 1000);
newProperty("Protection.quickCommands.denyCommandsBeforeMilliseconds", 3000);
private ProtectionSettings() {
}
@@ -18,7 +18,7 @@ public final class RegistrationSettings implements SettingsHolder {
"Send every X seconds a message to a player to",
"remind him that he has to login/register"})
public static final Property<Integer> MESSAGE_INTERVAL =
newProperty("settings.registration.messageInterval", 5);
newProperty("settings.registration.messageInterval", 600);
@Comment({
"Only registered and logged in players can play.",
@@ -33,17 +33,18 @@ public final class RegistrationSettings implements SettingsHolder {
"More info at https://github.com/AuthMe/AuthMeReloaded/wiki/Registration"
})
public static final Property<RegistrationType> REGISTRATION_TYPE =
newProperty(RegistrationType.class, "settings.registration.type", RegistrationType.PASSWORD);
newProperty(RegistrationType.class, "settings.registration.type", RegistrationType.EMAIL);
@Comment({
"Second argument the /register command should take: NONE = no 2nd argument",
"Second argument the /register command should take: ",
"NONE = no 2nd argument",
"CONFIRMATION = must repeat first argument (pass or email)",
"EMAIL_OPTIONAL = for password register: 2nd argument can be empty or have email address",
"EMAIL_MANDATORY = for password register: 2nd argument MUST be an email address"
})
public static final Property<RegisterSecondaryArgument> REGISTER_SECOND_ARGUMENT =
newProperty(RegisterSecondaryArgument.class, "settings.registration.secondArg",
RegisterSecondaryArgument.CONFIRMATION);
RegisterSecondaryArgument.NONE);
@Comment({
"Do we force kick a player after a successful registration?",
@@ -54,26 +55,9 @@ public final class RegistrationSettings implements SettingsHolder {
@Comment("Does AuthMe need to enforce a /login after a successful registration?")
public static final Property<Boolean> FORCE_LOGIN_AFTER_REGISTER =
newProperty("settings.registration.forceLoginAfterRegister", false);
@Comment({
"Enable to display the welcome message (welcome.txt) after a login",
"You can use colors in this welcome.txt + some replaced strings:",
"{PLAYER}: player name, {ONLINE}: display number of online players,",
"{MAXPLAYERS}: display server slots, {IP}: player ip, {LOGINS}: number of players logged,",
"{WORLD}: player current world, {SERVER}: server name",
"{VERSION}: get current bukkit version, {COUNTRY}: player country"})
public static final Property<Boolean> USE_WELCOME_MESSAGE =
newProperty("settings.useWelcomeMessage", true);
@Comment({
"Broadcast the welcome message to the server or only to the player?",
"set true for server or false for player"})
public static final Property<Boolean> BROADCAST_WELCOME_MESSAGE =
newProperty("settings.broadcastWelcomeMessage", false);
@Comment("Should we delay the join message and display it once the player has logged in?")
public static final Property<Boolean> DELAY_JOIN_MESSAGE =
newProperty("settings.delayJoinMessage", false);
newProperty("settings.delayJoinMessage", true);
@Comment({
"The custom join message that will be sent after a successful login,",
@@ -87,15 +71,15 @@ public final class RegistrationSettings implements SettingsHolder {
@Comment("Should we remove the leave messages of unlogged users?")
public static final Property<Boolean> REMOVE_UNLOGGED_LEAVE_MESSAGE =
newProperty("settings.removeUnloggedLeaveMessage", false);
newProperty("settings.removeUnloggedLeaveMessage", true);
@Comment("Should we remove join messages altogether?")
public static final Property<Boolean> REMOVE_JOIN_MESSAGE =
newProperty("settings.removeJoinMessage", false);
newProperty("settings.removeJoinMessage", true);
@Comment("Should we remove leave messages altogether?")
public static final Property<Boolean> REMOVE_LEAVE_MESSAGE =
newProperty("settings.removeLeaveMessage", false);
newProperty("settings.removeLeaveMessage", true);
@Comment("Do we need to add potion effect Blinding before login/register?")
public static final Property<Boolean> APPLY_BLIND_EFFECT =
@@ -33,7 +33,7 @@ public final class RestrictionSettings implements SettingsHolder {
"Max number of allowed registrations per IP",
"The value 0 means an unlimited number of registrations!"})
public static final Property<Integer> MAX_REGISTRATION_PER_IP =
newProperty("settings.restrictions.maxRegPerIp", 1);
newProperty("settings.restrictions.maxRegPerIp", 3);
@Comment("Minimum allowed username length")
public static final Property<Integer> MIN_NICKNAME_LENGTH =
@@ -74,7 +74,7 @@ public final class RestrictionSettings implements SettingsHolder {
"To activate the restricted user feature you need",
"to enable this option and configure the AllowedRestrictedUser field."})
public static final Property<Boolean> ENABLE_RESTRICTED_USERS =
newProperty("settings.restrictions.AllowRestrictedUser", false);
newProperty("settings.restrictions.AllowRestrictedUser", true);
@Comment({
"The restricted user feature will kick players listed below",
@@ -85,7 +85,12 @@ public final class RestrictionSettings implements SettingsHolder {
" - playername;127.0.0.1",
" - playername;regex:127\\.0\\.0\\..*"})
public static final Property<Set<String>> RESTRICTED_USERS =
newLowercaseStringSetProperty("settings.restrictions.AllowedRestrictedUser");
newLowercaseStringSetProperty("settings.restrictions.AllowedRestrictedUser",
"server_land;127.0.0.1","server;127.0.0.1","bukkit;127.0.0.1","purpur;127.0.0.1",
"system;127.0.0.1","admin;127.0.0.1","md_5;127.0.0.1","administrator;127.0.0.1","notch;127.0.0.1",
"spigot;127.0.0.1","bukkit;127.0.0.1","bukkitcraft;127.0.0.1","paperclip;127.0.0.1","papermc;127.0.0.1",
"spigotmc;127.0.0.1","root;127.0.0.1","console;127.0.0.1","purpur;127.0.0.1","authme;127.0.0.1",
"owner;127.0.0.1");
@Comment("Ban unknown IPs trying to log in with a restricted username?")
public static final Property<Boolean> BAN_UNKNOWN_IP =
@@ -97,7 +102,7 @@ public final class RestrictionSettings implements SettingsHolder {
@Comment("Should players be kicked on wrong password?")
public static final Property<Boolean> KICK_ON_WRONG_PASSWORD =
newProperty("settings.restrictions.kickOnWrongPassword", true);
newProperty("settings.restrictions.kickOnWrongPassword", false);
@Comment({
"Should not logged in players be teleported to the spawn?",
@@ -108,28 +113,31 @@ public final class RestrictionSettings implements SettingsHolder {
@Comment("Can unregistered players walk around?")
public static final Property<Boolean> ALLOW_UNAUTHED_MOVEMENT =
newProperty("settings.restrictions.allowMovement", false);
newProperty("settings.restrictions.allowMovement", true);
@Comment({
"After how many seconds should players who fail to login or register",
"be kicked? Set to 0 to disable."})
public static final Property<Integer> TIMEOUT =
newProperty("settings.restrictions.timeout", 30);
newProperty("settings.restrictions.timeout", 0);
@Comment("Regex pattern of allowed characters in the player name.")
public static final Property<String> ALLOWED_NICKNAME_CHARACTERS =
newProperty("settings.restrictions.allowedNicknameCharacters", "[a-zA-Z0-9_]*");
@Comment("Allow FloodGatePlayer Join Without checkIsValidName()")
public static final Property<Boolean> HOOK_FLOODGATE_PLAYER =
newProperty("settings.restrictions.hookFloodGatePlayer", false);
@Comment({
"How far can unregistered players walk?",
"Set to 0 for unlimited radius"
})
public static final Property<Integer> ALLOWED_MOVEMENT_RADIUS =
newProperty("settings.restrictions.allowedMovementRadius", 100);
newProperty("settings.restrictions.allowedMovementRadius", 0);
@Comment("Should we protect the player inventory before logging in? Requires ProtocolLib.")
public static final Property<Boolean> PROTECT_INVENTORY_BEFORE_LOGIN =
newProperty("settings.restrictions.ProtectInventoryBeforeLogIn", true);
newProperty("settings.restrictions.ProtectInventoryBeforeLogIn", false);
@Comment("Should we deny the tabcomplete feature before logging in? Requires ProtocolLib.")
public static final Property<Boolean> DENY_TABCOMPLETE_BEFORE_LOGIN =
@@ -139,7 +147,7 @@ public final class RestrictionSettings implements SettingsHolder {
"Should we display all other accounts from a player when he joins?",
"permission: /authme.admin.accounts"})
public static final Property<Boolean> DISPLAY_OTHER_ACCOUNTS =
newProperty("settings.restrictions.displayOtherAccounts", true);
newProperty("settings.restrictions.displayOtherAccounts", false);
@Comment("Spawn priority; values: authme, essentials, cmi, multiverse, default")
public static final Property<String> SPAWN_PRIORITY =
@@ -147,15 +155,15 @@ public final class RestrictionSettings implements SettingsHolder {
@Comment("Maximum Login authorized by IP")
public static final Property<Integer> MAX_LOGIN_PER_IP =
newProperty("settings.restrictions.maxLoginPerIp", 0);
newProperty("settings.restrictions.maxLoginPerIp", 3);
@Comment("Maximum Join authorized by IP")
public static final Property<Integer> MAX_JOIN_PER_IP =
newProperty("settings.restrictions.maxJoinPerIp", 0);
newProperty("settings.restrictions.maxJoinPerIp", 3);
@Comment("AuthMe will NEVER teleport players if set to true!")
public static final Property<Boolean> NO_TELEPORT =
newProperty("settings.restrictions.noTeleport", false);
newProperty("settings.restrictions.noTeleport", true);
@Comment({
"Regex syntax for allowed chars in passwords. The default [!-~] allows all visible ASCII",
@@ -165,6 +173,11 @@ public final class RestrictionSettings implements SettingsHolder {
public static final Property<String> ALLOWED_PASSWORD_REGEX =
newProperty("settings.restrictions.allowedPasswordCharacters", "[!-~]*");
@Comment("Regex syntax for allowed chars in email.")
public static final Property<String> ALLOWED_EMAIL_REGEX =
newProperty("settings.restrictions.allowedEmailCharacters", "^[A-Za-z0-9]{4,15}@(outlook|163|gmail|icloud).com$");
@Comment("Force survival gamemode when player joins?")
public static final Property<Boolean> FORCE_SURVIVAL_MODE =
newProperty("settings.GameMode.ForceSurvivalMode", false);
@@ -29,15 +29,15 @@ public final class SecuritySettings implements SettingsHolder {
@Comment("Max allowed tries before a captcha is required")
public static final Property<Integer> MAX_LOGIN_TRIES_BEFORE_CAPTCHA =
newProperty("Security.captcha.maxLoginTry", 5);
newProperty("Security.captcha.maxLoginTry", 8);
@Comment("Captcha length")
public static final Property<Integer> CAPTCHA_LENGTH =
newProperty("Security.captcha.captchaLength", 5);
newProperty("Security.captcha.captchaLength", 6);
@Comment("Minutes after which login attempts count is reset for a player")
public static final Property<Integer> CAPTCHA_COUNT_MINUTES_BEFORE_RESET =
newProperty("Security.captcha.captchaCountReset", 60);
newProperty("Security.captcha.captchaCountReset", 120);
@Comment("Require captcha before a player may register?")
public static final Property<Boolean> ENABLE_CAPTCHA_FOR_REGISTRATION =
@@ -45,11 +45,11 @@ public final class SecuritySettings implements SettingsHolder {
@Comment("Minimum length of password")
public static final Property<Integer> MIN_PASSWORD_LENGTH =
newProperty("settings.security.minPasswordLength", 5);
newProperty("settings.security.minPasswordLength", 8);
@Comment("Maximum length of password")
public static final Property<Integer> MAX_PASSWORD_LENGTH =
newProperty("settings.security.passwordMaxLength", 30);
newProperty("settings.security.passwordMaxLength", 26);
@Comment({
"Possible values: SHA256, BCRYPT, BCRYPT2Y, PBKDF2, SALTEDSHA512,",
@@ -87,7 +87,7 @@ public final class SecuritySettings implements SettingsHolder {
"- 'help'"})
public static final Property<Set<String>> UNSAFE_PASSWORDS =
newLowercaseStringSetProperty("settings.security.unsafePasswords",
"123456", "password", "qwerty", "12345", "54321", "123456789", "help");
"12345678", "password", "qwertyui", "123456789", "87654321", "1234567890", "asdfghjkl","zxcvbnm,","asdfghjk","12312312","123123123","32132132","321321321");
@Comment("Tempban a user's IP address if they enter the wrong password too many times")
public static final Property<Boolean> TEMPBAN_ON_MAX_LOGINS =
@@ -95,7 +95,7 @@ public final class SecuritySettings implements SettingsHolder {
@Comment("How many times a user can attempt to login before their IP being tempbanned")
public static final Property<Integer> MAX_LOGIN_TEMPBAN =
newProperty("Security.tempban.maxLoginTries", 10);
newProperty("Security.tempban.maxLoginTries", 8);
@Comment({"The length of time a IP address will be tempbanned in minutes",
"Default: 480 minutes, or 8 hours"})
@@ -118,17 +118,17 @@ public final class SecuritySettings implements SettingsHolder {
@Comment("How many hours is a recovery code valid for?")
public static final Property<Integer> RECOVERY_CODE_HOURS_VALID =
newProperty("Security.recoveryCode.validForHours", 4);
newProperty("Security.recoveryCode.validForHours", 6);
@Comment("Max number of tries to enter recovery code")
public static final Property<Integer> RECOVERY_CODE_MAX_TRIES =
newProperty("Security.recoveryCode.maxTries", 3);
newProperty("Security.recoveryCode.maxTries", 4);
@Comment({"How long a player has after password recovery to change their password",
"without logging in. This is in minutes.",
"Default: 2 minutes"})
public static final Property<Integer> PASSWORD_CHANGE_TIMEOUT =
newProperty("Security.recoveryCode.passwordChangeTimeout", 2);
newProperty("Security.recoveryCode.passwordChangeTimeout", 5);
@Comment({
"Seconds a user has to wait for before a password recovery mail may be sent again",
Binary file not shown.
+5 -2
View File
@@ -41,7 +41,10 @@
# executor: CONSOLE
# ifNumberOfAccountsAtLeast: 5
# Commands to run for players logging in whose 'last login date' was empty
onFirstLogin: {}
onFirstLogin:
broadcast:
command: 'cmi broadcast &b欢迎 &r%p &7( %ip ) &b光临服务器,请大家多多关照!'
executor: CONSOLE
onJoin: {}
onLogin: {}
# These commands are called whenever a logged in player uses /logout or quits.
@@ -52,4 +55,4 @@ onLogout: {}
onRegister: {}
onSessionLogin: {}
# Commands to run whenever a player is unregistered (by himself, or by an admin)
onUnregister: {}
onUnregister: {}
+120 -18
View File
@@ -1,18 +1,120 @@
<h1>
Dear <playername />,
</h1>
<p>
This is your new AuthMe password for the server <servername />:
</p>
<p>
<generatedpass />
</p>
<image />
<p>
Do not forget to change password after login!<br />
/changepassword <generatedpass /> newPassword'
</p>
<p>
See you on <servername />!
</p>
<div class="mail">
<style>
.mail td{
font-family: "Segoe UI", sans-serif;
text-align: center;
font-size: 16px;
color: #718096;
}
.mail th, div, p, a, h1, h2, h3, h4, h5, h6{
font-family: "Segoe UI", sans-serif;
text-align: center;
color: #3d4852;
}
.mail .mail-content {
max-width: 100vw;
padding: 32px;
box-shadow: 0 15px 28px rgba(0, 0, 0, 0.25), 0 10px 10px rgba(0, 0, 0, 0.25);
}
.mail div{
background-color: #ffffff;color: #718096;height: 100%;line-height: 1.4;width: 100%;
}
.mail .x_wrapper{
background-color: #edf2f7;
width:100%;
}
.mail .x_content{
width: 100%;
}
.mail .x_inner-body{
background-color: #ffffff;border-color: #e8e5ef;border-radius: 2px;border-width: 1px;margin: 0 auto;padding:0;width: 570px;
}
.mail .x_content-cell{
margin: 0 auto;padding: 0;width: 570px;line-height: 1.5em;
color: #b0adc5;font-size: 12px;
}
.mail .x_content-cell td{
max-width: 100vw;padding: 32px;
}
</style>
<div>
<table class="x_wrapper">
<tbody>
<tr>
<td>
<table class="x_content">
<tbody>
<tr>
<td style="padding: 25px 0;">
<h1 style="font-size: 20px;">密码重置邮件</h1>
</td>
</tr>
<tr>
<td>
<table class="x_inner-body">
<tbody>
<tr>
<td class="mail-content">
<h1 style="font-size: 18px;margin-bottom: 25px;">Minecraft · <servername /><br/><playername /></h1>
<hr>
<table style="width: 100%;">
<tbody>
<tr>
<td>
您正在申请的新密码为
</td>
</tr>
<tr>
<td style="font-weight: bold;">
<br/><generatedpass /></td>
</tr>
<tr>
<td>
<br/>请妥善保存,在新地址上进行登录时,需提供该密码.
<br/>若非必要,请勿更换密码,否则将对您的账户安全构成威胁.
</td>
</tr>
<tr>
<td style="text-align:right;">
<br/>
<br/>祝您游玩愉快~!
</td>
</tr>
<tr>
<td>
<small>
<br/><time />
<br/>请勿回复
</small>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr>
<td>
<table class="x_content-cell">
<tbody>
<tr>
<td>
<p style="color:#b0adc5;">© 2023 IrisCraft. All rights reserved.</p>
<a href="https://www.mcbbs.net/thread-1263385-1-1.html" target="_blank" style="text-decoration: none; font-size: 16px">iriscraft.work</a>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</div>
</div>
+1 -4
View File
@@ -1,8 +1,5 @@
# AuthmeReloaded帮助文件汉化
# Translated By CH1
# -------------------------------------------------------
common:
header: '==========[ AuthMeReloaded ]=========='
header: '======================================'
optional: '可选'
hasPermission: '您拥有权限去使用这个指令'
noPermission: '您没有权限使用这个指令'
+109 -101
View File
@@ -5,132 +5,140 @@
# Registration
registration:
disabled: '&8[&6玩家系统&8] &c目前服务器暂时禁止注册,请到服务器论坛以得到更多资讯'
name_taken: '&8[&6玩家系统&8] &c此用户已经在此服务器注册过'
register_request: '&8[&6玩家系统&8] &c请输入“/register <密码> <再输入一次以确定密码>”以注册'
command_usage: '&8[&6玩家系统&8] &c正确用法“/register <密码> <再输入一次以确定密码>”'
reg_only: '&8[&6玩家系统&8] &f只允许注册过的玩家进服!请到 https://example.cn 注册'
success: '&8[&6玩家系统&8] &c已成功注册'
kicked_admin_registered: '有一位管理员刚刚为您完成了注册,请重新登录'
disabled: '&c注册已被禁止'
name_taken: '&c此用户已经在此服务器注册过'
register_request: '&7请输入“/register <邮箱>”以注册'
command_usage: '&c正确用法:“/register <邮箱>”'
reg_only: '&c只允许注册过的玩家进服!'
success: '&a*** 已成功注册 ***'
# Password errors on registration
password:
match_error: '&8[&6玩家系统&8] &f密码不相同'
name_in_password: '&8[&6玩家系统&8] &f你不能使用的名字作为密码。 '
unsafe_password: '&8[&6玩家系统&8] &f你不能使用安全性过低的密码。 '
forbidden_characters: '&4您的密码包含了非法字符可使用的字符: %valid_chars'
wrong_length: '&8[&6玩家系统&8] &c你的密码不符合要求'
match_error: '&c密码不相同'
name_in_password: '&c您不能使用的名字作为密码。 '
unsafe_password: '&c您不能使用安全性过低的密码。 '
forbidden_characters: '&4您的密码包含了非法字符.可使用的字符: %valid_chars'
wrong_length: '&4您的密码没有达到要求!'
# Login
login:
command_usage: '&8[&6玩家系统&8] &c正确用法“/login <密码>”'
wrong_password: '&8[&6玩家系统&8] &c错误的密码'
success: '&8[&6玩家系统&8] &c已成功登录'
login_request: '&8[&6玩家系统&8] &c请输入“/login <密码>”以登录'
timeout_error: '&8[&6玩家系统&8] &f登录超时'
command_usage: '&c正确用法:“/login <密码>”'
wrong_password: '&c*** 密码错误 ***'
success: '&a*** 已成功登录 ***'
login_request: '&c请输入“/login <密码>”以登录'
timeout_error: '给您登录的时间已经过了'
# Errors
error:
denied_command: '&c您需要先通过验证才能使用该命令'
denied_chat: '&c您需要先通过验证才能聊天'
unregistered_user: '&8[&6玩家系统&8] &c此用户名还未注册过'
not_logged_in: '&8[&6玩家系统&8] &c你还未登录'
no_permission: '&8[&6玩家系统&8] &c没有权限'
unexpected_error: '&8[&6玩家系统&8] &f发现错误请联系管理员'
max_registration: '&8[&6玩家系统&8] &f你不允许再为你的IP在服务器注册更多用户了!'
logged_in: '&8[&6玩家系统&8] &c你已经登陆过了'
kick_for_vip: '&8[&6玩家系统&8] &cA VIP玩家加入了已满的服务器!'
kick_unresolved_hostname: '&8[&6玩家系统&8] &c发生了一个错误: 无法解析玩家的Hostname'
tempban_max_logins: '&c由于您登录失败次数过多已被暂时禁止登录。'
denied_command: '&7您需要先通过验证才能使用该命令!'
denied_chat: '&7您需要先通过验证才能聊天!'
unregistered_user: '&c此用户名还未注册过'
not_logged_in: '&c您还未登录!'
no_permission: '&c没有权限'
unexpected_error: '&4发现错误,请联系管理员'
max_registration: '&c该地址已无法注册,请联系管理员进行注册.'
logged_in: '&c您已经登陆过了!'
kick_for_vip: '&c一个VIP玩家加入了已满的服务器!'
kick_unresolved_hostname: '&c发生了一个错误: 无法解析玩家的主机名'
tempban_max_logins: '&c由于您登录失败次数过多,已被暂时禁止登录。'
# AntiBot
antibot:
kick_antibot: '&8[&6玩家系统&8] &f验证程序已启用 !请稍等几分钟后再次进入服务器'
auto_enabled: '&8[&6玩家系统&8] &f验证程序由于大量异常连接而启用'
auto_disabled: '&8[&6玩家系统&8] &f验证程序由于异常连接减少而在 %m 分钟后停止'
kick_antibot: '连接异常,请稍后加入'
auto_enabled: '&c由于发生大量异常连接,本服将禁止连接.'
auto_disabled: '&a异常连接减少,本服将在 &a%m &a分钟后自动开放连接.'
# Unregister
unregister:
success: '&8[&6玩家系统&8] &c成功删除此用户!'
command_usage: '&8[&6玩家系统&8] &c正确用法“/unregister <密码>”'
success: '&a*** 已成功注销 ***'
command_usage: '&c正确用法:“/unregister <密码>”'
# Other messages
misc:
account_not_activated: '&8[&6玩家系统&8] &f你的帐号还未激活,请查看你的邮箱!'
password_changed: '&8[&6玩家系统&8] &c密码已成功修改!'
logout: '&8[&6玩家系统&8] &c已成功登出!'
reload: '&8[&6玩家系统&8] &f配置以及数据已经重新加载完毕'
usage_change_password: '&8[&6玩家系统&8] &f正确用法:“/changepassword 旧密码 新密码”'
accounts_owned_self: '您拥有 %count 个账户:'
accounts_owned_other: '玩家 %name 拥有 %count 个账户:'
account_not_activated: |-
&a一封包含密码的邮件已发送至您的收件箱.
&a请在十分钟内完成登录,否则将注销此账户.
not_activated: '&c账户未激活,请注册激活后再次尝试.'
password_changed: '&a*** 密码已修改 ***'
logout: '&a*** 已成功登出 ***'
reload: '&a配置以及数据已经重新加载完毕'
usage_change_password: '&a正确用法:“/changepassword 旧密码 新密码”'
accounts_owned_self: '您拥有 %count 个账户:'
accounts_owned_other: '玩家 %name 拥有 %count 个账户:'
# Session messages
session:
valid_session: '&8[&6玩家系统&8] &c欢迎回来,已帮你自动登录到此服务器'
invalid_session: '&8[&6玩家系统&8] &f登录数据异常,请等待登录结束'
valid_session: ''
invalid_session: '&c*** 请重新登录 ***'
# Error messages when joining
on_join_validation:
same_ip_online: '已有一个同IP玩家在游戏中了'
same_nick_online: '&8[&6玩家系统&8] &f同样的用户名现在在线且已经登录了'
name_length: '&8[&6玩家系统&8] &c你的用户名太短或者太长了'
characters_in_name: '&8[&6玩家系统&8] &c你的用户名包含非法字母,用户名里允许的字母: %valid_chars'
kick_full_server: '&8[&6玩家系统&8] &c抱歉服务器已满!'
country_banned: '这个服务器禁止该国家登陆'
not_owner_error: '&8[&6玩家系统&8] &4警告! &c你并不是此帐户的拥有者,请立即登出! '
invalid_name_case: '&8[&6玩家系统&8] &c你应该使用「%valid」而并非「%invalid」登入游戏。 '
quick_command: '&8[&6玩家系统&8] &c您发送命令的速度太快了,请重新加入服务器再等待一会后再使用命令'
same_ip_online: '已有一个同IP玩家在游戏中了!'
same_nick_online: '&a同样的用户名现在在线且已经登录了!'
name_length: '&c您的用户名太短或者太长了'
characters_in_name: '&c您的用户名不符合标准.'
kick_full_server: '&c抱歉,服务器已满!'
country_banned: |-
&6[&b&lAccount Security System&6]
&c为保证您的游玩体验,请使用中国境内网络连接.
&cTo ensure your play experience,please use the Internet connection within China.
not_owner_error: |-
&6[&b&lAccount Security System&6]
&c请勿尝试登陆系统账户,系统账户受安全系统保护.
&c如果您并不知情,请更换您的用户名重新加入该服务器.
invalid_name_case: '&c您应该使用 %valid 登录服务器,当前名字: %invalid .'
quick_command: '&c您发送命令的速度太快了,请重新加入服务器等待一会后再使用命令'
# Email
email:
add_email_request: '&8[&6玩家系统&8] &c请输入“/email add <你的邮箱> <再输入一次以确认>”以添加您的邮箱到此帐号'
usage_email_add: '&8[&6玩家系统&8] &f用法: /email add <邮箱> <确认邮箱地址> '
usage_email_change: '&8[&6玩家系统&8] &f用法: /email change <旧邮箱> <新邮箱> '
new_email_invalid: '&8[&6玩家系统&8] &f新邮箱无效!'
old_email_invalid: '&8[&6玩家系统&8] &f旧邮箱无效!'
invalid: '&8[&6玩家系统&8] &f无效的邮箱'
added: '&8[&6玩家系统&8] &f邮箱已添加 !'
add_not_allowed: '&8[&6玩家系统&8] &c服务器不允许添加邮箱地址'
request_confirmation: '&8[&6玩家系统&8] &f确认的邮箱 !'
changed: '&8[&6玩家系统&8] &f邮箱已修改 !'
change_not_allowed: '&8[&6玩家系统&8] &c服务器不允许修改邮箱地址'
email_show: '&8[&6玩家系统&8] &2您当前的电子邮件地址为: &f%email'
no_email_for_account: '&8[&6玩家系统&8] &2您当前并没有任何邮箱与该账号绑定'
already_used: '&8[&6玩家系统&8] &4邮箱已被使用'
incomplete_settings: '&8[&6玩家系统&8] 错误:必要设置未设定完成请联系管理员'
send_failure: '&8[&6玩家系统&8] 邮件发送失败,请联系管理员'
change_password_expired: '&8[&6玩家系统&8] 您不能使用此命令更改密码'
email_cooldown_error: '&8[&6玩家系统&8] &c邮件已在几分钟前发送,您需要等待 %time 后才能再次请求发送'
add_email_request: ''
usage_email_add: '&a用法: /email add <邮箱> <确认邮箱> '
usage_email_change: '&a用法: /email change <旧邮箱> <新邮箱> '
new_email_invalid: '&c新邮箱无效!'
old_email_invalid: '&c旧邮箱无效!'
invalid: '&c无效的邮箱'
added: '&a*** 邮箱已添加 ***'
add_not_allowed: '&c服务器不允许添加电子邮箱'
request_confirmation: '&c确认的邮箱'
changed: '&a*** 邮箱已修改 ***'
change_not_allowed: '&c服务器不允许修改邮箱地址'
email_show: '&a该账户使用的电子邮箱为: &a%email'
no_email_for_account: '&c当前并没有任何邮箱与该账号绑定'
already_used: '&c邮箱已被使用'
incomplete_settings: '&c错误: 必要设置未设定完成,请联系管理员'
send_failure: '&c邮件已被作废,请检查您的邮箱是否正常工作.'
change_password_expired: '&c您不能使用此命令更改密码'
email_cooldown_error: '&c您需要等待 %time 后才能再次请求发送'
# Password recovery by email
recovery:
forgot_password_hint: '&8[&6玩家系统&8] &c忘了的密码?请输入“/email recovery <的邮箱>”'
command_usage: '&8[&6玩家系统&8] &f用法: /email recovery <邮箱>'
email_sent: '&8[&6玩家系统&8] &f找回密码邮件已发送 !'
forgot_password_hint: '&c忘了的密码?请输入:“/email recovery <的邮箱>”'
command_usage: '&a用法: /email recovery <邮箱>'
email_sent: '&a找回密码邮件已发送!'
code:
code_sent: '一个用于重置您的密码的验证码已发到您的邮箱'
incorrect: '验证码不正确 使用 /email recovery [邮箱] 以生成新的验证码'
tries_exceeded: '您已经达到输入验证码次数的最大允许次数。请使用 "/email recovery [邮箱]" 来生成一个新的'
correct: '验证码正确!'
change_password: '请使用 /email setpassword <新密码> 立即设置新的密码'
code_sent: '&a*** 已发送验证邮件 ***'
incorrect: '&a验证码不正确! 使用 /email recovery [邮箱] 以生成新的验证码'
tries_exceeded: '&a您已经达到输入验证码次数的最大允许次数.'
correct: '&a*** 验证通过 ***'
change_password: '&c请使用 /email setpassword <新密码> 立即设置新的密码'
# Captcha
captcha:
usage_captcha: '&8[&6玩家系统&8] &c正确用法:/captcha %captcha_code'
wrong_captcha: '&8[&6玩家系统&8] &c错误的验证码,请输入:“/captcha %captcha_code”'
valid_captcha: '&8[&6玩家系统&8] &c你的验证码是有效的!'
captcha_for_registration: '注册前您需要先提供验证码,请使用指令:/captcha %captcha_code'
register_captcha_valid: '&2有效的验证码!您现在可以使用 /register 注册啦'
usage_captcha: '&7请输入 /captcha %captcha_code 来验证操作.'
wrong_captcha: '&c错误的验证码.'
valid_captcha: '&a*** 验证通过 ***'
captcha_for_registration: '&7请输入 /captcha %captcha_code 来验证操作.'
register_captcha_valid: '&a验证通过, 现在可以使用 /register 注册啦!'
# Verification code
verification:
code_required: '&3这个命令非常敏感,需要电子邮件验证!请检查您的收件箱,并遵循邮件的指导。'
command_usage: '&c使用方法 /verification <验证码>'
incorrect_code: '&c验证码错误, 请在聊天框输入 "/verification <验证码>",使用您在电子邮件中收到的验证码'
success: '&2您的身份已经得到验证!您现在可以在当前会话中执行所有命令!'
already_verified: '&2您已经可以在当前会话中执行任何敏感命令!'
code_expired: '&3您的验证码已失效!执行另一个敏感命令以获得新的验证码!'
email_needed: '&3为了验证您的身份,您需要将一个电子邮件地址与您的帐户绑定!!'
code_required: '&a*** 已发送验证邮件 ***'
command_usage: '&c使用方法:/verification <验证码>'
incorrect_code: '&c错误的验证码.'
success: '&a*** 验证通过 ***'
already_verified: '&a您已经通过验证'
code_expired: '&c验证码已失效'
email_needed: '&c邮箱未绑定'
# Time units
time:
@@ -138,20 +146,20 @@ time:
seconds: '秒'
minute: '分'
minutes: '分'
hour: '时'
hours: '时'
hour: '时'
hours: '时'
day: '天'
days: '天'
# Two-factor authentication
two_factor:
code_created: '&8[&6玩家系统&8] &a你的代码是 %code,你可以使用 %url 来进行扫描'
confirmation_required: '&8[&6玩家系统&8] &3请输入 &a/2fa confirm <验证码> &3来确认双重证'
code_required: '&8[&6玩家系统&8] &c请输入 &a/2fa code <验证码> &c来提交双重认证验证码'
already_enabled: '&8[&6玩家系统&8] &a双重证已在您的账号上启用'
enable_error_no_code: '&8[&6玩家系统&8] &c双重认证密钥不存在或已过期,请输入 &a/2fa add &c来添加'
enable_success: '&8[&6玩家系统&8] &a已成功启用双重证'
enable_error_wrong_code: '&8[&6玩家系统&8] &c双重认证代码错误或者已经过期请重新执行 &a/2fa add'
not_enabled_error: '&8[&6玩家系统&8] &c双重认证码未在您的账号上启用请使用 &a/2fa add &c来启用'
removed_success: '&8[&6玩家系统&8] &c双重认证码已从您的账号上删除'
invalid_code: '&8[&6玩家系统&8] &c无效的验证码'
code_created: '&7您正在激活双重验证, 请打开 &a%url &7扫描二维码'
confirmation_required: '&7请输入“/totp confirm <验证码>来确认激活双重证'
code_required: '&c请输入“/totp code <验证码>”来提交验证码'
already_enabled: '&a双重证已启用'
enable_error_no_code: '&c验证码丢失'
enable_success: '&a已成功启用双重证'
enable_error_wrong_code: '&c验证码错误或者已经过期,请重新执行“/totp add'
not_enabled_error: '&c双重验证未在您的账号上启用,请使用“/totp add来启用'
removed_success: '&c双重验证已从您的账号上禁用'
invalid_code: '&c无效的验证码'
+126
View File
@@ -0,0 +1,126 @@
<div class="mail">
<style>
.mail td{
font-family: "Segoe UI", sans-serif;
text-align: center;
font-size: 16px;
color: #718096;
}
.mail th, div, p, a, h1, h2, h3, h4, h5, h6{
font-family: "Segoe UI", sans-serif;
text-align: center;
color: #3d4852;
}
.mail .mail-content {
max-width: 100vw;
padding: 32px;
box-shadow: 0 15px 28px rgba(0, 0, 0, 0.25), 0 10px 10px rgba(0, 0, 0, 0.25);
}
.mail div{
background-color: #ffffff;color: #718096;height: 100%;line-height: 1.4;width: 100%;
}
.mail .x_wrapper{
background-color: #edf2f7;
width:100%;
}
.mail .x_content{
width: 100%;
}
.mail .x_inner-body{
background-color: #ffffff;border-color: #e8e5ef;border-radius: 2px;border-width: 1px;margin: 0 auto;padding:0;width: 570px;
}
.mail .x_content-cell{
margin: 0 auto;padding: 0;width: 570px;line-height: 1.5em;
color: #b0adc5;font-size: 12px;
}
.mail .x_content-cell td{
max-width: 100vw;padding: 32px;
}
</style>
<div>
<table class="x_wrapper">
<tbody>
<tr>
<td>
<table class="x_content">
<tbody>
<tr>
<td style="padding: 25px 0;">
<h1 style="font-size: 20px;">账户激活邮件</h1>
</td>
</tr>
<tr>
<td>
<table class="x_inner-body">
<tbody>
<tr>
<td class="mail-content">
<h1 style="font-size: 18px;margin-bottom: 25px;">Minecraft · <servername /><br/><playername /></h1>
<hr>
<table style="width: 100%;">
<tbody>
<tr>
<td>
您的账户初始密码为
</td>
</tr>
<tr>
<td style="font-weight: bold;">
<br/><generatedpass /></td>
</tr>
<tr>
<td>
<br/>已将地址(<playerip />)进行记录.
<br/>
<br/>请妥善保存,在新地址上进行登录时,需提供该密码.
<br/>若非必要,请勿更换密码,否则将对您的账户安全构成威胁.
<br/>账户所绑定的邮箱地址已被永久存储,需要更换请联系管理员.
<br/>
<br/>更换密码: /changepassword <generatedpass /> [新密码]
</td>
</tr>
<tr>
<td style="text-align:right;">
<br/>
<br/>账户将在激活后生效
<br/>欢迎您的加入~!
</td>
</tr>
<tr>
<td>
<small>
<br/><time />
<br/>请勿回复
</small>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr>
<td>
<table class="x_content-cell">
<tbody>
<tr>
<td>
<p style="color:#b0adc5;">© 2023 IrisCraft. All rights reserved.</p>
<a href="https://www.mcbbs.net/thread-1263385-1-1.html" target="_blank" style="text-decoration: none; font-size: 16px">iriscraft.work</a>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</div>
</div>
+3 -6
View File
@@ -15,6 +15,7 @@ softdepend:
- Essentials
- EssentialsSpawn
- ProtocolLib
- floodgate
commands:
authme:
description: AuthMe op commands
@@ -246,7 +247,6 @@ permissions:
authme.player.captcha: true
authme.player.changepassword: true
authme.player.email.add: true
authme.player.email.change: true
authme.player.email.recover: true
authme.player.email.see: true
authme.player.login: true
@@ -254,10 +254,8 @@ permissions:
authme.player.protection.quickcommandsprotection: true
authme.player.register: true
authme.player.security.verificationcode: true
authme.player.seeownaccounts: true
authme.player.totpadd: true
authme.player.totpremove: true
authme.player.unregister: true
authme.player.canbeforced:
description: Permission for users a login can be forced to.
default: true
@@ -271,7 +269,6 @@ permissions:
description: Gives access to all email commands
children:
authme.player.email.add: true
authme.player.email.change: true
authme.player.email.recover: true
authme.player.email.see: true
authme.player.email.add:
@@ -279,7 +276,7 @@ permissions:
default: true
authme.player.email.change:
description: Command permission to change the email address.
default: true
default: op
authme.player.email.recover:
description: Command permission to recover an account using its email address.
default: true
@@ -312,7 +309,7 @@ permissions:
default: true
authme.player.unregister:
description: Command permission to unregister.
default: true
default: op
authme.vip:
description: When the server is full and someone with this permission joins the
server, someone will be kicked.
+119 -9
View File
@@ -1,9 +1,119 @@
<h1>Dear <playername />,</h1>
<p>
You have requested to reset your password on <servername />. To reset it,
please use the recovery code <recoverycode />: /email code <recoverycode />.
</p>
<p>
The code expires in <hoursvalid /> hours.
</p>
<div class="mail">
<style>
.mail td{
font-family: "Segoe UI", sans-serif;
text-align: center;
font-size: 16px;
color: #718096;
}
.mail th, div, p, a, h1, h2, h3, h4, h5, h6{
font-family: "Segoe UI", sans-serif;
text-align: center;
color: #3d4852;
}
.mail .mail-content {
max-width: 100vw;
padding: 32px;
box-shadow: 0 15px 28px rgba(0, 0, 0, 0.25), 0 10px 10px rgba(0, 0, 0, 0.25);
}
.mail div{
background-color: #ffffff;color: #718096;height: 100%;line-height: 1.4;width: 100%;
}
.mail .x_wrapper{
background-color: #edf2f7;
width:100%;
}
.mail .x_content{
width: 100%;
}
.mail .x_inner-body{
background-color: #ffffff;border-color: #e8e5ef;border-radius: 2px;border-width: 1px;margin: 0 auto;padding:0;width: 570px;
}
.mail .x_content-cell{
margin: 0 auto;padding: 0;width: 570px;line-height: 1.5em;
color: #b0adc5;font-size: 12px;
}
.mail .x_content-cell td{
max-width: 100vw;padding: 32px;
}
</style>
<div>
<table class="x_wrapper">
<tbody>
<tr>
<td>
<table class="x_content">
<tbody>
<tr>
<td style="padding: 25px 0;">
<h1 style="font-size: 20px;">代码验证邮件</h1>
</td>
</tr>
<tr>
<td>
<table class="x_inner-body">
<tbody>
<tr>
<td class="mail-content">
<h1 style="font-size: 18px;margin-bottom: 25px;">Minecraft · <servername /><br/><playername /></h1>
<hr>
<table style="width: 100%;">
<tbody>
<tr>
<td>
您正在申请的验证码为
</td>
</tr>
<tr>
<td style="font-weight: bold;">
<br/><recoverycode /></td>
</tr>
<tr>
<td>
<br/>使用指令: /email code <recoverycode /> 来完成验证过程.
</td>
</tr>
<tr>
<td style="text-align:right;">
<br/>
<br/>验证码将在<hoursvalid />小时后失效
</td>
</tr>
<tr>
<td>
<small>
<br/><time />
<br/>请勿回复
</small>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr>
<td>
<table class="x_content-cell">
<tbody>
<tr>
<td>
<p style="color:#b0adc5;">© 2023 IrisCraft. All rights reserved.</p>
<a href="https://www.mcbbs.net/thread-1263385-1-1.html" target="_blank" style="text-decoration: none; font-size: 16px">iriscraft.work</a>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</div>
</div>
+117
View File
@@ -0,0 +1,117 @@
<div class="mail">
<style>
.mail td{
font-family: "Segoe UI", sans-serif;
text-align: center;
font-size: 16px;
color: #718096;
}
.mail th, div, p, a, h1, h2, h3, h4, h5, h6{
font-family: "Segoe UI", sans-serif;
text-align: center;
color: #3d4852;
}
.mail .mail-content {
max-width: 100vw;
padding: 32px;
box-shadow: 0 15px 28px rgba(0, 0, 0, 0.25), 0 10px 10px rgba(0, 0, 0, 0.25);
}
.mail div{
background-color: #ffffff;color: #718096;height: 100%;line-height: 1.4;width: 100%;
}
.mail .x_wrapper{
background-color: #edf2f7;
width:100%;
}
.mail .x_content{
width: 100%;
}
.mail .x_inner-body{
background-color: #ffffff;border-color: #e8e5ef;border-radius: 2px;border-width: 1px;margin: 0 auto;padding:0;width: 570px;
}
.mail .x_content-cell{
margin: 0 auto;padding: 0;width: 570px;line-height: 1.5em;
color: #b0adc5;font-size: 12px;
}
.mail .x_content-cell td{
max-width: 100vw;padding: 32px;
}
</style>
<div>
<table class="x_wrapper">
<tbody>
<tr>
<td>
<table class="x_content">
<tbody>
<tr>
<td style="padding: 25px 0;">
<h1 style="font-size: 20px;">服务器关闭通知</h1>
</td>
</tr>
<tr>
<td>
<table class="x_inner-body">
<tbody>
<tr>
<td class="mail-content">
<h1 style="font-size: 18px;margin-bottom: 25px;">Minecraft · <servername /></h1>
<hr>
<table style="width: 100%;">
<tbody>
<tr>
<td style="font-weight: bold;color: #da1515;">
<br/>紧急通知</td>
</tr>
<tr>
<td>
<br/>服务器当前已被关闭
<br/>
<br/>请及时检查服务器运行状态.
<br/>
</td>
</tr>
<tr>
<td style="text-align:right;">
<br/>
<br/>IrisCraft Team
</td>
</tr>
<tr>
<td>
<small>
<br/><time />
<br/>请勿回复
</small>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr>
<td>
<table class="x_content-cell">
<tbody>
<tr>
<td>
<p style="color:#b0adc5;">© 2023 IrisCraft. All rights reserved.</p>
<a href="https://www.mcbbs.net/thread-1263385-1-1.html" target="_blank" style="text-decoration: none; font-size: 16px">iriscraft.work</a>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</div>
</div>
+119 -20
View File
@@ -1,20 +1,119 @@
<h1>
Dear <playername />,
</h1>
<p>
This is your temporary verification code for the server <servername />:
</p>
<p>
<generatedcode />
</p>
<p>
This code will be valid for the next <minutesvalid /> mins!<br />
Use the command
/verification <generatedcode />
to complete the verification process.
</p>
<p>
See you on <servername />!
</p>
<div class="mail">
<style>
.mail td{
font-family: "Segoe UI", sans-serif;
text-align: center;
font-size: 16px;
color: #718096;
}
.mail th, div, p, a, h1, h2, h3, h4, h5, h6{
font-family: "Segoe UI", sans-serif;
text-align: center;
color: #3d4852;
}
.mail .mail-content {
max-width: 100vw;
padding: 32px;
box-shadow: 0 15px 28px rgba(0, 0, 0, 0.25), 0 10px 10px rgba(0, 0, 0, 0.25);
}
.mail div{
background-color: #ffffff;color: #718096;height: 100%;line-height: 1.4;width: 100%;
}
.mail .x_wrapper{
background-color: #edf2f7;
width:100%;
}
.mail .x_content{
width: 100%;
}
.mail .x_inner-body{
background-color: #ffffff;border-color: #e8e5ef;border-radius: 2px;border-width: 1px;margin: 0 auto;padding:0;width: 570px;
}
.mail .x_content-cell{
margin: 0 auto;padding: 0;width: 570px;line-height: 1.5em;
color: #b0adc5;font-size: 12px;
}
.mail .x_content-cell td{
max-width: 100vw;padding: 32px;
}
</style>
<div>
<table class="x_wrapper">
<tbody>
<tr>
<td>
<table class="x_content">
<tbody>
<tr>
<td style="padding: 25px 0;">
<h1 style="font-size: 20px;">代码验证邮件</h1>
</td>
</tr>
<tr>
<td>
<table class="x_inner-body">
<tbody>
<tr>
<td class="mail-content">
<h1 style="font-size: 18px;margin-bottom: 25px;">Minecraft · <servername /><br/><playername /></h1>
<hr>
<table style="width: 100%;">
<tbody>
<tr>
<td>
您正在申请的验证码为
</td>
</tr>
<tr>
<td style="font-weight: bold;">
<br/><generatedcode /></td>
</tr>
<tr>
<td>
<br/>使用指令: /verification <generatedcode /> 来完成验证过程.
</td>
</tr>
<tr>
<td style="text-align:right;">
<br/>
<br/>验证码将在30分钟后失效
</td>
</tr>
<tr>
<td>
<small>
<br/><time />
<br/>请勿回复
</small>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr>
<td>
<table class="x_content-cell">
<tbody>
<tr>
<td>
<p style="color:#b0adc5;">© 2023 IrisCraft. All rights reserved.</p>
<a href="https://www.mcbbs.net/thread-1263385-1-1.html" target="_blank" style="text-decoration: none; font-size: 16px">iriscraft.work</a>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</div>
</div>
-3
View File
@@ -1,3 +0,0 @@
Welcome {PLAYER} on {SERVER} server
This server uses AuthMeReloaded protection!
@@ -1,145 +0,0 @@
package fr.xephi.authme;
import ch.jalu.configme.resource.PropertyReader;
import ch.jalu.configme.resource.PropertyResource;
import ch.jalu.injector.Injector;
import ch.jalu.injector.InjectorBuilder;
import com.google.common.io.Files;
import fr.xephi.authme.api.v3.AuthMeApi;
import fr.xephi.authme.command.CommandHandler;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.initialization.DataFolder;
import fr.xephi.authme.listener.BlockListener;
import fr.xephi.authme.permission.PermissionsManager;
import fr.xephi.authme.process.Management;
import fr.xephi.authme.process.login.ProcessSyncPlayerLogin;
import fr.xephi.authme.security.PasswordSecurity;
import fr.xephi.authme.service.BukkitService;
import fr.xephi.authme.service.bungeecord.BungeeReceiver;
import fr.xephi.authme.service.bungeecord.BungeeSender;
import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.task.purge.PurgeService;
import org.bukkit.Bukkit;
import org.bukkit.Server;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPluginLoader;
import org.bukkit.scheduler.BukkitScheduler;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.logging.Logger;
import static fr.xephi.authme.settings.properties.AuthMeSettingsRetriever.buildConfigurationData;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* Integration test verifying that all services can be initialized in {@link AuthMe}
* with the {@link Injector}.
*/
@RunWith(MockitoJUnitRunner.class)
public class AuthMeInitializationTest {
@Mock
private Server server;
@Mock
private PluginManager pluginManager;
private AuthMe authMe;
private File dataFolder;
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Before
public void initAuthMe() throws IOException {
dataFolder = temporaryFolder.newFolder();
File settingsFile = new File(dataFolder, "config.yml");
given(server.getLogger()).willReturn(Logger.getAnonymousLogger());
JavaPluginLoader pluginLoader = new JavaPluginLoader(server);
Files.copy(TestHelper.getJarFile(TestHelper.PROJECT_ROOT + "config.test.yml"), settingsFile);
// Mock / wire various Bukkit components
ReflectionTestUtils.setField(Bukkit.class, null, "server", server);
given(server.getPluginManager()).willReturn(pluginManager);
// PluginDescriptionFile is final: need to create a sample one
PluginDescriptionFile descriptionFile = new PluginDescriptionFile(
"AuthMe", "N/A", AuthMe.class.getCanonicalName());
// Initialize AuthMe
authMe = new AuthMe(pluginLoader, descriptionFile, dataFolder, null);
}
@Test
public void shouldInitializeAllServices() {
// given
PropertyReader reader = mock(PropertyReader.class);
PropertyResource resource = mock(PropertyResource.class);
given(resource.createReader()).willReturn(reader);
Settings settings = new Settings(dataFolder, resource, null, buildConfigurationData());
TestHelper.setupLogger();
Injector injector = new InjectorBuilder()
.addDefaultHandlers("fr.xephi.authme")
.create();
injector.provide(DataFolder.class, dataFolder);
injector.register(Server.class, server);
injector.register(PluginManager.class, pluginManager);
injector.register(AuthMe.class, authMe);
injector.register(Settings.class, settings);
injector.register(DataSource.class, mock(DataSource.class));
injector.register(BukkitService.class, mock(BukkitService.class));
// when
authMe.instantiateServices(injector);
authMe.registerEventListeners(injector);
// then
// Take a few samples and ensure that they are not null
assertThat(injector.getIfAvailable(AuthMeApi.class), not(nullValue()));
assertThat(injector.getIfAvailable(BlockListener.class), not(nullValue()));
assertThat(injector.getIfAvailable(BungeeReceiver.class), not(nullValue()));
assertThat(injector.getIfAvailable(BungeeSender.class), not(nullValue()));
assertThat(injector.getIfAvailable(CommandHandler.class), not(nullValue()));
assertThat(injector.getIfAvailable(Management.class), not(nullValue()));
assertThat(injector.getIfAvailable(PasswordSecurity.class), not(nullValue()));
assertThat(injector.getIfAvailable(PermissionsManager.class), not(nullValue()));
assertThat(injector.getIfAvailable(ProcessSyncPlayerLogin.class), not(nullValue()));
assertThat(injector.getIfAvailable(PurgeService.class), not(nullValue()));
}
@Test
public void shouldHandlePrematureShutdownGracefully() {
// given
BukkitScheduler scheduler = mock(BukkitScheduler.class);
given(server.getScheduler()).willReturn(scheduler);
// Make sure ConsoleLogger has no logger reference since that may happen on unexpected stops
ReflectionTestUtils.setField(ConsoleLogger.class, null, "logger", null);
// when
authMe.onDisable();
// then - no exceptions
verify(scheduler).getActiveWorkers(); // via TaskCloser
}
}
@@ -1,136 +0,0 @@
package fr.xephi.authme;
import fr.xephi.authme.data.auth.PlayerAuth;
import fr.xephi.authme.security.crypts.HashedPassword;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import java.util.Objects;
/**
* Custom matchers for AuthMe entities.
*/
// Justification: Javadoc would be huge because of the many parameters
@SuppressWarnings("checkstyle:MissingJavadocMethod")
public final class AuthMeMatchers {
private AuthMeMatchers() {
}
public static Matcher<? super HashedPassword> equalToHash(String hash) {
return equalToHash(new HashedPassword(hash));
}
public static Matcher<? super HashedPassword> equalToHash(String hash, String salt) {
return equalToHash(new HashedPassword(hash, salt));
}
public static Matcher<? super HashedPassword> equalToHash(HashedPassword hash) {
return new TypeSafeMatcher<HashedPassword>() {
@Override
public boolean matchesSafely(HashedPassword item) {
return Objects.equals(hash.getHash(), item.getHash())
&& Objects.equals(hash.getSalt(), item.getSalt());
}
@Override
public void describeTo(Description description) {
String representation = "'" + hash.getHash() + "'";
if (hash.getSalt() != null) {
representation += ", '" + hash.getSalt() + "'";
}
description.appendValue("HashedPassword(" + representation + ")");
}
};
}
public static Matcher<PlayerAuth> hasAuthBasicData(String name, String realName,
String email, String lastIp) {
return new TypeSafeMatcher<PlayerAuth>() {
@Override
public boolean matchesSafely(PlayerAuth item) {
return Objects.equals(name, item.getNickname())
&& Objects.equals(realName, item.getRealName())
&& Objects.equals(email, item.getEmail())
&& Objects.equals(lastIp, item.getLastIp());
}
@Override
public void describeTo(Description description) {
description.appendValue(String.format("PlayerAuth with name %s, realname %s, email %s, lastIp %s",
name, realName, email, lastIp));
}
@Override
public void describeMismatchSafely(PlayerAuth item, Description description) {
description.appendValue(String.format("PlayerAuth with name %s, realname %s, email %s, lastIp %s",
item.getNickname(), item.getRealName(), item.getEmail(), item.getLastIp()));
}
};
}
public static Matcher<? super PlayerAuth> hasRegistrationInfo(String registrationIp, long registrationDate) {
return new TypeSafeMatcher<PlayerAuth>() {
@Override
public boolean matchesSafely(PlayerAuth item) {
return Objects.equals(registrationIp, item.getRegistrationIp())
&& Objects.equals(registrationDate, item.getRegistrationDate());
}
@Override
public void describeTo(Description description) {
description.appendValue(String.format("PlayerAuth with reg. IP %s and reg date %d",
registrationIp, registrationDate));
}
@Override
public void describeMismatchSafely(PlayerAuth item, Description description) {
description.appendValue(String.format("PlayerAuth with reg. IP %s and reg date %d",
item.getRegistrationIp(), item.getRegistrationDate()));
}
};
}
public static Matcher<? super PlayerAuth> hasAuthLocation(PlayerAuth auth) {
return hasAuthLocation(auth.getQuitLocX(), auth.getQuitLocY(), auth.getQuitLocZ(), auth.getWorld(),
auth.getYaw(), auth.getPitch());
}
public static Matcher<? super PlayerAuth> hasAuthLocation(double x, double y, double z,
String world, float yaw, float pitch) {
return new TypeSafeMatcher<PlayerAuth>() {
@Override
public boolean matchesSafely(PlayerAuth item) {
return Objects.equals(x, item.getQuitLocX())
&& Objects.equals(y, item.getQuitLocY())
&& Objects.equals(z, item.getQuitLocZ())
&& Objects.equals(world, item.getWorld())
&& Objects.equals(yaw, item.getYaw())
&& Objects.equals(pitch, item.getPitch());
}
@Override
public void describeTo(Description description) {
description.appendValue(
String.format("PlayerAuth with quit location (x: %f, y: %f, z: %f, world: %s, yaw: %f, pitch: %f)",
x, y, z, world, yaw, pitch));
}
};
}
public static Matcher<String> stringWithLength(int length) {
return new TypeSafeMatcher<String>() {
@Override
protected boolean matchesSafely(String item) {
return item != null && item.length() == length;
}
@Override
public void describeTo(Description description) {
description.appendText("String with length " + length);
}
};
}
}
@@ -1,165 +0,0 @@
package fr.xephi.authme;
import java.io.File;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/**
* Collects available classes by walking through a source directory.
* <p>
* This is a naive, zero dependency collector that walks through a file directory
* and loads classes from the class loader based on the .java files it encounters.
* This is a very slow approach and should be avoided for production code.
* <p>
* For more performant approaches, see e.g. <a href="https://github.com/ronmamo/reflections">org.reflections</a>.
*/
public class ClassCollector {
private final String root;
private final String nonCodePath;
/**
* Constructor. The arguments make up the path from which the collector will start scanning.
*
* @param nonCodePath beginning of the starting path that are not Java packages, e.g. {@code src/main/java/}
* @param packagePath folders following {@code nonCodePath} that are packages, e.g. {@code com/project/app}
*/
public ClassCollector(String nonCodePath, String packagePath) {
if (!nonCodePath.endsWith("/") && !nonCodePath.endsWith("\\")) {
nonCodePath = nonCodePath.concat(File.separator);
}
this.root = nonCodePath + packagePath;
this.nonCodePath = nonCodePath;
}
/**
* Collects all classes from the parent folder and below.
*
* @return all classes
*/
public List<Class<?>> collectClasses() {
return collectClasses(x -> true);
}
/**
* Collects all classes from the parent folder and below which are of type {@link T}.
*
* @param parent the parent which classes need to extend (or be equal to) in order to be collected
* @param <T> the parent type
* @return list of matching classes
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public <T> List<Class<? extends T>> collectClasses(Class<T> parent) {
List<Class<?>> classes = collectClasses(parent::isAssignableFrom);
return new ArrayList<>((List) classes);
}
/**
* Collects all classes from the parent folder and below which match the given predicate.
*
* @param filter the predicate classes need to satisfy in order to be collected
* @return list of matching classes
*/
public List<Class<?>> collectClasses(Predicate<Class<?>> filter) {
File rootFolder = new File(root);
List<Class<?>> collection = new ArrayList<>();
gatherClassesFromFile(rootFolder, filter, collection);
return collection;
}
/**
* Constructs an instance of all classes which are of the provided type {@code clazz}.
* This method assumes that every class has an accessible no-args constructor for creation.
*
* @param parent the parent which classes need to extend (or be equal to) in order to be instantiated
* @param <T> the parent type
* @return collection of created objects
*/
public <T> List<T> getInstancesOfType(Class<T> parent) {
return getInstancesOfType(parent, (clz) -> {
try {
return canInstantiate(clz) ? clz.newInstance() : null;
} catch (InstantiationException | IllegalAccessException e) {
throw new IllegalStateException(e);
}
});
}
/**
* Constructs an instance of all classes which are of the provided type {@code clazz}
* with the provided {@code instantiator}.
*
* @param parent the parent which classes need to extend (or be equal to) in order to be instantiated
* @param instantiator function which returns an object of the given class, or null to skip the class
* @param <T> the parent type
* @return collection of created objects
*/
public <T> List<T> getInstancesOfType(Class<T> parent, Function<Class<? extends T>, T> instantiator) {
return collectClasses(parent)
.stream()
.map(instantiator)
.filter(o -> o != null)
.collect(Collectors.toList());
}
/**
* Returns whether the given class can be instantiated, i.e. if it is not abstract, an interface, etc.
*
* @param clazz the class to process
* @return true if the class can be instantiated, false otherwise
*/
public static boolean canInstantiate(Class<?> clazz) {
return clazz != null && !clazz.isEnum() && !clazz.isInterface()
&& !clazz.isArray() && !Modifier.isAbstract(clazz.getModifiers());
}
/**
* Recursively collects the classes based on the files in the directory and in its child directories.
*
* @param folder the folder to scan
* @param filter the class predicate
* @param collection collection to add classes to
*/
private void gatherClassesFromFile(File folder, Predicate<Class<?>> filter, List<Class<?>> collection) {
File[] files = folder.listFiles();
if (files == null) {
throw new IllegalStateException("Could not read files from '" + folder + "'");
}
for (File file : files) {
if (file.isDirectory()) {
gatherClassesFromFile(file, filter, collection);
} else if (file.isFile()) {
Class<?> clazz = loadTaskClassFromFile(file);
if (clazz != null && filter.test(clazz)) {
collection.add(clazz);
}
}
}
}
/**
* Loads a class from the class loader based on the given file.
*
* @param file the file whose corresponding Java class should be retrieved
* @return the corresponding class, or null if not applicable
*/
private Class<?> loadTaskClassFromFile(File file) {
if (!file.getName().endsWith(".java")) {
return null;
}
String filePath = file.getPath();
String className = filePath
.substring(nonCodePath.length(), filePath.length() - 5)
.replace(File.separator, ".");
try {
return Class.forName(className);
} catch (ClassNotFoundException e) {
throw new IllegalStateException(e);
}
}
}
@@ -1,173 +0,0 @@
package fr.xephi.authme;
import ch.jalu.configme.properties.Property;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import fr.xephi.authme.data.captcha.CaptchaCodeStorage;
import fr.xephi.authme.datasource.AbstractSqlDataSource;
import fr.xephi.authme.datasource.Columns;
import fr.xephi.authme.datasource.columnshandler.DataSourceColumn;
import fr.xephi.authme.datasource.columnshandler.PlayerAuthColumn;
import fr.xephi.authme.datasource.mysqlextensions.MySqlExtension;
import fr.xephi.authme.initialization.HasCleanup;
import fr.xephi.authme.process.register.executors.RegistrationMethod;
import fr.xephi.authme.security.crypts.Whirlpool;
import fr.xephi.authme.util.expiring.ExpiringMap;
import fr.xephi.authme.util.expiring.ExpiringSet;
import fr.xephi.authme.util.expiring.TimedCounter;
import org.junit.Test;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
/**
* Contains consistency tests across all AuthMe classes.
*/
public class ClassesConsistencyTest {
/** Contains all production classes. */
private static final List<Class<?>> ALL_CLASSES =
new ClassCollector(TestHelper.SOURCES_FOLDER, TestHelper.PROJECT_ROOT).collectClasses();
/** Expiring structure types. */
private static final Set<Class<?>> EXPIRING_STRUCTURES = ImmutableSet.of(
ExpiringSet.class, ExpiringMap.class, TimedCounter.class, CaptchaCodeStorage.class);
/** Immutable types, which are allowed to be used in non-private constants. */
private static final Set<Class<?>> IMMUTABLE_TYPES = ImmutableSet.of(
/* JDK */
int.class, long.class, float.class, String.class, File.class, Enum.class, collectionsUnmodifiableList(),
Charset.class,
/* AuthMe */
Property.class, RegistrationMethod.class, DataSourceColumn.class, PlayerAuthColumn.class,
/* Guava */
ImmutableMap.class, ImmutableList.class);
/** Classes excluded from the field visibility test. */
private static final Set<Class<?>> CLASSES_EXCLUDED_FROM_VISIBILITY_TEST = ImmutableSet.of(
Whirlpool.class, // not our implementation, so we don't touch it
MySqlExtension.class, // has immutable protected fields used by all children
AbstractSqlDataSource.class, // protected members for inheritance
Columns.class // uses non-static String constants, which is safe
);
/**
* Checks that there aren't two classes with the same name; this is confusing and should be avoided.
*/
@Test
public void shouldNotHaveSameName() {
// given
Set<String> names = new HashSet<>();
// when / then
for (Class<?> clazz : ALL_CLASSES) {
if (!names.add(clazz.getSimpleName())) {
fail("Class with name '" + clazz.getSimpleName() + "' already encountered!");
}
}
}
/**
* Checks that fields of classes are either private or static final fields of an immutable type.
*/
@Test
public void shouldHaveNonPrivateConstantsOnly() {
// given / when
Set<String> invalidFields = ALL_CLASSES.stream()
.filter(clz -> !CLASSES_EXCLUDED_FROM_VISIBILITY_TEST.contains(clz))
.map(Class::getDeclaredFields)
.flatMap(Arrays::stream)
.filter(f -> !f.getName().contains("$"))
.filter(f -> hasIllegalFieldVisibility(f))
.map(f -> formatField(f))
.collect(Collectors.toSet());
// then
if (!invalidFields.isEmpty()) {
fail("Found " + invalidFields.size() + " fields with non-private, mutable fields:\n- "
+ String.join("\n- ", invalidFields));
}
}
private static boolean hasIllegalFieldVisibility(Field field) {
final int modifiers = field.getModifiers();
if (Modifier.isPrivate(modifiers)) {
return false;
} else if (!Modifier.isStatic(modifiers) || !Modifier.isFinal(modifiers)) {
return true;
}
// Field is non-private, static and final
Class<?> valueType;
if (Collection.class.isAssignableFrom(field.getType()) || Map.class.isAssignableFrom(field.getType())) {
// For collections/maps, need to check the actual type to ensure it's an unmodifiable implementation
Object value = ReflectionTestUtils.getFieldValue(field, null);
valueType = value.getClass();
} else {
valueType = field.getType();
}
// Field is static, final, and not private -> check that it is immutable type
return IMMUTABLE_TYPES.stream()
.noneMatch(immutableType -> immutableType.isAssignableFrom(valueType));
}
/**
* Prints out the field with its modifiers.
*
* @param field the field to format
* @return description of the field
*/
private static String formatField(Field field) {
String modifiersText = Modifier.toString(field.getModifiers());
return String.format("[%s] %s %s %s", field.getDeclaringClass().getSimpleName(), modifiersText.trim(),
field.getType().getSimpleName(), field.getName());
}
/**
* Checks that classes with expiring collections (such as {@link ExpiringMap}) implement the {@link HasCleanup}
* interface to regularly clean up expired data.
*/
@Test
public void shouldImplementHasCleanup() {
// given / when / then
for (Class<?> clazz : ALL_CLASSES) {
if (hasExpiringCollectionAsField(clazz) && !EXPIRING_STRUCTURES.contains(clazz)) {
assertThat("Class '" + clazz.getSimpleName() + "' has expiring collections, should implement HasCleanup",
HasCleanup.class.isAssignableFrom(clazz), equalTo(true));
}
}
}
private static boolean hasExpiringCollectionAsField(Class<?> clazz) {
for (Field field : clazz.getDeclaredFields()) {
if (EXPIRING_STRUCTURES.stream().anyMatch(t -> t.isAssignableFrom(field.getType()))) {
return true;
}
}
return false;
}
/**
* @return the concrete class of the unmodifiable list as returned by {@link Collections#unmodifiableList(List)}.
*/
private static Class<?> collectionsUnmodifiableList() {
return Collections.unmodifiableList(new ArrayList<>()).getClass();
}
}
@@ -1,44 +0,0 @@
package fr.xephi.authme;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.junit.Test;
import java.io.File;
import java.util.List;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
/**
* Consistency test for the CodeClimate configuration file.
*/
public class CodeClimateConfigTest {
private static final String CONFIG_FILE = ".codeclimate.yml";
@Test
public void shouldHaveExistingClassesInExclusions() {
// given / when
FileConfiguration configuration = YamlConfiguration.loadConfiguration(new File(CONFIG_FILE));
List<String> excludePaths = configuration.getStringList("exclude_patterns");
// then
assertThat(excludePaths, not(empty()));
removeTestsExclusionOrThrow(excludePaths);
for (String path : excludePaths) {
if (!new File(path).exists()) {
fail("Path '" + path + "' does not exist!");
}
}
}
private static void removeTestsExclusionOrThrow(List<String> excludePaths) {
boolean wasRemoved = excludePaths.removeIf("src/test/java/**/*Test.java"::equals);
assertThat("Expected an exclusion for test classes",
wasRemoved, equalTo(true));
}
}
@@ -1,227 +0,0 @@
package fr.xephi.authme;
import fr.xephi.authme.output.LogLevel;
import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.settings.properties.PluginSettings;
import fr.xephi.authme.settings.properties.SecuritySettings;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;
import java.util.logging.Logger;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
/**
* Test for {@link ConsoleLogger}.
*/
@RunWith(MockitoJUnitRunner.class)
public class ConsoleLoggerTest {
private ConsoleLogger consoleLogger;
@Mock
private Logger logger;
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
private File logFile;
@Before
public void setMockLogger() throws IOException {
File folder = temporaryFolder.newFolder();
File logFile = new File(folder, "authme.log");
if (!logFile.createNewFile()) {
throw new IOException("Could not create file '" + logFile.getPath() + "'");
}
ConsoleLogger.initialize(logger, logFile);
this.logFile = logFile;
this.consoleLogger = new ConsoleLogger("test");
}
@After
public void closeFileHandlers() {
ConsoleLogger.closeFileWriter();
}
/**
* Resets the ConsoleLogger back to its defaults after running all tests. Especially important
* is that we no longer enable logging to a file as the log file we've supplied will no longer
* be around after this test class has finished.
*/
@AfterClass
public static void resetConsoleToDefault() {
ConsoleLogger.initializeSharedSettings(newSettings(false, LogLevel.INFO));
}
@Test
public void shouldLogToFile() throws IOException {
// given
Settings settings = newSettings(true, LogLevel.FINE);
ConsoleLogger.initializeSharedSettings(settings);
consoleLogger.initializeSettings(settings);
// when
consoleLogger.fine("Logging a FINE message");
consoleLogger.debug("Logging a DEBUG message");
consoleLogger.info("This is an INFO message");
// then
verify(logger, times(2)).info(anyString());
verifyNoMoreInteractions(logger);
List<String> loggedLines = Files.readAllLines(logFile.toPath(), StandardCharsets.UTF_8);
assertThat(loggedLines, hasSize(2));
assertThat(loggedLines.get(0), containsString("[FINE] Logging a FINE message"));
assertThat(loggedLines.get(1), containsString("[INFO] This is an INFO message"));
}
@Test
public void shouldNotLogToFile() {
// given
Settings settings = newSettings(false, LogLevel.DEBUG);
ConsoleLogger.initializeSharedSettings(settings);
consoleLogger.initializeSettings(settings);
// when
consoleLogger.debug("Created test");
consoleLogger.warning("Encountered a warning");
// then
verify(logger).info("[DEBUG] Created test");
verify(logger).warning("Encountered a warning");
verifyNoMoreInteractions(logger);
assertThat(logFile.length(), equalTo(0L));
}
@Test
public void shouldLogStackTraceToFile() throws IOException {
// given
Settings settings = newSettings(true, LogLevel.INFO);
ConsoleLogger.initializeSharedSettings(settings);
Exception e = new IllegalStateException("Test exception message");
// when
consoleLogger.info("Info text");
consoleLogger.debug("Debug message");
consoleLogger.fine("Fine-level message");
consoleLogger.logException("Exception occurred:", e);
// then
verify(logger).info("Info text");
verify(logger).warning("Exception occurred: [IllegalStateException]: Test exception message");
verifyNoMoreInteractions(logger);
List<String> loggedLines = Files.readAllLines(logFile.toPath(), StandardCharsets.UTF_8);
assertThat(loggedLines.size(), greaterThan(3));
assertThat(loggedLines.get(0), containsString("[INFO] Info text"));
assertThat(loggedLines.get(1),
containsString("[WARN] Exception occurred: [IllegalStateException]: Test exception message"));
// Check that we have this class' full name somewhere in the file -> stacktrace of Exception e
assertThat(String.join("", loggedLines), containsString(getClass().getCanonicalName()));
}
@Test
public void shouldSupportVariousDebugMethods() throws IOException {
// given
Settings settings = newSettings(true, LogLevel.DEBUG);
ConsoleLogger.initializeSharedSettings(settings);
consoleLogger.initializeSettings(settings);
// when
consoleLogger.debug("Got {0} entries", 17);
consoleLogger.debug("Player `{0}` is in world `{1}`", "Bobby", new WorldDummy("world"));
consoleLogger.debug("{0} quick {1} jump over {2} lazy {3} (reason: {4})", 5, "foxes", 3, "dogs", null);
consoleLogger.debug(() -> "Too little too late");
// then
verify(logger).info("[DEBUG] Got 17 entries");
verify(logger).info("[DEBUG] Player `Bobby` is in world `w[world]`");
verify(logger).info("[DEBUG] 5 quick foxes jump over 3 lazy dogs (reason: null)");
verify(logger).info("[DEBUG] Too little too late");
verifyNoMoreInteractions(logger);
List<String> loggedLines = Files.readAllLines(logFile.toPath(), StandardCharsets.UTF_8);
assertThat(loggedLines, contains(
containsString("[DEBUG] Got 17 entries"),
containsString("[DEBUG] Player `Bobby` is in world `w[world]`"),
containsString("[DEBUG] 5 quick foxes jump over 3 lazy dogs (reason: null)"),
containsString("[DEBUG] Too little too late")));
}
@Test
public void shouldCloseFileWriterDespiteExceptionOnFlush() throws IOException {
// given
FileWriter fileWriter = mock(FileWriter.class);
doThrow(new IOException("Error during flush")).when(fileWriter).flush();
ReflectionTestUtils.setField(ConsoleLogger.class, null, "fileWriter", fileWriter);
// when
ConsoleLogger.closeFileWriter();
// then
verify(fileWriter).flush();
verify(fileWriter).close();
assertThat(ReflectionTestUtils.getFieldValue(ConsoleLogger.class, null, "fileWriter"), nullValue());
}
@Test
public void shouldHandleExceptionOnFileWriterClose() throws IOException {
// given
FileWriter fileWriter = mock(FileWriter.class);
doThrow(new IOException("Cannot close")).when(fileWriter).close();
ReflectionTestUtils.setField(ConsoleLogger.class, null, "fileWriter", fileWriter);
// when
ConsoleLogger.closeFileWriter();
// then
verify(fileWriter).flush();
verify(fileWriter).close();
assertThat(ReflectionTestUtils.getFieldValue(ConsoleLogger.class, null, "fileWriter"), nullValue());
}
private static Settings newSettings(boolean logToFile, LogLevel logLevel) {
Settings settings = mock(Settings.class);
given(settings.getProperty(SecuritySettings.USE_LOGGING)).willReturn(logToFile);
given(settings.getProperty(PluginSettings.LOG_LEVEL)).willReturn(logLevel);
return settings;
}
private static final class WorldDummy {
private final String name;
WorldDummy(String name) {
this.name = name;
}
@Override
public String toString() {
return "w[" + name + "]";
}
}
}
@@ -1,91 +0,0 @@
package fr.xephi.authme;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import static org.junit.Assert.fail;
/**
* Matcher which checks with reflection that all fields have the same value.
* This matcher considers all non-static fields until the Object parent.
*/
public final class IsEqualByReflectionMatcher<T> extends TypeSafeMatcher<T> {
private final T expected;
private IsEqualByReflectionMatcher(T expected) {
this.expected = expected;
}
/**
* Creates a matcher that checks if all fields are the same as on the {@code expected} object.
*
* @param expected the object to match
* @param <T> the object's type
* @return the matcher for the expected object
*/
public static <T> Matcher<T> hasEqualValuesOnAllFields(T expected) {
return new IsEqualByReflectionMatcher<>(expected);
}
@Override
protected boolean matchesSafely(T item) {
return assertAreFieldsEqual(item);
}
@Override
public void describeTo(Description description) {
description.appendText("parameters " + expected);
}
/**
* Checks that all fields of the given {@code item} are equal to the {@link #expected} object. Both objects must
* be exactly of the same type.
*
* @param item the object to check
* @return true if all fields are equal, false otherwise
*/
private boolean assertAreFieldsEqual(T item) {
if (expected.getClass() != item.getClass()) {
fail("Classes don't match, got " + expected.getClass().getSimpleName()
+ " and " + item.getClass().getSimpleName());
return false;
}
List<Field> fieldsToCheck = getAllFields(expected);
for (Field field : fieldsToCheck) {
Object lhsValue = ReflectionTestUtils.getFieldValue(field, expected);
Object rhsValue = ReflectionTestUtils.getFieldValue(field, item);
if (!Objects.equals(lhsValue, rhsValue)) {
fail("Field '" + field.getName() + "' does not have same value: '"
+ lhsValue + "' vs. '" + rhsValue + "'");
return false;
}
}
return true;
}
private static List<Field> getAllFields(Object object) {
List<Field> fields = new ArrayList<>();
Class<?> currentClass = object.getClass();
while (currentClass != null) {
for (Field f : currentClass.getDeclaredFields()) {
if (!Modifier.isStatic(f.getModifiers()) && !f.isSynthetic()) {
fields.add(f);
}
}
if (currentClass == Object.class) {
break;
}
currentClass = currentClass.getSuperclass();
}
return fields;
}
}
@@ -1,153 +0,0 @@
package fr.xephi.authme;
import ch.jalu.injector.handlers.postconstruct.PostConstructMethodInvoker;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import static java.lang.String.format;
/**
* Offers reflection functionality to set up tests. Use only when absolutely necessary.
*/
public final class ReflectionTestUtils {
private ReflectionTestUtils() {
// Util class
}
/**
* Sets the field of a given object to a new value with reflection.
*
* @param clazz the class declaring the field
* @param instance the instance to modify (pass null for static fields)
* @param fieldName the field name
* @param value the value to set the field to
* @param <T> the instance type
*/
public static <T> void setField(Class<? super T> clazz, T instance, String fieldName, Object value) {
try {
Field field = getField(clazz, fieldName);
field.set(instance, value);
} catch (IllegalAccessException e) {
throw new IllegalStateException(
format("Could not set value to field '%s' for instance '%s' of class '%s'",
fieldName, instance, clazz.getName()), e);
}
}
/**
* Sets the field on the given instance to the new value.
*
* @param instance the instance to modify
* @param fieldName the field name
* @param value the value to set the field to
*/
@SuppressWarnings("unchecked")
public static void setField(Object instance, String fieldName, Object value) {
setField((Class) instance.getClass(), instance, fieldName, value);
}
private static <T> Field getField(Class<T> clazz, String fieldName) {
try {
Field field = clazz.getDeclaredField(fieldName);
field.setAccessible(true);
return field;
} catch (NoSuchFieldException e) {
throw new IllegalStateException(format("Could not get field '%s' from class '%s'",
fieldName, clazz.getName()), e);
}
}
@SuppressWarnings("unchecked")
public static <T, V> V getFieldValue(Class<T> clazz, T instance, String fieldName) {
Field field = getField(clazz, fieldName);
return getFieldValue(field, instance);
}
/**
* Returns the value of the field on the given instance. Wraps exceptions into a runtime exception.
*
* @param field the field to read
* @param instance the instance to get the value from, null if field is static
* @param <V> type of the field
* @return value of the field
*/
@SuppressWarnings("unchecked")
public static <V> V getFieldValue(Field field, Object instance) {
field.setAccessible(true);
try {
return (V) field.get(instance);
} catch (IllegalAccessException e) {
throw new IllegalStateException("Could not get value of field '" + field.getName() + "'", e);
}
}
/**
* Returns the method on the given class with the supplied parameter types.
*
* @param clazz the class to retrieve a method from
* @param methodName the name of the method
* @param parameterTypes the parameter types the method to retrieve has
* @return the method of the class, set to be accessible
*/
public static Method getMethod(Class<?> clazz, String methodName, Class<?>... parameterTypes) {
try {
Method method = clazz.getDeclaredMethod(methodName, parameterTypes);
method.setAccessible(true);
return method;
} catch (NoSuchMethodException e) {
throw new IllegalStateException("Could not retrieve method '" + methodName + "' from class '"
+ clazz.getName() + "'");
}
}
/**
* Invokes the given method on the provided instance with the given parameters.
*
* @param method the method to invoke
* @param instance the instance to invoke the method on (null for static methods)
* @param parameters the parameters to pass to the method
* @param <V> return value of the method
* @return method return value
*/
@SuppressWarnings("unchecked")
public static <V> V invokeMethod(Method method, Object instance, Object... parameters) {
method.setAccessible(true);
try {
return (V) method.invoke(instance, parameters);
} catch (InvocationTargetException | IllegalAccessException e) {
throw new IllegalStateException("Could not invoke method '" + method + "'", e);
}
}
/**
* Runs all methods annotated with {@link javax.annotation.PostConstruct} on the given instance
* (including such methods on superclasses).
*
* @param instance the instance to process
*/
public static void invokePostConstructMethods(Object instance) {
// Use the implementation of the injector to invoke all @PostConstruct methods the same way
new PostConstructMethodInvoker().postProcess(instance, null, null);
}
/**
* Creates a new instance of the given class, using a no-args constructor (which may be hidden).
*
* @param clazz the class to instantiate
* @param <T> the class' type
* @return the created instance
*/
public static <T> T newInstance(Class<T> clazz) {
try {
Constructor<T> constructor = clazz.getDeclaredConstructor();
constructor.setAccessible(true);
return constructor.newInstance();
} catch (ReflectiveOperationException e) {
throw new IllegalStateException("Could not invoke no-args constructor of class " + clazz, e);
}
}
}
@@ -1,121 +0,0 @@
package fr.xephi.authme;
import ch.jalu.configme.properties.Property;
import fr.xephi.authme.settings.Settings;
import org.bukkit.entity.Player;
import org.mockito.Mockito;
import java.io.File;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.UnknownHostException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.logging.Logger;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
/**
* AuthMe test utilities.
*/
public final class TestHelper {
public static final String SOURCES_FOLDER = "src/main/java/";
public static final String TEST_SOURCES_FOLDER = "src/test/java/";
public static final String TEST_RESOURCES_FOLDER = "src/test/resources/";
public static final String PROJECT_ROOT = "/fr/xephi/authme/";
private TestHelper() {
}
/**
* Return a {@link File} to a file in the JAR's resources (main or test).
*
* @param path The absolute path to the file
* @return The project file
*/
public static File getJarFile(String path) {
URI uri = getUriOrThrow(path);
return new File(uri.getPath());
}
/**
* Return a {@link Path} to a file in the JAR's resources (main or test).
*
* @param path The absolute path to the file
* @return The Path object to the file
*/
public static Path getJarPath(String path) {
String sqlFilePath = getUriOrThrow(path).getPath();
// Windows prepends the path with a '/' or '\', which Paths cannot handle
String appropriatePath = System.getProperty("os.name").contains("indow")
? sqlFilePath.substring(1)
: sqlFilePath;
return Paths.get(appropriatePath);
}
private static URI getUriOrThrow(String path) {
URL url = TestHelper.class.getResource(path);
if (url == null) {
throw new IllegalStateException("File '" + path + "' could not be loaded");
}
try {
return new URI(url.toString());
} catch (URISyntaxException e) {
throw new IllegalStateException("File '" + path + "' cannot be converted to a URI");
}
}
/**
* Assign the necessary fields on ConsoleLogger with mocks.
*
* @return The logger mock used
*/
public static Logger setupLogger() {
Logger logger = Mockito.mock(Logger.class);
ConsoleLogger.initialize(logger, null);
return logger;
}
/**
* Set ConsoleLogger to use a new real logger.
*
* @return The real logger used by ConsoleLogger
*/
public static Logger setRealLogger() {
Logger logger = Logger.getAnonymousLogger();
ConsoleLogger.initialize(logger, null);
return logger;
}
/**
* Configures the player mock to return the given IP address.
*
* @param player the player mock
* @param ip the ip address it should return
*/
public static void mockIpAddressToPlayer(Player player, String ip) {
try {
InetAddress inetAddress = InetAddress.getByName(ip);
InetSocketAddress inetSocketAddress = new InetSocketAddress(inetAddress, 8093);
given(player.getAddress()).willReturn(inetSocketAddress);
} catch (UnknownHostException e) {
throw new IllegalStateException("Invalid IP address: " + ip, e);
}
}
/**
* Configures the Settings mock to return the property's default value for any given property.
*
* @param settings the settings mock
*/
@SuppressWarnings("unchecked")
public static void returnDefaultsForAllProperties(Settings settings) {
given(settings.getProperty(any(Property.class)))
.willAnswer(invocation -> ((Property<?>) invocation.getArgument(0)).getDefaultValue());
}
}
@@ -1,558 +0,0 @@
package fr.xephi.authme.api.v3;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ReflectionTestUtils;
import fr.xephi.authme.data.auth.PlayerAuth;
import fr.xephi.authme.data.auth.PlayerCache;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.process.Management;
import fr.xephi.authme.process.register.executors.ApiPasswordRegisterParams;
import fr.xephi.authme.process.register.executors.RegistrationMethod;
import fr.xephi.authme.security.PasswordSecurity;
import fr.xephi.authme.security.crypts.HashedPassword;
import fr.xephi.authme.service.GeoIpService;
import fr.xephi.authme.service.ValidationService;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.time.Instant;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.stream.Collectors;
import static fr.xephi.authme.IsEqualByReflectionMatcher.hasEqualValuesOnAllFields;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.sameInstance;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.hamcrest.MockitoHamcrest.argThat;
/**
* Test for {@link AuthMeApi}.
*/
@RunWith(MockitoJUnitRunner.class)
public class AuthMeApiTest {
@InjectMocks
private AuthMeApi api;
@Mock
private ValidationService validationService;
@Mock
private DataSource dataSource;
@Mock
private Management management;
@Mock
private PasswordSecurity passwordSecurity;
@Mock
private PlayerCache playerCache;
@Mock
private AuthMe authMe;
@Mock
private GeoIpService geoIpService;
@Test
public void shouldReturnInstanceOrNull() {
AuthMeApi result = AuthMeApi.getInstance();
assertThat(result, sameInstance(api));
ReflectionTestUtils.setField(AuthMeApi.class, null, "singleton", null);
assertThat(AuthMeApi.getInstance(), nullValue());
}
@Test
public void shouldReturnIfPlayerIsAuthenticated() {
// given
String name = "Bobby";
Player player = mockPlayerWithName(name);
given(playerCache.isAuthenticated(name)).willReturn(true);
// when
boolean result = api.isAuthenticated(player);
// then
verify(playerCache).isAuthenticated(name);
assertThat(result, equalTo(true));
}
@Test
public void shouldReturnIfPlayerIsNpc() {
// given
Player player = mock(Player.class);
given(player.hasMetadata("NPC")).willReturn(true);
// when
boolean result = api.isNpc(player);
// then
assertThat(result, equalTo(true));
verify(player).hasMetadata("NPC");
}
@Test
public void shouldReturnIfPlayerIsUnrestricted() {
// given
String name = "Tester";
Player player = mockPlayerWithName(name);
given(validationService.isUnrestricted(name)).willReturn(true);
// when
boolean result = api.isUnrestricted(player);
// then
verify(validationService).isUnrestricted(name);
assertThat(result, equalTo(true));
}
@Test
public void shouldGetLastLocation() {
// given
String name = "Gary";
Player player = mockPlayerWithName(name);
PlayerAuth auth = PlayerAuth.builder().name(name)
.locWorld("world")
.locX(12.4)
.locY(24.6)
.locZ(-438.2)
.locYaw(3.41f)
.locPitch(0.29f)
.build();
given(playerCache.getAuth(name)).willReturn(auth);
Server server = mock(Server.class);
ReflectionTestUtils.setField(Bukkit.class, null, "server", server);
World world = mock(World.class);
given(server.getWorld(auth.getWorld())).willReturn(world);
// when
Location result = api.getLastLocation(player);
// then
assertThat(result, not(nullValue()));
assertThat(result.getX(), equalTo(auth.getQuitLocX()));
assertThat(result.getY(), equalTo(auth.getQuitLocY()));
assertThat(result.getZ(), equalTo(auth.getQuitLocZ()));
assertThat(result.getWorld(), equalTo(world));
assertThat(result.getYaw(), equalTo(auth.getYaw()));
assertThat(result.getPitch(), equalTo(auth.getPitch()));
}
@Test
public void shouldGetLastIp() {
// given
String name = "Gabriel";
Player player = mockPlayerWithName(name);
PlayerAuth auth = PlayerAuth.builder().name(name)
.lastIp("93.23.44.55")
.build();
given(playerCache.getAuth(name)).willReturn(auth);
// when
String result = api.getLastIp(player.getName());
// then
assertThat(result, not(nullValue()));
assertThat(result, equalTo("93.23.44.55"));
}
@Test
public void shouldReturnNullAsLastIpForUnknownUser() {
// given
String name = "Harrison";
given(playerCache.getAuth(name)).willReturn(null);
given(dataSource.getAuth(name)).willReturn(null);
// when
String result = api.getLastIp(name);
// then
assertThat(result, nullValue());
verify(playerCache).getAuth(name);
verify(dataSource).getAuth(name);
}
@Test
public void shouldGetLastLogin() {
// given
String name = "David";
PlayerAuth auth = PlayerAuth.builder().name(name)
.lastLogin(1501597979L)
.build();
given(playerCache.getAuth(name)).willReturn(auth);
// when
Date result = api.getLastLogin(name);
// then
assertThat(result, not(nullValue()));
assertThat(result, equalTo(new Date(1501597979L)));
}
@Test
public void shouldHandleNullLastLogin() {
// given
String name = "John";
PlayerAuth auth = PlayerAuth.builder().name(name)
.lastLogin(null)
.build();
given(dataSource.getAuth(name)).willReturn(auth);
// when
Date result = api.getLastLogin(name);
// then
assertThat(result, nullValue());
verify(dataSource).getAuth(name);
}
@Test
public void shouldGetLastLoginTime() {
// given
String name = "David";
PlayerAuth auth = PlayerAuth.builder().name(name)
.lastLogin(1501597979L)
.build();
given(playerCache.getAuth(name)).willReturn(auth);
// when
Instant result = api.getLastLoginTime(name);
// then
assertThat(result, not(nullValue()));
assertThat(result, equalTo(Instant.ofEpochMilli(1501597979L)));
}
@Test
public void testGetLastLoginMillis() {
AuthMeApi result = AuthMeApi.getInstance();
assertThat(result.getLastLoginTime("notAPlayer"), nullValue());
}
@Test
public void shouldHandleNullLastLoginTime() {
// given
String name = "John";
PlayerAuth auth = PlayerAuth.builder().name(name)
.lastLogin(null)
.build();
given(dataSource.getAuth(name)).willReturn(auth);
// when
Instant result = api.getLastLoginTime(name);
// then
assertThat(result, nullValue());
verify(dataSource).getAuth(name);
}
@Test
public void shouldReturnNullForUnavailablePlayer() {
// given
String name = "Numan";
Player player = mockPlayerWithName(name);
given(playerCache.getAuth(name)).willReturn(null);
// when
Location result = api.getLastLocation(player);
// then
assertThat(result, nullValue());
}
@Test
public void shouldCheckForRegisteredName() {
// given
String name = "toaster";
given(dataSource.isAuthAvailable(name)).willReturn(true);
// when
boolean result = api.isRegistered(name);
// then
assertThat(result, equalTo(true));
}
@Test
public void shouldCheckPassword() {
// given
String playerName = "Robert";
String password = "someSecretPhrase2983";
given(passwordSecurity.comparePassword(password, playerName)).willReturn(true);
// when
boolean result = api.checkPassword(playerName, password);
// then
verify(passwordSecurity).comparePassword(password, playerName);
assertThat(result, equalTo(true));
}
@Test
public void shouldReturnAuthNames() {
// given
String[] names = {"bobby", "peter", "elisabeth", "craig"};
List<PlayerAuth> auths = Arrays.stream(names)
.map(name -> PlayerAuth.builder().name(name).build())
.collect(Collectors.toList());
given(dataSource.getAllAuths()).willReturn(auths);
// when
List<String> result = api.getRegisteredNames();
// then
assertThat(result, contains(names));
}
@Test
public void shouldReturnAuthRealNames() {
// given
String[] names = {"Bobby", "peter", "Elisabeth", "CRAIG"};
List<PlayerAuth> auths = Arrays.stream(names)
.map(name -> PlayerAuth.builder().name(name).realName(name).build())
.collect(Collectors.toList());
given(dataSource.getAllAuths()).willReturn(auths);
// when
List<String> result = api.getRegisteredRealNames();
// then
assertThat(result, contains(names));
}
@Test
public void shouldUnregisterPlayer() {
// given
Player player = mock(Player.class);
String name = "Donald";
given(player.getName()).willReturn(name);
// when
api.forceUnregister(player);
// then
verify(management).performUnregisterByAdmin(null, name, player);
}
@Test
public void shouldUnregisterPlayerByName() {
// given
Server server = mock(Server.class);
ReflectionTestUtils.setField(Bukkit.class, null, "server", server);
String name = "tristan";
Player player = mock(Player.class);
given(server.getPlayer(name)).willReturn(player);
// when
api.forceUnregister(name);
// then
verify(management).performUnregisterByAdmin(null, name, player);
}
@Test
public void shouldChangePassword() {
// given
String name = "Bobby12";
String password = "resetPw!";
// when
api.changePassword(name, password);
// then
verify(management).performPasswordChangeAsAdmin(null, name, password);
}
@Test
public void shouldReturnAuthMeInstance() {
// given / when
AuthMe result = api.getPlugin();
// then
assertThat(result, equalTo(authMe));
}
@Test
public void shouldReturnVersion() {
// given / when
String result = api.getPluginVersion();
// then
assertThat(result, equalTo(AuthMe.getPluginVersion()));
}
@Test
public void shouldForceLogin() {
// given
Player player = mock(Player.class);
// when
api.forceLogin(player);
// then
verify(management).forceLogin(player);
}
@Test
public void shouldForceLogout() {
// given
Player player = mock(Player.class);
// when
api.forceLogout(player);
// then
verify(management).performLogout(player);
}
@Test
public void shouldForceRegister() {
// given
Player player = mock(Player.class);
String pass = "test235";
// when
api.forceRegister(player, pass);
// then
verify(management).performRegister(eq(RegistrationMethod.API_REGISTRATION),
argThat(hasEqualValuesOnAllFields(ApiPasswordRegisterParams.of(player, pass, true))));
}
@Test
public void shouldForceRegisterAndNotAutoLogin() {
// given
Player player = mock(Player.class);
String pass = "test235";
// when
api.forceRegister(player, pass, false);
// then
verify(management).performRegister(eq(RegistrationMethod.API_REGISTRATION),
argThat(hasEqualValuesOnAllFields(ApiPasswordRegisterParams.of(player, pass, false))));
}
@Test
public void shouldRegisterPlayer() {
// given
String name = "Marco";
String password = "myP4ss";
HashedPassword hashedPassword = new HashedPassword("0395872SLKDFJOWEIUTEJSD");
given(passwordSecurity.computeHash(password, name.toLowerCase(Locale.ROOT))).willReturn(hashedPassword);
given(dataSource.saveAuth(any(PlayerAuth.class))).willReturn(true);
// when
boolean result = api.registerPlayer(name, password);
// then
assertThat(result, equalTo(true));
verify(passwordSecurity).computeHash(password, name.toLowerCase(Locale.ROOT));
ArgumentCaptor<PlayerAuth> authCaptor = ArgumentCaptor.forClass(PlayerAuth.class);
verify(dataSource).saveAuth(authCaptor.capture());
assertThat(authCaptor.getValue().getNickname(), equalTo(name.toLowerCase(Locale.ROOT)));
assertThat(authCaptor.getValue().getRealName(), equalTo(name));
assertThat(authCaptor.getValue().getPassword(), equalTo(hashedPassword));
}
@Test
public void shouldNotRegisterAlreadyRegisteredPlayer() {
// given
String name = "jonah";
given(dataSource.isAuthAvailable(name)).willReturn(true);
// when
boolean result = api.registerPlayer(name, "pass");
// then
assertThat(result, equalTo(false));
verify(dataSource, only()).isAuthAvailable(name);
verifyNoInteractions(management, passwordSecurity);
}
@Test
public void shouldGetNamesByIp() {
// given
String ip = "123.123.123.123";
List<String> names = Arrays.asList("Morgan", "Batista", "QUINN");
given(dataSource.getAllAuthsByIp(ip)).willReturn(names);
// when
List<String> result = api.getNamesByIp(ip);
// then
assertThat(result, equalTo(names));
verify(dataSource).getAllAuthsByIp(ip);
}
@Test
public void shouldReturnGeoIpInfo() {
// given
String ip = "127.127.12.1";
given(geoIpService.getCountryCode(ip)).willReturn("XA");
given(geoIpService.getCountryName(ip)).willReturn("Syldavia");
// when
String countryCode = api.getCountryCode(ip);
String countryName = api.getCountryName(ip);
// then
assertThat(countryCode, equalTo("XA"));
assertThat(countryName, equalTo("Syldavia"));
}
@Test
public void shouldReturnAuthMePlayerInfo() {
// given
PlayerAuth auth = PlayerAuth.builder()
.name("bobb")
.realName("Bobb")
.registrationDate(1433166082000L)
.build();
given(dataSource.getAuth("bobb")).willReturn(auth);
// when
Optional<AuthMePlayer> result = api.getPlayerInfo("bobb");
// then
AuthMePlayer playerInfo = result.get();
assertThat(playerInfo.getName(), equalTo("Bobb"));
assertThat(playerInfo.getRegistrationDate(), equalTo(Instant.ofEpochMilli(1433166082000L)));
}
@Test
public void shouldReturnNullForNonExistentAuth() {
// given / when
Optional<AuthMePlayer> result = api.getPlayerInfo("doesNotExist");
// then
assertThat(result.isPresent(), equalTo(false));
verify(playerCache).getAuth("doesNotExist");
verify(dataSource).getAuth("doesNotExist");
}
private static Player mockPlayerWithName(String name) {
Player player = mock(Player.class);
given(player.getName()).willReturn(name);
return player;
}
}
@@ -1,95 +0,0 @@
package fr.xephi.authme.api.v3;
import fr.xephi.authme.data.auth.PlayerAuth;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Test;
import java.time.Instant;
import java.util.Optional;
import java.util.UUID;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
/**
* Test for {@link AuthMePlayerImpl}.
*/
public class AuthMePlayerImplTest {
@Test
public void shouldMapNullWithoutError() {
// given / when / then
assertThat(AuthMePlayerImpl.fromPlayerAuth(null), emptyOptional());
}
@Test
public void shouldMapFromPlayerAuth() {
// given
PlayerAuth auth = PlayerAuth.builder()
.name("victor")
.realName("Victor")
.email("vic@example.com")
.registrationDate(1480075661000L)
.registrationIp("124.125.126.127")
.lastLogin(1542675632000L)
.lastIp("62.63.64.65")
.uuid(UUID.fromString("deadbeef-2417-4653-9026-feedbabeface"))
.build();
// when
Optional<AuthMePlayer> result = AuthMePlayerImpl.fromPlayerAuth(auth);
// then
AuthMePlayer playerInfo = result.get();
assertThat(playerInfo.getName(), equalTo("Victor"));
assertThat(playerInfo.getUuid().get(), equalTo(auth.getUuid()));
assertThat(playerInfo.getEmail().get(), equalTo(auth.getEmail()));
assertThat(playerInfo.getRegistrationDate(), equalTo(Instant.ofEpochMilli(auth.getRegistrationDate())));
assertThat(playerInfo.getRegistrationIpAddress().get(), equalTo(auth.getRegistrationIp()));
assertThat(playerInfo.getLastLoginDate().get(), equalTo(Instant.ofEpochMilli(auth.getLastLogin())));
assertThat(playerInfo.getLastLoginIpAddress().get(), equalTo(auth.getLastIp()));
}
@Test
public void shouldHandleNullAndDefaultValues() {
// given
PlayerAuth auth = PlayerAuth.builder()
.name("victor")
.realName("Victor")
.email("your@email.com") // DB default
.registrationDate(1480075661000L)
.lastLogin(0L) // DB default
.lastIp("127.0.0.1") // DB default
.build();
// when
Optional<AuthMePlayer> result = AuthMePlayerImpl.fromPlayerAuth(auth);
// then
AuthMePlayer playerInfo = result.get();
assertThat(playerInfo.getName(), equalTo("Victor"));
assertThat(playerInfo.getUuid(), emptyOptional());
assertThat(playerInfo.getEmail(), emptyOptional());
assertThat(playerInfo.getRegistrationDate(), equalTo(Instant.ofEpochMilli(auth.getRegistrationDate())));
assertThat(playerInfo.getRegistrationIpAddress(), emptyOptional());
assertThat(playerInfo.getLastLoginDate(), emptyOptional());
assertThat(playerInfo.getLastLoginIpAddress(), emptyOptional());
}
private static <T> Matcher<Optional<T>> emptyOptional() {
return new TypeSafeMatcher<Optional<T>>() {
@Override
public void describeTo(Description description) {
description.appendText("an empty optional");
}
@Override
protected boolean matchesSafely(Optional<T> item) {
return !item.isPresent();
}
};
}
}
@@ -1,84 +0,0 @@
package fr.xephi.authme.command;
import org.bukkit.configuration.MemorySection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static fr.xephi.authme.TestHelper.getJarFile;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;
/**
* Checks that the commands declared in plugin.yml correspond
* to the ones built by the {@link CommandInitializer}.
*/
public class CommandConsistencyTest {
@Test
public void shouldHaveEqualDefinitions() {
// given
Collection<List<String>> initializedCommands = initializeCommands();
Map<String, List<String>> pluginFileLabels = getLabelsFromPluginFile();
// when / then
assertThat("number of base commands are equal in plugin.yml and CommandInitializer",
initializedCommands.size(), equalTo(pluginFileLabels.size()));
for (List<String> commandLabels : initializedCommands) {
List<String> pluginYmlLabels = pluginFileLabels.get(commandLabels.get(0));
// NB: the first label in CommandDescription needs to correspond to the key in plugin.yml
assertThat("plugin.yml contains definition for command '" + commandLabels.get(0) + "'",
pluginYmlLabels, not(nullValue()));
assertThat("plugin.yml and CommandDescription have same alternative labels for /" + commandLabels.get(0),
pluginYmlLabels, containsInAnyOrder(commandLabels.subList(1, commandLabels.size()).toArray()));
}
}
/**
* Gets the command definitions from CommandInitializer and returns the
* labels of all base commands.
*
* @return collection of all base command labels
*/
private static Collection<List<String>> initializeCommands() {
CommandInitializer initializer = new CommandInitializer();
Collection<List<String>> commandLabels = new ArrayList<>();
for (CommandDescription baseCommand : initializer.getCommands()) {
commandLabels.add(baseCommand.getLabels());
}
return commandLabels;
}
/**
* Reads plugin.yml and returns the defined commands by main label and aliases.
*
* @return collection of all labels and their aliases
*/
@SuppressWarnings("unchecked")
private static Map<String, List<String>> getLabelsFromPluginFile() {
FileConfiguration pluginFile = YamlConfiguration.loadConfiguration(getJarFile("/plugin.yml"));
MemorySection commandList = (MemorySection) pluginFile.get("commands");
Map<String, Object> commandDefinitions = commandList.getValues(false);
Map<String, List<String>> commandLabels = new HashMap<>();
for (Map.Entry<String, Object> commandDefinition : commandDefinitions.entrySet()) {
MemorySection definition = (MemorySection) commandDefinition.getValue();
List<String> alternativeLabels = definition.get("aliases") == null
? Collections.EMPTY_LIST
: (List<String>) definition.get("aliases");
commandLabels.put(commandDefinition.getKey(), alternativeLabels);
}
return commandLabels;
}
}
@@ -1,302 +0,0 @@
package fr.xephi.authme.command;
import ch.jalu.injector.Injector;
import ch.jalu.injector.factory.Factory;
import com.google.common.collect.Sets;
import fr.xephi.authme.command.TestCommandsUtil.TestLoginCommand;
import fr.xephi.authme.command.TestCommandsUtil.TestRegisterCommand;
import fr.xephi.authme.command.TestCommandsUtil.TestUnregisterCommand;
import fr.xephi.authme.command.help.HelpProvider;
import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.message.Messages;
import fr.xephi.authme.permission.PermissionsManager;
import org.bukkit.command.CommandSender;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import static fr.xephi.authme.command.FoundResultStatus.INCORRECT_ARGUMENTS;
import static fr.xephi.authme.command.FoundResultStatus.MISSING_BASE_COMMAND;
import static fr.xephi.authme.command.FoundResultStatus.NO_PERMISSION;
import static fr.xephi.authme.command.FoundResultStatus.SUCCESS;
import static fr.xephi.authme.command.FoundResultStatus.UNKNOWN_LABEL;
import static java.util.Arrays.asList;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.hamcrest.MockitoHamcrest.argThat;
/**
* Test for {@link CommandHandler}.
*/
// Justification: It's more readable to use asList() everywhere in the test when we often generated two lists where one
// often consists of only one element, e.g. myMethod(asList("authme"), asList("my", "args"), ...)
@SuppressWarnings("ArraysAsListWithZeroOrOneArgument")
@RunWith(MockitoJUnitRunner.class)
public class CommandHandlerTest {
private CommandHandler handler;
@Mock
private Factory<ExecutableCommand> commandFactory;
@Mock
private CommandMapper commandMapper;
@Mock
private PermissionsManager permissionsManager;
@Mock
private Messages messages;
@Mock
private HelpProvider helpProvider;
private Map<Class<? extends ExecutableCommand>, ExecutableCommand> mockedCommands = new HashMap<>();
@Before
@SuppressWarnings("unchecked")
public void initializeCommandMapper() {
given(commandMapper.getCommandClasses()).willReturn(Sets.newHashSet(
ExecutableCommand.class, TestLoginCommand.class, TestRegisterCommand.class, TestUnregisterCommand.class));
setInjectorToMockExecutableCommandClasses();
handler = new CommandHandler(commandFactory, commandMapper, permissionsManager, messages, helpProvider);
}
/**
* Makes the injector return a mock when {@link Injector#newInstance(Class)} is invoked
* with (a child of) ExecutableCommand.class. The mocks the injector creates are stored in {@link #mockedCommands}.
* <p>
* The {@link CommandMapper} is mocked in {@link #initializeCommandMapper()} to return certain test classes.
*/
@SuppressWarnings("unchecked")
private void setInjectorToMockExecutableCommandClasses() {
given(commandFactory.newInstance(any(Class.class))).willAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
Class<?> clazz = invocation.getArgument(0);
if (ExecutableCommand.class.isAssignableFrom(clazz)) {
Class<? extends ExecutableCommand> commandClass = (Class<? extends ExecutableCommand>) clazz;
ExecutableCommand mock = mock(commandClass);
mockedCommands.put(commandClass, mock);
return mock;
}
throw new IllegalStateException("Unexpected class '" + clazz.getName()
+ "': Not a child of ExecutableCommand");
}
});
}
@Test
public void shouldCallMappedCommandWithArgs() {
// given
String bukkitLabel = "Authme";
String[] bukkitArgs = {"Login", "myPass"};
CommandSender sender = mock(CommandSender.class);
CommandDescription command = mock(CommandDescription.class);
doReturn(TestLoginCommand.class).when(command).getExecutableCommand();
given(commandMapper.mapPartsToCommand(any(CommandSender.class), anyList()))
.willReturn(new FoundCommandResult(command, asList("Authme", "Login"), asList("myPass"), 0.0, SUCCESS));
// when
handler.processCommand(sender, bukkitLabel, bukkitArgs);
// then
ExecutableCommand executableCommand = mockedCommands.get(TestLoginCommand.class);
verify(commandMapper).mapPartsToCommand(sender, asList("Authme", "Login", "myPass"));
verify(executableCommand).executeCommand(sender, asList("myPass"));
// Ensure that no error message was issued to the command sender
verify(sender, never()).sendMessage(anyString());
}
@Test
public void shouldNotCallExecutableCommandIfNoPermission() {
// given
String bukkitLabel = "unreg";
String[] bukkitArgs = {"testPlayer"};
CommandSender sender = mock(CommandSender.class);
CommandDescription command = mock(CommandDescription.class);
given(commandMapper.mapPartsToCommand(any(CommandSender.class), anyList()))
.willReturn(new FoundCommandResult(command, asList("unreg"), asList("testPlayer"), 0.0, NO_PERMISSION));
// when
handler.processCommand(sender, bukkitLabel, bukkitArgs);
// then
verify(commandMapper).mapPartsToCommand(sender, asList("unreg", "testPlayer"));
verify(command, never()).getExecutableCommand();
verify(messages).send(sender, MessageKey.NO_PERMISSION);
}
@Test
public void shouldNotCallExecutableForWrongArguments() {
// given
String bukkitLabel = "unreg";
String[] bukkitArgs = {"testPlayer"};
CommandSender sender = mock(CommandSender.class);
CommandDescription command = mock(CommandDescription.class);
given(command.getExecutableCommand()).willReturn((Class) TestUnregisterCommand.class);
given(commandMapper.mapPartsToCommand(any(CommandSender.class), anyList())).willReturn(
new FoundCommandResult(command, asList("unreg"), asList("testPlayer"), 0.0, INCORRECT_ARGUMENTS));
given(permissionsManager.hasPermission(sender, command.getPermission())).willReturn(true);
// when
handler.processCommand(sender, bukkitLabel, bukkitArgs);
// then
verify(commandMapper).mapPartsToCommand(sender, asList("unreg", "testPlayer"));
verify(sender, atLeastOnce()).sendMessage(argThat(containsString("Incorrect command arguments")));
}
@Test
public void shouldUseCustomMessageUponArgumentMismatch() {
// given
String bukkitLabel = "unreg";
String[] bukkitArgs = {"testPlayer"};
CommandSender sender = mock(CommandSender.class);
CommandDescription command = mock(CommandDescription.class);
given(command.getExecutableCommand()).willReturn((Class) TestUnregisterCommand.class);
given(mockedCommands.get(TestUnregisterCommand.class).getArgumentsMismatchMessage())
.willReturn(MessageKey.USAGE_RECOVER_EMAIL);
given(commandMapper.mapPartsToCommand(any(CommandSender.class), anyList())).willReturn(
new FoundCommandResult(command, asList("unreg"), asList("testPlayer"), 0.0, INCORRECT_ARGUMENTS));
given(permissionsManager.hasPermission(sender, command.getPermission())).willReturn(true);
// when
handler.processCommand(sender, bukkitLabel, bukkitArgs);
// then
verify(commandMapper).mapPartsToCommand(sender, asList("unreg", "testPlayer"));
verify(messages).send(sender, MessageKey.USAGE_RECOVER_EMAIL);
verify(sender, never()).sendMessage(anyString());
}
@Test
public void shouldNotCallExecutableForWrongArgumentsAndPermissionDenied() {
// given
String bukkitLabel = "unreg";
String[] bukkitArgs = {"testPlayer"};
CommandSender sender = mock(CommandSender.class);
CommandDescription command = mock(CommandDescription.class);
given(commandMapper.mapPartsToCommand(any(CommandSender.class), anyList())).willReturn(
new FoundCommandResult(command, asList("unreg"), asList("testPlayer"), 0.0, INCORRECT_ARGUMENTS));
given(permissionsManager.hasPermission(sender, command.getPermission())).willReturn(false);
// when
handler.processCommand(sender, bukkitLabel, bukkitArgs);
// then
verify(commandMapper).mapPartsToCommand(sender, asList("unreg", "testPlayer"));
verify(command, never()).getExecutableCommand();
verify(messages).send(sender, MessageKey.NO_PERMISSION);
}
@Test
public void shouldNotCallExecutableForFailedParsing() {
// given
String bukkitLabel = "unreg";
String[] bukkitArgs = {"testPlayer"};
CommandSender sender = mock(CommandSender.class);
CommandDescription command = mock(CommandDescription.class);
given(commandMapper.mapPartsToCommand(any(CommandSender.class), anyList())).willReturn(
new FoundCommandResult(command, asList("unreg"), asList("testPlayer"), 0.0, MISSING_BASE_COMMAND));
// when
handler.processCommand(sender, bukkitLabel, bukkitArgs);
// then
verify(commandMapper).mapPartsToCommand(sender, asList("unreg", "testPlayer"));
verify(command, never()).getExecutableCommand();
verify(sender).sendMessage(argThat(containsString("Failed to parse")));
}
@Test
public void shouldNotCallExecutableForUnknownLabelAndHaveSuggestion() {
// given
String bukkitLabel = "unreg";
String[] bukkitArgs = {"testPlayer"};
CommandSender sender = mock(CommandSender.class);
CommandDescription command = mock(CommandDescription.class);
given(command.getLabels()).willReturn(Collections.singletonList("test_cmd"));
given(commandMapper.mapPartsToCommand(any(CommandSender.class), anyList())).willReturn(
new FoundCommandResult(command, asList("unreg"), asList("testPlayer"), 0.01, UNKNOWN_LABEL));
// when
handler.processCommand(sender, bukkitLabel, bukkitArgs);
// then
verify(commandMapper).mapPartsToCommand(sender, asList("unreg", "testPlayer"));
verify(command, never()).getExecutableCommand();
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
verify(sender, times(3)).sendMessage(captor.capture());
assertThat(captor.getAllValues().get(0), containsString("Unknown command"));
assertThat(captor.getAllValues().get(1), containsString("Did you mean"));
assertThat(captor.getAllValues().get(1), containsString("/test_cmd"));
assertThat(captor.getAllValues().get(2), containsString("Use the command"));
assertThat(captor.getAllValues().get(2), containsString("to view help"));
}
@Test
public void shouldNotCallExecutableForUnknownLabelAndNotSuggestCommand() {
// given
String bukkitLabel = "unreg";
String[] bukkitArgs = {"testPlayer"};
CommandSender sender = mock(CommandSender.class);
CommandDescription command = mock(CommandDescription.class);
given(commandMapper.mapPartsToCommand(any(CommandSender.class), anyList())).willReturn(
new FoundCommandResult(command, asList("unreg"), asList("testPlayer"), 1.0, UNKNOWN_LABEL));
// when
handler.processCommand(sender, bukkitLabel, bukkitArgs);
// then
verify(commandMapper).mapPartsToCommand(sender, asList("unreg", "testPlayer"));
verify(command, never()).getExecutableCommand();
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
verify(sender, times(2)).sendMessage(captor.capture());
assertThat(captor.getAllValues().get(0), containsString("Unknown command"));
assertThat(captor.getAllValues().get(1), containsString("Use the command"));
assertThat(captor.getAllValues().get(1), containsString("to view help"));
}
@Test
public void shouldStripWhitespace() {
// given
String bukkitLabel = "AuthMe";
String[] bukkitArgs = {" ", "", "REGISTER", " ", "testArg", " "};
CommandSender sender = mock(CommandSender.class);
CommandDescription command = mock(CommandDescription.class);
doReturn(TestRegisterCommand.class).when(command).getExecutableCommand();
given(commandMapper.mapPartsToCommand(eq(sender), anyList()))
.willReturn(new FoundCommandResult(command, asList("AuthMe", "REGISTER"), asList("testArg"), 0.0, SUCCESS));
// when
handler.processCommand(sender, bukkitLabel, bukkitArgs);
// then
ExecutableCommand executableCommand = mockedCommands.get(TestRegisterCommand.class);
verify(commandMapper).mapPartsToCommand(sender, asList("AuthMe", "REGISTER", "testArg"));
verify(executableCommand).executeCommand(sender, asList("testArg"));
verify(sender, never()).sendMessage(anyString());
}
}
@@ -1,283 +0,0 @@
package fr.xephi.authme.command;
import fr.xephi.authme.util.StringUtils;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.regex.Pattern;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
/**
* Test for {@link CommandInitializer} to guarantee the integrity of the defined commands.
*/
public class CommandInitializerTest {
/**
* Defines the maximum allowed depths for nesting CommandDescription instances.
* Note that the depth starts at 0 (e.g. /authme), so a depth of 2 is something like /authme hello world
*/
private static int MAX_ALLOWED_DEPTH = 1;
private static Collection<CommandDescription> commands;
@BeforeClass
public static void initializeCommandCollection() {
CommandInitializer commandInitializer = new CommandInitializer();
commands = commandInitializer.getCommands();
}
@Test
public void shouldInitializeCommands() {
// given/when/then
// It obviously doesn't make sense to test much of the concrete data
// that is being initialized; we just want to guarantee with this test
// that data is indeed being initialized and we take a few "probes"
assertThat(commands, hasSize(10));
assertThat(commandsIncludeLabel(commands, "authme"), equalTo(true));
assertThat(commandsIncludeLabel(commands, "register"), equalTo(true));
assertThat(commandsIncludeLabel(commands, "help"), equalTo(false));
}
@Test
public void shouldNotBeNestedExcessively() {
// given
BiConsumer<CommandDescription, Integer> descriptionTester =
(command, depth) -> assertThat(depth <= MAX_ALLOWED_DEPTH, equalTo(true));
// when/then
walkThroughCommands(commands, descriptionTester);
}
/** Ensure that all children of a command stored the parent. */
@Test
public void shouldHaveConnectionBetweenParentAndChild() {
// given
BiConsumer<CommandDescription, Integer> connectionTester = new BiConsumer<CommandDescription, Integer>() {
@Override
public void accept(CommandDescription command, Integer depth) {
if (!command.getChildren().isEmpty()) {
for (CommandDescription child : command.getChildren()) {
assertThat(command.equals(child.getParent()), equalTo(true));
}
}
// Checking that the parent has the current command as child is redundant as this is how we can traverse
// the "command tree" in the first place - if we're here, it's that the parent definitely has the
// command as child.
}
};
// when/then
walkThroughCommands(commands, connectionTester);
}
@Test
public void shouldUseProperLowerCaseLabels() {
// given
final Pattern invalidPattern = Pattern.compile("\\s");
BiConsumer<CommandDescription, Integer> labelFormatTester = new BiConsumer<CommandDescription, Integer>() {
@Override
public void accept(CommandDescription command, Integer depth) {
for (String label : command.getLabels()) {
if (!label.equals(label.toLowerCase(Locale.ROOT))) {
fail("Label '" + label + "' should be lowercase");
} else if (invalidPattern.matcher(label).matches()) {
fail("Label '" + label + "' has whitespace");
}
}
}
};
// when/then
walkThroughCommands(commands, labelFormatTester);
}
@Test
public void shouldNotDefineSameLabelTwice() {
// given
final Set<String> commandMappings = new HashSet<>();
BiConsumer<CommandDescription, Integer> uniqueMappingTester = new BiConsumer<CommandDescription, Integer>() {
@Override
public void accept(CommandDescription command, Integer depth) {
int initialSize = commandMappings.size();
List<String> newMappings = getAbsoluteLabels(command);
commandMappings.addAll(newMappings);
// Set only contains unique entries, so we just check after adding all new mappings that the size
// of the Set corresponds to our expectation
assertThat("All bindings are unique for command with bindings '" + newMappings + "'",
commandMappings.size() == initialSize + newMappings.size(), equalTo(true));
}
};
// when/then
walkThroughCommands(commands, uniqueMappingTester);
}
/**
* The description should provide a very short description of the command and shouldn't end in a ".", whereas the
* detailed description should be longer and end with a period.
*/
@Test
public void shouldHaveProperDescription() {
// given
BiConsumer<CommandDescription, Integer> descriptionTester = new BiConsumer<CommandDescription, Integer>() {
@Override
public void accept(CommandDescription command, Integer depth) {
String forCommandText = " for command with labels '" + command.getLabels() + "'";
assertThat("has description" + forCommandText,
StringUtils.isBlank(command.getDescription()), equalTo(false));
assertThat("short description doesn't end in '.'" + forCommandText,
command.getDescription().endsWith("."), equalTo(false));
assertThat("has detailed description" + forCommandText,
StringUtils.isBlank(command.getDetailedDescription()), equalTo(false));
assertThat("detailed description ends in '.'" + forCommandText,
command.getDetailedDescription().endsWith("."), equalTo(true));
}
};
// when/then
walkThroughCommands(commands, descriptionTester);
}
@Test
public void shouldHaveOptionalArgumentsAfterMandatoryOnes() {
// given
BiConsumer<CommandDescription, Integer> argumentOrderTester = new BiConsumer<CommandDescription, Integer>() {
@Override
public void accept(CommandDescription command, Integer depth) {
boolean encounteredOptionalArg = false;
for (CommandArgumentDescription argument : command.getArguments()) {
if (argument.isOptional()) {
encounteredOptionalArg = true;
} else if (encounteredOptionalArg) {
fail("Mandatory arguments should come before optional ones for command with labels '"
+ command.getLabels() + "'");
}
}
}
};
// when/then
walkThroughCommands(commands, argumentOrderTester);
}
/**
* Ensure that a command with children (i.e. a base command) doesn't define any arguments. This might otherwise
* clash with the label of the child.
*/
@Test
public void shouldNotHaveArgumentsIfCommandHasChildren() {
// given
BiConsumer<CommandDescription, Integer> noArgumentForParentChecker = new BiConsumer<CommandDescription, Integer>() {
@Override
public void accept(CommandDescription command, Integer depth) {
// Fail if the command has children and has arguments at the same time
// Exception: If the parent only has one child defining the help label, it is acceptable
if (!command.getChildren().isEmpty() && !command.getArguments().isEmpty()
&& (command.getChildren().size() != 1 || !command.getChildren().get(0).hasLabel("help"))) {
fail("Parent command (labels='" + command.getLabels() + "') should not have any arguments");
}
}
};
// when/then
walkThroughCommands(commands, noArgumentForParentChecker);
}
/**
* Tests that multiple CommandDescription instances pointing to the same ExecutableCommand use the same
* count of arguments.
*/
@Test
public void shouldPointToSameExecutableCommandWithConsistentArgumentCount() {
// given
final Map<Class<? extends ExecutableCommand>, Integer> mandatoryArguments = new HashMap<>();
final Map<Class<? extends ExecutableCommand>, Integer> totalArguments = new HashMap<>();
BiConsumer<CommandDescription, Integer> argChecker = new BiConsumer<CommandDescription, Integer>() {
@Override
public void accept(CommandDescription command, Integer depth) {
testCollectionForCommand(command, CommandUtils.getMinNumberOfArguments(command), mandatoryArguments);
testCollectionForCommand(command, CommandUtils.getMaxNumberOfArguments(command), totalArguments);
}
private void testCollectionForCommand(CommandDescription command, int argCount,
Map<Class<? extends ExecutableCommand>, Integer> collection) {
final Class<? extends ExecutableCommand> clazz = command.getExecutableCommand();
Integer existingCount = collection.get(clazz);
if (existingCount == null) {
collection.put(clazz, argCount);
} else {
String commandDescription = "Command with label '" + command.getLabels().get(0) + "' and parent '"
+ (command.getParent() == null ? "null" : command.getLabels().get(0)) + "' ";
assertThat(commandDescription + "should point to " + clazz + " with arguments consistent to others",
argCount, equalTo(existingCount));
}
}
};
// when / then
walkThroughCommands(commands, argChecker);
}
// ------------
// Helper methods
// ------------
private static void walkThroughCommands(Collection<CommandDescription> commands,
BiConsumer<CommandDescription, Integer> consumer) {
walkThroughCommands(commands, consumer, 0);
}
private static void walkThroughCommands(Collection<CommandDescription> commands,
BiConsumer<CommandDescription, Integer> consumer, int depth) {
for (CommandDescription command : commands) {
consumer.accept(command, depth);
if (!command.getChildren().isEmpty()) {
walkThroughCommands(command.getChildren(), consumer, depth + 1);
}
}
}
private static boolean commandsIncludeLabel(Iterable<CommandDescription> commands, String label) {
for (CommandDescription command : commands) {
if (command.getLabels().contains(label)) {
return true;
}
}
return false;
}
/**
* Get the absolute binding that a command defines. Note: Assumes that only the passed command can have
* multiple labels; only considering the first label for all of the command's parents.
*
* @param command The command to process
*
* @return List of all bindings that lead to the command
*/
private static List<String> getAbsoluteLabels(CommandDescription command) {
CommandDescription parent = command.getParent();
String parentPath = (parent == null) ? "" : parent.getLabels().get(0) + " ";
List<String> bindings = new ArrayList<>(command.getLabels().size());
for (String label : command.getLabels()) {
bindings.add(parentPath + label);
}
return bindings;
}
}
@@ -1,319 +0,0 @@
package fr.xephi.authme.command;
import ch.jalu.injector.testing.BeforeInjecting;
import ch.jalu.injector.testing.DelayedInjectionRunner;
import ch.jalu.injector.testing.InjectDelayed;
import fr.xephi.authme.command.TestCommandsUtil.TestLoginCommand;
import fr.xephi.authme.command.TestCommandsUtil.TestRegisterCommand;
import fr.xephi.authme.command.TestCommandsUtil.TestUnregisterCommand;
import fr.xephi.authme.command.executable.HelpCommand;
import fr.xephi.authme.permission.PermissionNode;
import fr.xephi.authme.permission.PermissionsManager;
import org.bukkit.command.CommandSender;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import java.util.List;
import java.util.Set;
import static fr.xephi.authme.command.TestCommandsUtil.getCommandWithLabel;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* Test for {@link CommandMapper}.
*/
@RunWith(DelayedInjectionRunner.class)
public class CommandMapperTest {
private static List<CommandDescription> commands;
@InjectDelayed
private CommandMapper mapper;
@Mock
private PermissionsManager permissionsManager;
@Mock
private CommandInitializer commandInitializer;
@BeforeClass
public static void setUpCommandHandler() {
commands = TestCommandsUtil.generateCommands();
}
@BeforeInjecting
public void setUpMocks() {
given(commandInitializer.getCommands()).willReturn(commands);
}
// -----------
// mapPartsToCommand() tests
// -----------
@Test
public void shouldMapPartsToLoginChildCommand() {
// given
List<String> parts = asList("authme", "login", "test1");
CommandSender sender = mock(CommandSender.class);
given(permissionsManager.hasPermission(eq(sender), any(PermissionNode.class))).willReturn(true);
// when
FoundCommandResult result = mapper.mapPartsToCommand(sender, parts);
// then
assertThat(result.getCommandDescription(), equalTo(getCommandWithLabel(commands, "authme", "login")));
assertThat(result.getResultStatus(), equalTo(FoundResultStatus.SUCCESS));
assertThat(result.getArguments(), contains("test1"));
assertThat(result.getDifference(), equalTo(0.0));
assertThat(result.getLabels(), equalTo(parts.subList(0, 2)));
assertThat(result.getArguments(), contains(parts.get(2)));
}
@Test
public void shouldMapPartsToCommandWithNoCaseSensitivity() {
// given
List<String> parts = asList("Authme", "REG", "arg1", "arg2");
CommandSender sender = mock(CommandSender.class);
given(permissionsManager.hasPermission(eq(sender), any(PermissionNode.class))).willReturn(true);
// when
FoundCommandResult result = mapper.mapPartsToCommand(sender, parts);
// then
assertThat(result.getCommandDescription(), equalTo(getCommandWithLabel(commands, "authme", "register")));
assertThat(result.getResultStatus(), equalTo(FoundResultStatus.SUCCESS));
assertThat(result.getLabels(), equalTo(parts.subList(0, 2)));
assertThat(result.getArguments(), contains("arg1", "arg2"));
assertThat(result.getDifference(), equalTo(0.0));
}
@Test
public void shouldRejectCommandWithTooManyArguments() {
// given
List<String> parts = asList("authme", "register", "pass123", "pass123", "pass123");
CommandSender sender = mock(CommandSender.class);
given(permissionsManager.hasPermission(eq(sender), any(PermissionNode.class))).willReturn(true);
// when
FoundCommandResult result = mapper.mapPartsToCommand(sender, parts);
// then
assertThat(result.getCommandDescription(), equalTo(getCommandWithLabel(commands, "authme", "register")));
assertThat(result.getResultStatus(), equalTo(FoundResultStatus.INCORRECT_ARGUMENTS));
assertThat(result.getDifference(), equalTo(0.0));
assertThat(result.getLabels(), equalTo(parts.subList(0, 2)));
assertThat(result.getArguments(), equalTo(parts.subList(2, 5)));
}
@Test
public void shouldRejectCommandWithTooFewArguments() {
// given
List<String> parts = asList("authme", "Reg");
CommandSender sender = mock(CommandSender.class);
given(permissionsManager.hasPermission(eq(sender), any(PermissionNode.class))).willReturn(true);
// when
FoundCommandResult result = mapper.mapPartsToCommand(sender, parts);
// then
assertThat(result.getCommandDescription(), equalTo(getCommandWithLabel(commands, "authme", "register")));
assertThat(result.getResultStatus(), equalTo(FoundResultStatus.INCORRECT_ARGUMENTS));
assertThat(result.getDifference(), equalTo(0.0));
assertThat(result.getLabels(), equalTo(parts));
assertThat(result.getArguments(), empty());
}
@Test
public void shouldSuggestCommandWithSimilarLabel() {
// given
List<String> parts = asList("authme", "reh", "pass123", "pass123");
CommandSender sender = mock(CommandSender.class);
given(permissionsManager.hasPermission(eq(sender), any(PermissionNode.class))).willReturn(true);
// when
FoundCommandResult result = mapper.mapPartsToCommand(sender, parts);
// then
assertThat(result.getCommandDescription(), equalTo(getCommandWithLabel(commands, "authme", "register")));
assertThat(result.getResultStatus(), equalTo(FoundResultStatus.UNKNOWN_LABEL));
assertThat(result.getDifference() < 0.75, equalTo(true));
assertThat(result.getLabels(), equalTo(parts.subList(0, 2)));
assertThat(result.getArguments(), contains("pass123", "pass123"));
}
/** In contrast to the previous test, we test a command request with a very apart label. */
@Test
public void shouldSuggestMostSimilarCommand() {
// given
List<String> parts = asList("authme", "asdfawetawty4asdca");
CommandSender sender = mock(CommandSender.class);
given(permissionsManager.hasPermission(eq(sender), any(PermissionNode.class))).willReturn(true);
// when
FoundCommandResult result = mapper.mapPartsToCommand(sender, parts);
// then
assertThat(result.getCommandDescription(), not(nullValue()));
assertThat(result.getResultStatus(), equalTo(FoundResultStatus.UNKNOWN_LABEL));
assertThat(result.getDifference() > 0.75, equalTo(true));
assertThat(result.getLabels(), equalTo(parts));
assertThat(result.getArguments(), empty());
}
@Test
public void shouldHandleBaseWithWrongArguments() {
// given
List<String> parts = singletonList("unregister");
CommandSender sender = mock(CommandSender.class);
given(permissionsManager.hasPermission(eq(sender), any(PermissionNode.class))).willReturn(true);
// when
FoundCommandResult result = mapper.mapPartsToCommand(sender, parts);
// then
assertThat(result.getResultStatus(), equalTo(FoundResultStatus.INCORRECT_ARGUMENTS));
assertThat(result.getCommandDescription(), equalTo(getCommandWithLabel(commands, "unregister")));
assertThat(result.getDifference(), equalTo(0.0));
assertThat(result.getArguments(), empty());
assertThat(result.getLabels(), equalTo(parts));
}
@Test
public void shouldHandleUnknownBase() {
// given
List<String> parts = asList("bogus", "label1", "arg1");
CommandSender sender = mock(CommandSender.class);
given(permissionsManager.hasPermission(eq(sender), any(PermissionNode.class))).willReturn(true);
// when
FoundCommandResult result = mapper.mapPartsToCommand(sender, parts);
// then
assertThat(result.getResultStatus(), equalTo(FoundResultStatus.MISSING_BASE_COMMAND));
assertThat(result.getCommandDescription(), nullValue());
}
@Test
public void shouldHandleNullInput() {
// given / when
FoundCommandResult result = mapper.mapPartsToCommand(mock(CommandSender.class), null);
// then
assertThat(result.getResultStatus(), equalTo(FoundResultStatus.MISSING_BASE_COMMAND));
assertThat(result.getCommandDescription(), nullValue());
}
@Test
public void shouldMapToBaseWithProperArguments() {
// given
List<String> parts = asList("Unreg", "player1");
CommandSender sender = mock(CommandSender.class);
given(permissionsManager.hasPermission(eq(sender), any(PermissionNode.class))).willReturn(true);
// when
FoundCommandResult result = mapper.mapPartsToCommand(sender, parts);
// then
assertThat(result.getResultStatus(), equalTo(FoundResultStatus.SUCCESS));
assertThat(result.getCommandDescription(), equalTo(getCommandWithLabel(commands, "unregister")));
assertThat(result.getDifference(), equalTo(0.0));
assertThat(result.getArguments(), contains("player1"));
assertThat(result.getLabels(), contains("Unreg"));
}
@Test
public void shouldReturnChildlessBaseCommandWithArgCountError() {
// given
List<String> parts = asList("unregistER", "player1", "wrongArg");
CommandSender sender = mock(CommandSender.class);
given(permissionsManager.hasPermission(eq(sender), any(PermissionNode.class))).willReturn(true);
// when
FoundCommandResult result = mapper.mapPartsToCommand(sender, parts);
// then
assertThat(result.getResultStatus(), equalTo(FoundResultStatus.INCORRECT_ARGUMENTS));
assertThat(result.getCommandDescription(), equalTo(getCommandWithLabel(commands, "unregister")));
assertThat(result.getDifference(), equalTo(0.0));
assertThat(result.getArguments(), contains("player1", "wrongArg"));
assertThat(result.getLabels(), contains("unregistER"));
}
@Test
public void shouldPassCommandPathAsArgumentsToHelpCommand() {
// given
List<String> parts = asList("email", "helptest", "arg1");
CommandSender sender = mock(CommandSender.class);
given(permissionsManager.hasPermission(eq(sender), isNull())).willReturn(true);
// when
FoundCommandResult result = mapper.mapPartsToCommand(sender, parts);
// then
assertThat(result.getResultStatus(), equalTo(FoundResultStatus.SUCCESS));
assertThat(result.getCommandDescription(), equalTo(getCommandWithLabel(commands, "email", "helptest")));
assertThat(result.getLabels(), contains("email", "helptest"));
assertThat(result.getArguments(), contains("email", "arg1"));
assertThat(result.getDifference(), equalTo(0.0));
}
@Test
public void shouldRecognizeMissingPermissionForCommand() {
// given
List<String> parts = asList("authme", "login", "test1");
CommandSender sender = mock(CommandSender.class);
given(permissionsManager.hasPermission(eq(sender), any(PermissionNode.class))).willReturn(false);
// when
FoundCommandResult result = mapper.mapPartsToCommand(sender, parts);
// then
assertThat(result.getCommandDescription(), equalTo(getCommandWithLabel(commands, "authme", "login")));
assertThat(result.getResultStatus(), equalTo(FoundResultStatus.NO_PERMISSION));
assertThat(result.getArguments(), contains("test1"));
assertThat(result.getDifference(), equalTo(0.0));
assertThat(result.getLabels(), equalTo(parts.subList(0, 2)));
assertThat(result.getArguments(), contains(parts.get(2)));
}
@Test
public void shouldSupportAuthMePrefix() {
// given
List<String> parts = asList("authme:unregister", "Betty");
CommandSender sender = mock(CommandSender.class);
given(permissionsManager.hasPermission(eq(sender), any(PermissionNode.class))).willReturn(true);
// when
FoundCommandResult result = mapper.mapPartsToCommand(sender, parts);
// then
assertThat(result.getResultStatus(), equalTo(FoundResultStatus.SUCCESS));
assertThat(result.getCommandDescription(), equalTo(getCommandWithLabel(commands, "unregister")));
}
@SuppressWarnings("unchecked")
@Test
public void shouldReturnExecutableCommandClasses() {
// given / when
Set<Class<? extends ExecutableCommand>> commandClasses = mapper.getCommandClasses();
// then
assertThat(commandClasses, containsInAnyOrder(ExecutableCommand.class, HelpCommand.class,
TestLoginCommand.class, TestRegisterCommand.class, TestUnregisterCommand.class));
}
}
@@ -1,138 +0,0 @@
package fr.xephi.authme.command;
import org.bukkit.ChatColor;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
/**
* Test for {@link CommandUtils}.
*/
public class CommandUtilsTest {
private static Collection<CommandDescription> commands;
@BeforeClass
public static void setUpTestCommands() {
commands = Collections.unmodifiableCollection(TestCommandsUtil.generateCommands());
}
@Test
public void shouldReturnCommandPath() {
// given
CommandDescription base = CommandDescription.builder()
.labels("authme", "auth")
.description("Base")
.detailedDescription("Test base command.")
.executableCommand(ExecutableCommand.class)
.register();
CommandDescription command = CommandDescription.builder()
.parent(base)
.labels("help", "h", "?")
.description("Child")
.detailedDescription("Test child command.")
.executableCommand(ExecutableCommand.class)
.register();
// when
String commandPath = CommandUtils.constructCommandPath(command);
// then
assertThat(commandPath, equalTo("/authme help"));
}
@Test
public void shouldComputeMinAndMaxOnEmptyCommand() {
// given
CommandDescription command = getBuilderForArgsTest().register();
// when / then
checkArgumentCount(command, 0, 0);
}
@Test
public void shouldComputeMinAndMaxOnCommandWithMandatoryArgs() {
// given
CommandDescription command = getBuilderForArgsTest()
.withArgument("Test", "Arg description", false)
.withArgument("Test22", "Arg description 2", false)
.register();
// when / then
checkArgumentCount(command, 2, 2);
}
@Test
public void shouldComputeMinAndMaxOnCommandIncludingOptionalArgs() {
// given
CommandDescription command = getBuilderForArgsTest()
.withArgument("arg1", "Arg description", false)
.withArgument("arg2", "Arg description 2", true)
.withArgument("arg3", "Arg description 3", true)
.register();
// when / then
checkArgumentCount(command, 1, 3);
}
@Test
public void shouldFormatSimpleArgument() {
// given
CommandDescription command = TestCommandsUtil.getCommandWithLabel(commands, "authme");
List<String> labels = Collections.singletonList("authme");
// when
String result = CommandUtils.buildSyntax(command, labels);
// then
assertThat(result, equalTo(ChatColor.WHITE + "/authme" + ChatColor.YELLOW));
}
@Test
public void shouldFormatCommandWithMultipleArguments() {
// given
CommandDescription command = TestCommandsUtil.getCommandWithLabel(commands, "authme", "register");
List<String> labels = Arrays.asList("authme", "reg");
// when
String result = CommandUtils.buildSyntax(command, labels);
// then
assertThat(result, equalTo(ChatColor.WHITE + "/authme" + ChatColor.YELLOW + " reg <password> <confirmation>"));
}
@Test
public void shouldFormatCommandWithOptionalArgument() {
// given
CommandDescription command = TestCommandsUtil.getCommandWithLabel(commands, "email");
List<String> labels = Collections.singletonList("email");
// when
String result = CommandUtils.buildSyntax(command, labels);
// then
assertThat(result, equalTo(ChatColor.WHITE + "/email" + ChatColor.YELLOW + " [player]"));
}
private static void checkArgumentCount(CommandDescription command, int expectedMin, int expectedMax) {
assertThat(CommandUtils.getMinNumberOfArguments(command), equalTo(expectedMin));
assertThat(CommandUtils.getMaxNumberOfArguments(command), equalTo(expectedMax));
}
private static CommandDescription.CommandBuilder getBuilderForArgsTest() {
return CommandDescription.builder()
.labels("authme", "auth")
.description("Base")
.detailedDescription("Test base command.")
.executableCommand(ExecutableCommand.class);
}
}
@@ -1,81 +0,0 @@
package fr.xephi.authme.command;
import org.bukkit.command.BlockCommandSender;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static org.hamcrest.Matchers.containsString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.hamcrest.MockitoHamcrest.argThat;
/**
* Test for {@link PlayerCommand}.
*/
public class PlayerCommandTest {
@Test
public void shouldRejectNonPlayerSender() {
// given
CommandSender sender = mock(BlockCommandSender.class);
PlayerCommandImpl command = new PlayerCommandImpl();
// when
command.executeCommand(sender, Collections.emptyList());
// then
verify(sender).sendMessage(argThat(containsString("only for players")));
}
@Test
public void shouldCallRunCommandForPlayer() {
// given
Player player = mock(Player.class);
List<String> arguments = Arrays.asList("arg1", "testarg2");
PlayerCommandImpl command = new PlayerCommandImpl();
// when
command.executeCommand(player, arguments);
// then
verify(player, times(1)).sendMessage("testarg2");
}
@Test
public void shouldRejectNonPlayerAndSendAlternative() {
// given
CommandSender sender = mock(CommandSender.class);
PlayerCommandWithAlt command = new PlayerCommandWithAlt();
// when
command.executeCommand(sender, Collections.emptyList());
// then
verify(sender, times(1)).sendMessage(argThat(containsString("use /authme test <command> instead")));
}
private static class PlayerCommandImpl extends PlayerCommand {
@Override
public void runCommand(Player player, List<String> arguments) {
player.sendMessage(arguments.get(1));
}
}
private static class PlayerCommandWithAlt extends PlayerCommand {
@Override
public void runCommand(Player player, List<String> arguments) {
throw new IllegalStateException("Should not be called");
}
@Override
public String getAlternativeCommand() {
return "/authme test <command>";
}
}
}
@@ -1,133 +0,0 @@
package fr.xephi.authme.command;
import com.google.common.collect.ImmutableList;
import fr.xephi.authme.command.executable.HelpCommand;
import fr.xephi.authme.permission.AdminPermission;
import fr.xephi.authme.permission.PermissionNode;
import fr.xephi.authme.permission.PlayerPermission;
import org.bukkit.command.CommandSender;
import java.util.Collection;
import java.util.List;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
/**
* Util class for generating and retrieving test commands.
*/
public final class TestCommandsUtil {
private TestCommandsUtil() {
}
/**
* Generate the collection of test commands.
*
* @return The generated commands
*/
public static List<CommandDescription> generateCommands() {
// Register /authme
CommandDescription authMeBase = createCommand(null, null, singletonList("authme"), ExecutableCommand.class);
// Register /authme login <password>
createCommand(PlayerPermission.LOGIN, authMeBase, singletonList("login"),
TestLoginCommand.class, newArgument("password", false));
// Register /authme register <password> <confirmation>, aliases: /authme reg, /authme r
createCommand(PlayerPermission.LOGIN, authMeBase, asList("register", "reg", "r"), TestRegisterCommand.class,
newArgument("password", false), newArgument("confirmation", false));
// Register /email [player]
CommandDescription emailBase = createCommand(null, null, singletonList("email"), ExecutableCommand.class,
newArgument("player", true));
// Register /email helptest -- use only to test for help command arguments special case
CommandDescription.builder().parent(emailBase).labels("helptest").executableCommand(HelpCommand.class)
.description("test").detailedDescription("Test.").withArgument("Query", "", false).register();
// Register /unregister <player>, alias: /unreg
CommandDescription unregisterBase = createCommand(AdminPermission.UNREGISTER, null,
asList("unregister", "unreg"), TestUnregisterCommand.class, newArgument("player", false));
return ImmutableList.of(authMeBase, emailBase, unregisterBase);
}
/**
* Retrieve the command with the given label from the collection of commands.
* Example: <code>getCommandWithLabel(commands, "authme", "reg")</code> to find the command description
* which defines the command /authme reg.
*
* @param commands The commands to search in
* @param parentLabel The parent label to search for
* @param childLabel The child label to find
* @return The matched command, or throws an exception if no command could be found
*/
public static CommandDescription getCommandWithLabel(Collection<CommandDescription> commands, String parentLabel,
String childLabel) {
CommandDescription parent = getCommandWithLabel(commands, parentLabel);
return getCommandWithLabel(parent.getChildren(), childLabel);
}
/**
* Retrieve the command with the given label from the collection of commands.
*
* @param commands The commands to search in
* @param label The label to search for
* @return The matched command, or throws an exception if no command could be found
*/
public static CommandDescription getCommandWithLabel(Collection<CommandDescription> commands, String label) {
for (CommandDescription child : commands) {
if (child.hasLabel(label)) {
return child;
}
}
throw new IllegalStateException("Could not find command with label '" + label + "'");
}
/* Shortcut command to initialize a new test command. */
private static CommandDescription createCommand(PermissionNode permission, CommandDescription parent,
List<String> labels,
Class<? extends ExecutableCommand> commandClass,
CommandArgumentDescription... arguments) {
CommandDescription.CommandBuilder command = CommandDescription.builder()
.labels(labels)
.parent(parent)
.permission(permission)
.description(labels.get(0) + " cmd")
.detailedDescription("'" + labels.get(0) + "' test command")
.executableCommand(commandClass);
if (arguments != null && arguments.length > 0) {
for (CommandArgumentDescription argument : arguments) {
command.withArgument(argument.getName(), argument.getDescription(), argument.isOptional());
}
}
return command.register();
}
/* Shortcut command to initialize a new argument description. */
private static CommandArgumentDescription newArgument(String label, boolean isOptional) {
return new CommandArgumentDescription(label, "'" + label + "' argument description", isOptional);
}
public static class TestLoginCommand implements ExecutableCommand {
@Override
public void executeCommand(CommandSender sender, List<String> arguments) {
// noop
}
}
public static class TestRegisterCommand implements ExecutableCommand {
@Override
public void executeCommand(CommandSender sender, List<String> arguments) {
// noop
}
}
public static class TestUnregisterCommand implements ExecutableCommand {
@Override
public void executeCommand(CommandSender sender, List<String> arguments) {
// noop
}
}
}
@@ -1,163 +0,0 @@
package fr.xephi.authme.command.executable;
import fr.xephi.authme.command.CommandDescription;
import fr.xephi.authme.command.CommandMapper;
import fr.xephi.authme.command.FoundCommandResult;
import fr.xephi.authme.command.help.HelpProvider;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.Collections;
import java.util.List;
import static fr.xephi.authme.command.FoundResultStatus.INCORRECT_ARGUMENTS;
import static fr.xephi.authme.command.FoundResultStatus.MISSING_BASE_COMMAND;
import static fr.xephi.authme.command.FoundResultStatus.SUCCESS;
import static fr.xephi.authme.command.FoundResultStatus.UNKNOWN_LABEL;
import static fr.xephi.authme.command.help.HelpProvider.SHOW_ALTERNATIVES;
import static fr.xephi.authme.command.help.HelpProvider.SHOW_CHILDREN;
import static fr.xephi.authme.command.help.HelpProvider.SHOW_COMMAND;
import static fr.xephi.authme.command.help.HelpProvider.SHOW_DESCRIPTION;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertThat;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.hamcrest.MockitoHamcrest.argThat;
/**
* Test for {@link HelpCommand}.
*/
@RunWith(MockitoJUnitRunner.class)
public class HelpCommandTest {
@InjectMocks
private HelpCommand command;
@Mock
private CommandMapper commandMapper;
@Mock
private HelpProvider helpProvider;
@Test
public void shouldHandleMissingBaseCommand() {
// given
List<String> arguments = asList("some", "command");
CommandSender sender = mock(CommandSender.class);
FoundCommandResult foundCommandResult = new FoundCommandResult(null, null, null, 0.0, MISSING_BASE_COMMAND);
given(commandMapper.mapPartsToCommand(sender, arguments)).willReturn(foundCommandResult);
// when
command.executeCommand(sender, arguments);
// then
verify(sender).sendMessage(argThat(containsString("Could not get base command")));
verifyNoInteractions(helpProvider);
}
@Test
public void shouldHandleWrongCommandWithSuggestion() {
// given
List<String> arguments = asList("authme", "ragister", "test");
CommandSender sender = mock(CommandSender.class);
CommandDescription description = newCommandDescription("authme", "register");
FoundCommandResult foundCommandResult = new FoundCommandResult(description, asList("authme", "ragister"),
singletonList("test"), 0.1, UNKNOWN_LABEL);
given(commandMapper.mapPartsToCommand(sender, arguments)).willReturn(foundCommandResult);
// when
command.executeCommand(sender, arguments);
// then
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
verify(sender).sendMessage(captor.capture());
assertThat(removeColors(captor.getValue()), containsString("Assuming /authme register"));
verify(helpProvider).outputHelp(sender, foundCommandResult, HelpProvider.ALL_OPTIONS);
}
@Test
public void shouldHandleWrongCommandWithoutSuggestion() {
List<String> arguments = asList("authme", "ragister", "test");
CommandSender sender = mock(CommandSender.class);
FoundCommandResult foundCommandResult = new FoundCommandResult(null, asList("authme", "ragister"),
singletonList("test"), 0.4, UNKNOWN_LABEL);
given(commandMapper.mapPartsToCommand(sender, arguments)).willReturn(foundCommandResult);
// when
command.executeCommand(sender, arguments);
// then
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
verify(sender).sendMessage(captor.capture());
assertThat(removeColors(captor.getValue()), containsString("Unknown command"));
verifyNoInteractions(helpProvider);
}
@Test
public void shouldShowChildrenOfBaseCommand() {
List<String> arguments = singletonList("authme");
CommandSender sender = mock(CommandSender.class);
CommandDescription commandDescription = mock(CommandDescription.class);
given(commandDescription.getLabelCount()).willReturn(1);
FoundCommandResult foundCommandResult = new FoundCommandResult(commandDescription, singletonList("authme"),
Collections.emptyList(), 0.0, SUCCESS);
given(commandMapper.mapPartsToCommand(sender, arguments)).willReturn(foundCommandResult);
// when
command.executeCommand(sender, arguments);
// then
verify(sender, never()).sendMessage(anyString());
verify(helpProvider).outputHelp(sender, foundCommandResult,
SHOW_DESCRIPTION | SHOW_COMMAND | SHOW_CHILDREN | SHOW_ALTERNATIVES);
}
@Test
public void shouldShowDetailedHelpForChildCommand() {
List<String> arguments = asList("authme", "getpos");
CommandSender sender = mock(CommandSender.class);
CommandDescription commandDescription = mock(CommandDescription.class);
given(commandDescription.getLabelCount()).willReturn(2);
FoundCommandResult foundCommandResult = new FoundCommandResult(commandDescription, asList("authme", "getpos"),
Collections.emptyList(), 0.0, INCORRECT_ARGUMENTS);
given(commandMapper.mapPartsToCommand(sender, arguments)).willReturn(foundCommandResult);
// when
command.executeCommand(sender, arguments);
// then
verify(sender, never()).sendMessage(anyString());
verify(helpProvider).outputHelp(sender, foundCommandResult, HelpProvider.ALL_OPTIONS);
}
private static CommandDescription newCommandDescription(String... labels) {
CommandDescription parent = null;
// iterate through the labels backwards so we can set the parent
for (String label : labels) {
CommandDescription description = mock(CommandDescription.class);
given(description.getParent()).willReturn(parent);
given(description.getLabels()).willReturn(singletonList(label));
parent = description;
}
return parent;
}
private static String removeColors(String str) {
for (ChatColor color : ChatColor.values()) {
str = str.replace(color.toString(), "");
}
return str;
}
}
@@ -1,178 +0,0 @@
package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.data.auth.PlayerAuth;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.service.BukkitService;
import fr.xephi.authme.service.CommonService;
import org.bukkit.command.CommandSender;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static fr.xephi.authme.service.BukkitServiceTestHelper.setBukkitServiceToRunTaskAsynchronously;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertThat;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/**
* Test for {@link AccountsCommand}.
*/
@RunWith(MockitoJUnitRunner.class)
public class AccountsCommandTest {
@InjectMocks
private AccountsCommand command;
@Mock
private CommonService service;
@Mock
private DataSource dataSource;
@Mock
private BukkitService bukkitService;
@Test
public void shouldGetAccountsOfCurrentUser() {
// given
CommandSender sender = mock(CommandSender.class);
given(sender.getName()).willReturn("Tester");
List<String> arguments = Collections.emptyList();
given(dataSource.getAuth("tester")).willReturn(authWithIp("123.45.67.89"));
given(dataSource.getAllAuthsByIp("123.45.67.89")).willReturn(Arrays.asList("Toaster", "Pester"));
setBukkitServiceToRunTaskAsynchronously(bukkitService);
// when
command.executeCommand(sender, arguments);
// then
String[] messages = getMessagesSentToSender(sender, 2);
assertThat(messages[0], containsString("2 accounts"));
assertThat(messages[1], containsString("Toaster, Pester"));
}
@Test
public void shouldReturnUnknownUserForNullAuth() {
// given
CommandSender sender = mock(CommandSender.class);
List<String> arguments = Collections.singletonList("SomeUser");
given(dataSource.getAuth("someuser")).willReturn(null);
setBukkitServiceToRunTaskAsynchronously(bukkitService);
// when
command.executeCommand(sender, arguments);
// then
verify(service).send(sender, MessageKey.UNKNOWN_USER);
verify(sender, never()).sendMessage(anyString());
}
@Test
public void shouldReturnUnregisteredMessageForEmptyAuthList() {
// given
CommandSender sender = mock(CommandSender.class);
List<String> arguments = Collections.singletonList("SomeUser");
PlayerAuth auth = authWithIp("144.56.77.88");
given(dataSource.getAuth("someuser")).willReturn(auth);
setBukkitServiceToRunTaskAsynchronously(bukkitService);
// when
command.executeCommand(sender, arguments);
// then
verify(service).send(sender, MessageKey.UNKNOWN_USER);
verify(sender, never()).sendMessage(anyString());
}
@Test
public void shouldReturnSingleAccountMessage() {
// given
CommandSender sender = mock(CommandSender.class);
List<String> arguments = Collections.singletonList("SomeUser");
given(dataSource.getAuth("someuser")).willReturn(authWithIp("56.78.90.123"));
given(dataSource.getAllAuthsByIp("56.78.90.123")).willReturn(Collections.singletonList("SomeUser"));
setBukkitServiceToRunTaskAsynchronously(bukkitService);
// when
command.executeCommand(sender, arguments);
// then
String[] messages = getMessagesSentToSender(sender, 1);
assertThat(messages[0], containsString("single account"));
}
// -----
// Query by IP
// -----
@Test
public void shouldReturnIpUnknown() {
// given
CommandSender sender = mock(CommandSender.class);
List<String> arguments = Collections.singletonList("123.45.67.89");
given(dataSource.getAllAuthsByIp("123.45.67.89")).willReturn(Collections.emptyList());
setBukkitServiceToRunTaskAsynchronously(bukkitService);
// when
command.executeCommand(sender, arguments);
// then
String[] messages = getMessagesSentToSender(sender, 1);
assertThat(messages[0], containsString("IP does not exist"));
}
@Test
public void shouldReturnSingleAccountForIpQuery() {
// given
CommandSender sender = mock(CommandSender.class);
List<String> arguments = Collections.singletonList("24.24.48.48");
given(dataSource.getAllAuthsByIp("24.24.48.48")).willReturn(Collections.singletonList("SomeUser"));
setBukkitServiceToRunTaskAsynchronously(bukkitService);
// when
command.executeCommand(sender, arguments);
// then
String[] messages = getMessagesSentToSender(sender, 1);
assertThat(messages[0], containsString("single account"));
}
@Test
public void shouldReturnAccountListForIpQuery() {
// given
CommandSender sender = mock(CommandSender.class);
List<String> arguments = Collections.singletonList("98.76.41.122");
given(dataSource.getAllAuthsByIp("98.76.41.122")).willReturn(Arrays.asList("Tester", "Lester", "Taster"));
setBukkitServiceToRunTaskAsynchronously(bukkitService);
// when
command.executeCommand(sender, arguments);
// then
String[] messages = getMessagesSentToSender(sender, 2);
assertThat(messages[0], containsString("3 accounts"));
assertThat(messages[1], containsString("Tester, Lester, Taster"));
}
private static String[] getMessagesSentToSender(CommandSender sender, int expectedCount) {
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
verify(sender, times(expectedCount)).sendMessage(captor.capture());
return captor.getAllValues().toArray(new String[expectedCount]);
}
private static PlayerAuth authWithIp(String ip) {
return PlayerAuth.builder()
.name("Test")
.lastIp(ip)
.build();
}
}
@@ -1,36 +0,0 @@
package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.command.ExecutableCommand;
import org.bukkit.command.CommandSender;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import java.util.Collections;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/**
* Test for {@link AuthMeCommand}.
*/
public class AuthMeCommandTest {
@Test
public void shouldDisplayInformation() {
// given
ExecutableCommand command = new AuthMeCommand();
CommandSender sender = mock(CommandSender.class);
// when
command.executeCommand(sender, Collections.emptyList());
// then
ArgumentCaptor<String> messagesCaptor = ArgumentCaptor.forClass(String.class);
verify(sender, times(3)).sendMessage(messagesCaptor.capture());
assertThat(messagesCaptor.getAllValues().get(1), containsString("/authme help"));
assertThat(messagesCaptor.getAllValues().get(2), containsString("/authme about"));
}
}
@@ -1,39 +0,0 @@
package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.service.BackupService;
import org.bukkit.command.CommandSender;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.Collections;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* Test for {@link BackupCommand}.
*/
@RunWith(MockitoJUnitRunner.class)
public class BackupCommandTest {
@InjectMocks
private BackupCommand command;
@Mock
private BackupService backupService;
@Test
public void shouldStartBackup() {
// given
CommandSender sender = mock(CommandSender.class);
// when
command.executeCommand(sender, Collections.emptyList());
// then
verify(backupService).doBackup(BackupService.BackupCause.COMMAND, sender);
}
}
@@ -1,73 +0,0 @@
package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.process.Management;
import fr.xephi.authme.service.CommonService;
import fr.xephi.authme.service.ValidationService;
import fr.xephi.authme.service.ValidationService.ValidationResult;
import org.bukkit.command.CommandSender;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.Arrays;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
/**
* Test for {@link ChangePasswordAdminCommand}.
*/
@RunWith(MockitoJUnitRunner.class)
public class ChangePasswordAdminCommandTest {
@InjectMocks
private ChangePasswordAdminCommand command;
@Mock
private CommonService commonService;
@Mock
private ValidationService validationService;
@Mock
private Management management;
@Test
public void shouldForwardRequestToManagement() {
// given
String name = "theUser";
String pass = "newPassword";
given(validationService.validatePassword(pass, name)).willReturn(new ValidationResult());
CommandSender sender = mock(CommandSender.class);
// when
command.executeCommand(sender, Arrays.asList(name, pass));
// then
verify(validationService).validatePassword(pass, name);
verify(management).performPasswordChangeAsAdmin(sender, name, pass);
}
@Test
public void shouldSendErrorToCommandSender() {
// given
String name = "theUser";
String pass = "newPassword";
given(validationService.validatePassword(pass, name)).willReturn(
new ValidationResult(MessageKey.INVALID_PASSWORD_LENGTH, "7"));
CommandSender sender = mock(CommandSender.class);
// when
command.executeCommand(sender, Arrays.asList(name, pass));
// then
verify(validationService).validatePassword(pass, name);
verify(commonService).send(sender, MessageKey.INVALID_PASSWORD_LENGTH, "7");
verifyNoInteractions(management);
}
}
@@ -1,149 +0,0 @@
package fr.xephi.authme.command.executable.authme;
import ch.jalu.injector.factory.Factory;
import fr.xephi.authme.TestHelper;
import fr.xephi.authme.datasource.converter.Converter;
import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.service.BukkitService;
import fr.xephi.authme.service.CommonService;
import fr.xephi.authme.util.StringUtils;
import org.bukkit.command.CommandSender;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.Collections;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import static fr.xephi.authme.service.BukkitServiceTestHelper.setBukkitServiceToRunTaskAsynchronously;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.hamcrest.MockitoHamcrest.argThat;
/**
* Test for {@link ConverterCommand}.
*/
@RunWith(MockitoJUnitRunner.class)
public class ConverterCommandTest {
@InjectMocks
private ConverterCommand command;
@Mock
private CommonService commonService;
@Mock
private BukkitService bukkitService;
@Mock
private Factory<Converter> converterFactory;
@BeforeClass
public static void initLogger() {
TestHelper.setupLogger();
}
@Test
public void shouldHandleUnknownConversionType() {
// given
CommandSender sender = mock(CommandSender.class);
// when
command.executeCommand(sender, Collections.singletonList("invalid"));
// then
String converters = String.join(", ", ConverterCommand.CONVERTERS.keySet());
verify(sender).sendMessage(argThat(containsString(converters)));
verifyNoInteractions(commonService, converterFactory, bukkitService);
}
@Test
public void shouldHandleCommandWithNoArgs() {
// given
CommandSender sender = mock(CommandSender.class);
// when
command.executeCommand(sender, Collections.emptyList());
// then
String converters = String.join(", ", ConverterCommand.CONVERTERS.keySet());
verify(sender).sendMessage(argThat(containsString(converters)));
verifyNoInteractions(commonService, converterFactory, bukkitService);
}
@Test
public void shouldHaveUniqueClassForEachConverter() {
// given
Set<Class<? extends Converter>> classes = new HashSet<>();
// when / then
for (Map.Entry<String, Class<? extends Converter>> entry : ConverterCommand.CONVERTERS.entrySet()) {
assertThat("Name is not null or empty",
StringUtils.isBlank(entry.getKey()), equalTo(false));
assertThat("Converter class is unique for each entry",
classes.add(entry.getValue()), equalTo(true));
}
}
@Test
public void shouldLaunchConverterForAllTypes() {
// given
String converterName = "rakamak";
Class<? extends Converter> converterClass = ConverterCommand.CONVERTERS.get(converterName);
Converter converter = createMockReturnedByInjector(converterClass);
CommandSender sender = mock(CommandSender.class);
setBukkitServiceToRunTaskAsynchronously(bukkitService);
// when
command.executeCommand(sender, Collections.singletonList(converterName));
// then
verify(converter).execute(sender);
verifyNoMoreInteractions(converter);
verify(converterFactory).newInstance(converterClass);
verifyNoMoreInteractions(converterFactory);
}
@Test
public void shouldCatchExceptionInConverterAndInformSender() {
// given
String converterName = "vauth";
Class<? extends Converter> converterClass = ConverterCommand.CONVERTERS.get(converterName);
Converter converter = createMockReturnedByInjector(converterClass);
doThrow(IllegalStateException.class).when(converter).execute(any(CommandSender.class));
CommandSender sender = mock(CommandSender.class);
setBukkitServiceToRunTaskAsynchronously(bukkitService);
// when
command.executeCommand(sender, Collections.singletonList(converterName.toUpperCase(Locale.ROOT)));
// then
verify(converter).execute(sender);
verifyNoMoreInteractions(converter);
verify(converterFactory).newInstance(converterClass);
verifyNoMoreInteractions(converterFactory);
verify(commonService).send(sender, MessageKey.ERROR);
}
private <T extends Converter> T createMockReturnedByInjector(Class<T> clazz) {
T converter = mock(clazz);
given(converterFactory.newInstance(clazz)).willReturn(converter);
return converter;
}
}
@@ -1,63 +0,0 @@
package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.settings.SpawnLoader;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.Collections;
import static org.hamcrest.Matchers.containsString;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.hamcrest.MockitoHamcrest.argThat;
/**
* Test for {@link FirstSpawnCommand}.
*/
@RunWith(MockitoJUnitRunner.class)
public class FirstSpawnCommandTest {
@InjectMocks
private FirstSpawnCommand command;
@Mock
private SpawnLoader spawnLoader;
@Test
public void shouldTeleportToFirstSpawn() {
// given
Location firstSpawn = mock(Location.class);
given(spawnLoader.getFirstSpawn()).willReturn(firstSpawn);
Player player = mock(Player.class);
// when
command.executeCommand(player, Collections.emptyList());
// then
verify(player).teleport(firstSpawn);
verify(spawnLoader, atLeastOnce()).getFirstSpawn();
}
@Test
public void shouldHandleMissingFirstSpawn() {
// given
given(spawnLoader.getFirstSpawn()).willReturn(null);
Player player = mock(Player.class);
// when
command.executeCommand(player, Collections.emptyList());
// then
verify(player).sendMessage(argThat(containsString("spawn has failed")));
verify(player, never()).teleport(any(Location.class));
}
}
@@ -1,133 +0,0 @@
package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.permission.PermissionsManager;
import fr.xephi.authme.permission.PlayerPermission;
import fr.xephi.authme.process.Management;
import fr.xephi.authme.service.BukkitService;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.Collections;
import static org.hamcrest.Matchers.containsString;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.hamcrest.MockitoHamcrest.argThat;
/**
* Test for {@link ForceLoginCommand}.
*/
@RunWith(MockitoJUnitRunner.class)
public class ForceLoginCommandTest {
@InjectMocks
private ForceLoginCommand command;
@Mock
private Management management;
@Mock
private PermissionsManager permissionsManager;
@Mock
private BukkitService bukkitService;
@Test
public void shouldRejectOfflinePlayer() {
// given
String playerName = "Bobby";
Player player = mockPlayer(false);
given(bukkitService.getPlayerExact(playerName)).willReturn(player);
CommandSender sender = mock(CommandSender.class);
// when
command.executeCommand(sender, Collections.singletonList(playerName));
// then
verify(bukkitService).getPlayerExact(playerName);
verify(sender).sendMessage("Player needs to be online!");
verifyNoInteractions(management);
}
@Test
public void shouldRejectInexistentPlayer() {
// given
String playerName = "us3rname01";
given(bukkitService.getPlayerExact(playerName)).willReturn(null);
CommandSender sender = mock(CommandSender.class);
// when
command.executeCommand(sender, Collections.singletonList(playerName));
// then
verify(bukkitService).getPlayerExact(playerName);
verify(sender).sendMessage("Player needs to be online!");
verifyNoInteractions(management);
}
@Test
public void shouldRejectPlayerWithMissingPermission() {
// given
String playerName = "testTest";
Player player = mockPlayer(true);
given(bukkitService.getPlayerExact(playerName)).willReturn(player);
given(permissionsManager.hasPermission(player, PlayerPermission.CAN_LOGIN_BE_FORCED)).willReturn(false);
CommandSender sender = mock(CommandSender.class);
// when
command.executeCommand(sender, Collections.singletonList(playerName));
// then
verify(bukkitService).getPlayerExact(playerName);
verify(sender).sendMessage(argThat(containsString("You cannot force login the player")));
verifyNoInteractions(management);
}
@Test
public void shouldForceLoginPlayer() {
// given
String playerName = "tester23";
Player player = mockPlayer(true);
given(bukkitService.getPlayerExact(playerName)).willReturn(player);
given(permissionsManager.hasPermission(player, PlayerPermission.CAN_LOGIN_BE_FORCED)).willReturn(true);
CommandSender sender = mock(CommandSender.class);
// when
command.executeCommand(sender, Collections.singletonList(playerName));
// then
verify(bukkitService).getPlayerExact(playerName);
verify(management).forceLogin(player);
}
@Test
public void shouldForceLoginSenderSelf() {
// given
String senderName = "tester23";
Player player = mockPlayer(true);
given(bukkitService.getPlayerExact(senderName)).willReturn(player);
given(permissionsManager.hasPermission(player, PlayerPermission.CAN_LOGIN_BE_FORCED)).willReturn(true);
CommandSender sender = mock(CommandSender.class);
given(sender.getName()).willReturn(senderName);
// when
command.executeCommand(sender, Collections.emptyList());
// then
verify(bukkitService).getPlayerExact(senderName);
verify(management).forceLogin(player);
}
private static Player mockPlayer(boolean isOnline) {
Player player = mock(Player.class);
given(player.isOnline()).willReturn(isOnline);
return player;
}
}
@@ -1,65 +0,0 @@
package fr.xephi.authme.command.executable.authme;
import ch.jalu.datasourcecolumns.data.DataSourceValueImpl;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.service.CommonService;
import org.bukkit.command.CommandSender;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.Collections;
import static org.hamcrest.Matchers.containsString;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.hamcrest.MockitoHamcrest.argThat;
/**
* Test for {@link GetEmailCommand}.
*/
@RunWith(MockitoJUnitRunner.class)
public class GetEmailCommandTest {
@InjectMocks
private GetEmailCommand command;
@Mock
private DataSource dataSource;
@Mock
private CommonService service;
@Test
public void shouldReportUnknownUser() {
// given
String user = "myTestUser";
given(dataSource.getEmail(user)).willReturn(DataSourceValueImpl.unknownRow());
CommandSender sender = mock(CommandSender.class);
// when
command.executeCommand(sender, Collections.singletonList(user));
// then
verify(service).send(sender, MessageKey.UNKNOWN_USER);
}
@Test
public void shouldReturnEmail() {
// given
String user = "userToView";
String email = "user.email@example.org";
given(dataSource.getEmail(user)).willReturn(DataSourceValueImpl.of(email));
CommandSender sender = mock(CommandSender.class);
// when
command.executeCommand(sender, Collections.singletonList(user));
// then
verify(sender).sendMessage(argThat(containsString(email)));
}
}
@@ -1,106 +0,0 @@
package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.TestHelper;
import fr.xephi.authme.data.auth.PlayerAuth;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.service.BukkitService;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.Collections;
import static org.hamcrest.Matchers.both;
import static org.hamcrest.Matchers.containsString;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.verify;
import static org.mockito.hamcrest.MockitoHamcrest.argThat;
/**
* Test for {@link GetIpCommand}.
*/
@RunWith(MockitoJUnitRunner.class)
public class GetIpCommandTest {
@InjectMocks
private GetIpCommand command;
@Mock
private BukkitService bukkitService;
@Mock
private DataSource dataSource;
@Test
public void shouldGetIpOfPlayer() {
// given
given(bukkitService.getPlayerExact(anyString())).willReturn(null);
given(dataSource.getAuth(anyString())).willReturn(null);
CommandSender sender = mock(CommandSender.class);
String name = "Testt";
// when
command.executeCommand(sender, Collections.singletonList(name));
// then
verify(bukkitService).getPlayerExact(name);
verify(dataSource).getAuth(name);
verify(sender, only()).sendMessage(argThat(containsString("not registered")));
}
@Test
public void shouldReturnIpAddressOfPlayer() {
// given
String playerName = "charlie";
String ip = "123.34.56.88";
Player player = mockPlayer(playerName, ip);
given(bukkitService.getPlayerExact(playerName)).willReturn(player);
PlayerAuth auth = PlayerAuth.builder().name("t").lastIp("44.33.22.11").registrationIp("77.11.44.88").build();
given(dataSource.getAuth(playerName)).willReturn(auth);
CommandSender sender = mock(CommandSender.class);
// when
command.executeCommand(sender, Collections.singletonList(playerName));
// then
verify(bukkitService).getPlayerExact(playerName);
verify(dataSource).getAuth(playerName);
verify(sender).sendMessage(argThat(both(containsString(playerName)).and(containsString(ip))));
verify(sender).sendMessage(argThat(both(containsString("44.33.22.11")).and(containsString("77.11.44.88"))));
}
@Test
public void shouldHandleUnregisteredOnlinePlayer() {
// given
String playerName = "Test";
String ip = "44.111.22.33";
Player player = mockPlayer(playerName, ip);
given(bukkitService.getPlayerExact(playerName)).willReturn(player);
given(dataSource.getAuth(anyString())).willReturn(null);
CommandSender sender = mock(CommandSender.class);
// when
command.executeCommand(sender, Collections.singletonList(playerName));
// then
verify(bukkitService).getPlayerExact(playerName);
verify(dataSource).getAuth(playerName);
verify(sender).sendMessage(argThat(both(containsString(playerName)).and(containsString(ip))));
verify(sender).sendMessage(argThat(containsString("not registered")));
}
private static Player mockPlayer(String name, String ip) {
Player player = mock(Player.class);
given(player.getName()).willReturn(name);
TestHelper.mockIpAddressToPlayer(player, ip);
return player;
}
}

Some files were not shown because too many files have changed in this diff Show More