Merge branch 'master' into cache

This commit is contained in:
DNx5 2016-02-20 09:48:27 +07:00
commit fd12efa2c0
24 changed files with 388 additions and 398 deletions

View File

@ -122,7 +122,7 @@ typing commands or using the inventory. It can also kick players with uncommonly
</li><li><a href="http://dev.bukkit.org/server-mods/authme-reloaded/pages/web-site-integration/">Website Integration</a>
</li><li><a href="https://raw.githubusercontent.com/Xephi/AuthMeReloaded/master/src/main/resources/config.yml">Click here for an example of the Config file</a>
</li><li><a href="http://dev.bukkit.org/server-mods/authme-reloaded/pages/how-to-import-database-from-rakamak/">How to convert from Rakamak</a>
</li><li>Convert from FlatFile (auths.db but not the sqlite one) to MySQL: /converter
</li><li>Convert from FlatFile (auths.db but not the sqlite one) to MySQL: /authme converter
</li></ul>
<hr>

10
pom.xml
View File

@ -372,7 +372,7 @@
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-jdk14</artifactId>
<version>1.7.14</version>
<version>1.7.16</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
@ -400,7 +400,7 @@
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.5</version>
<version>2.6.1</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
@ -416,9 +416,9 @@
<!-- Maxmind GeoIp API -->
<dependency>
<groupId>com.maxmind.geoip2</groupId>
<artifactId>geoip2</artifactId>
<version>2.6.0</version>
<groupId>com.maxmind.geoip</groupId>
<artifactId>geoip-api</artifactId>
<version>1.3.1</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>

View File

@ -0,0 +1,86 @@
<!--
This is a demo page for AuthMe website integration with BCrypt.
See integration.php for the PHP code you need.
-->
<!DOCTYPE html>
<html lang="en">
<head>
<title>AuthMe Integration Sample</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<?php
error_reporting(E_ALL);
$action = get_from_post_or_empty('action');
$user = get_from_post_or_empty('username');
$pass = get_from_post_or_empty('password');
$was_successful = false;
if ($action && $user && $pass) {
require_once('integration.php');
if ($action === 'Log in') {
$was_successful = process_login($user, $pass);
} else if ($action === 'Register') {
$was_successful = process_register($user, $pass);
}
}
if (!$was_successful) {
echo '<h1>Login sample</h1>
This is a demo form for AuthMe website integration. Enter your AuthMe login details
into the following form to test it.
<form method="post">
<table>
<tr><td>Name</td><td><input type="text" value="' . htmlspecialchars($user) . '" name="username" /></td></tr>
<tr><td>Pass</td><td><input type="password" value="' . htmlspecialchars($pass) . '" name="password" /></td></tr>
<tr>
<td><input type="submit" name="action" value="Log in" /></td>
<td><input type="submit" name="action" value="Register" /></td>
</tr>
</table>
</form>';
}
function get_from_post_or_empty($index_name) {
return trim(
filter_input(INPUT_POST, $index_name, FILTER_UNSAFE_RAW, FILTER_REQUIRE_SCALAR | FILTER_FLAG_STRIP_LOW)
?: '');
}
// Login logic
function process_login($user, $pass) {
if (authme_check_password($user, $pass)) {
printf('<h1>Hello, %s!</h1>', htmlspecialchars($user));
echo 'Successful login. Nice to have you back!'
. '<br /><a href="form.php">Back to form</a>';
return true;
} else {
echo '<h1>Error</h1> Invalid username or password.';
}
return false;
}
// Register logic
function process_register($user, $pass) {
if (authme_has_user($user)) {
echo '<h1>Error</h1> This user already exists.';
} else {
// Note that we don't validate the password or username at all in this demo...
$register_success = authme_register($user, $pass);
if ($register_success) {
printf('<h1>Welcome, %s!</h1>Thanks for registering', htmlspecialchars($user));
echo '<br /><a href="form.php">Back to form</a>';
return true;
} else {
echo '<h1>Error</h1>Unfortunately, there was an error during the registration.';
}
}
return false;
}
?>
</body>
</html>

View File

@ -0,0 +1,107 @@
<?php
/*****************************************************************************
* AuthMe website integration logic for BCrypt *
* -------------------------------- *
* Check with authme_check_password() whether the received username and *
* password match the AuthMe MySQL database. Don't forget to adjust the *
* database info in authme_get_hash(). *
* *
* Source: https://github.com/AuthMe-Team/AuthMeReloaded/ *
*****************************************************************************/
/** The name of the authme MySQL table. */
define('AUTHME_TABLE', 'authme');
/**
* Entry point function to check supplied credentials against the AuthMe database.
*
* @param string $username the username
* @param string $password the password
* @return bool true iff the data is correct, false otherwise
*/
function authme_check_password($username, $password) {
if (is_scalar($username) && is_scalar($password)) {
$hash = authme_get_hash($username);
if ($hash) {
return password_verify($password, $hash);
}
}
return false;
}
/**
* Returns a connection to the database.
*
* @return mysqli|null the mysqli object or null upon error
*/
function authme_get_mysqli() {
$mysqli = new mysqli('localhost', 'root', '', 'authme');
if (mysqli_connect_error()) {
printf('Could not connect to AuthMe database. Errno: %d, error: "%s"',
mysqli_connect_errno(), mysqli_connect_error());
return null;
}
return $mysqli;
}
/**
* Retrieves the hash associated with the given user from the database.
*
* @param string $username the username whose hash should be retrieved
* @return string|null the hash, or null if unavailable (e.g. username doesn't exist)
*/
function authme_get_hash($username) {
// Add here your database host, username, password and database name
$mysqli = authme_get_mysqli();
if ($mysqli !== null) {
$stmt = $mysqli->prepare('SELECT password FROM ' . AUTHME_TABLE . ' WHERE username = ?');
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->bind_result($password);
if ($stmt->fetch()) {
return $password;
}
}
return null;
}
/**
* Returns whether the user exists in the database or not.
*
* @param string $username the username to check
* @return bool true if the user exists; false otherwise
*/
function authme_has_user($username) {
$mysqli = authme_get_mysqli();
if ($mysqli !== null) {
$stmt = $mysqli->prepare('SELECT 1 FROM ' . AUTHME_TABLE . ' WHERE username = ?');
$stmt->bind_param('s', $username);
$stmt->execute();
return $stmt->fetch();
}
// Defensive default to true; we actually don't know
return true;
}
/**
* Registers a player with the given username.
*
* @param string $username the username to register
* @param string $password the password to associate to the user
* @return bool whether or not the registration was successful
*/
function authme_register($username, $password) {
$mysqli = authme_get_mysqli();
if ($mysqli !== null) {
$hash = password_hash($password, PASSWORD_BCRYPT);
$stmt = $mysqli->prepare('INSERT INTO ' . AUTHME_TABLE . ' (username, realname, password, ip) '
. 'VALUES (?, ?, ?, ?)');
$username_low = strtolower($username);
$stmt->bind_param('ssss', $username, $username_low, $hash, $_SERVER['REMOTE_ADDR']);
return $stmt->execute();
}
return false;
}

View File

@ -1,5 +1,5 @@
<!--
This is a demo page for AuthMe website integration.
This is a demo page for AuthMe website integration with SHA256.
See integration.php for the PHP code you need.
-->
<!DOCTYPE html>
@ -36,7 +36,7 @@ into the following form to test it.
<table>
<tr><td>Name</td><td><input type="text" value="' . htmlspecialchars($user) . '" name="username" /></td></tr>
<tr><td>Pass</td><td><input type="password" value="' . htmlspecialchars($pass) . '" name="password" /></td></tr>
<tr><td colspan="2"><input type="submit" value=" Log in " />
<tr><td colspan="2"><input type="submit" value=" Log in " /></td></tr>
</table>
</form>';
}

View File

@ -1,6 +1,6 @@
<?php
/*****************************************************************************
* AuthMe website integration logic *
* AuthMe website integration logic for SHA256 *
* -------------------------------- *
* Check with authme_check_password() whether the received username and *
* password match the AuthMe MySQL database. Don't forget to adjust the *

View File

@ -5,6 +5,7 @@ import fr.xephi.authme.command.executable.HelpCommand;
import fr.xephi.authme.command.executable.authme.AccountsCommand;
import fr.xephi.authme.command.executable.authme.AuthMeCommand;
import fr.xephi.authme.command.executable.authme.ChangePasswordAdminCommand;
import fr.xephi.authme.command.executable.authme.ConverterCommand;
import fr.xephi.authme.command.executable.authme.FirstSpawnCommand;
import fr.xephi.authme.command.executable.authme.ForceLoginCommand;
import fr.xephi.authme.command.executable.authme.GetEmailCommand;
@ -24,7 +25,6 @@ import fr.xephi.authme.command.executable.authme.UnregisterAdminCommand;
import fr.xephi.authme.command.executable.authme.VersionCommand;
import fr.xephi.authme.command.executable.captcha.CaptchaCommand;
import fr.xephi.authme.command.executable.changepassword.ChangePasswordCommand;
import fr.xephi.authme.command.executable.converter.ConverterCommand;
import fr.xephi.authme.command.executable.email.AddEmailCommand;
import fr.xephi.authme.command.executable.email.ChangeEmailCommand;
import fr.xephi.authme.command.executable.email.EmailBaseCommand;
@ -269,6 +269,17 @@ public final class CommandInitializer {
.executableCommand(new VersionCommand())
.build();
CommandDescription.builder()
.parent(AUTHME_BASE)
.labels("converter", "convert", "conv")
.description("Converter Command")
.detailedDescription("Converter command for AuthMeReloaded.")
.withArgument("job", "Conversion job: xauth / crazylogin / rakamak / " +
"royalauth / vauth / sqlitetosql", false)
.permissions(OP_ONLY, AdminPermission.CONVERTER)
.executableCommand(new ConverterCommand())
.build();
// Register the base login command
final CommandDescription LOGIN_BASE = CommandDescription.builder()
.parent(null)
@ -381,18 +392,6 @@ public final class CommandInitializer {
.executableCommand(new CaptchaCommand())
.build();
// Register the base converter command
CommandDescription CONVERTER_BASE = CommandDescription.builder()
.parent(null)
.labels("converter", "convert", "conv")
.description("Converter Command")
.detailedDescription("Converter command for AuthMeReloaded.")
.withArgument("job", "Conversion job: xauth / crazylogin / rakamak / " +
"royalauth / vauth / sqlitetosql", false)
.permissions(OP_ONLY, AdminPermission.CONVERTER)
.executableCommand(new ConverterCommand())
.build();
Set<CommandDescription> baseCommands = ImmutableSet.of(
AUTHME_BASE,
LOGIN_BASE,
@ -401,8 +400,7 @@ public final class CommandInitializer {
UNREGISTER_BASE,
CHANGE_PASSWORD_BASE,
EMAIL_BASE,
CAPTCHA_BASE,
CONVERTER_BASE);
CAPTCHA_BASE);
setHelpOnAllBases(baseCommands);
return baseCommands;

View File

@ -30,7 +30,7 @@ public class AccountsCommand implements ExecutableCommand {
return;
}
List<String> accountList = commandService.getDataSource().getAllAuthsByName(auth);
List<String> accountList = commandService.getDataSource().getAllAuthsByIp(auth.getIp());
if (accountList.isEmpty()) {
commandService.send(sender, MessageKey.USER_NOT_REGISTERED);
} else if (accountList.size() == 1) {

View File

@ -1,4 +1,4 @@
package fr.xephi.authme.command.executable.converter;
package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.command.CommandService;

View File

@ -7,8 +7,6 @@ import fr.xephi.authme.datasource.DataSourceType;
import fr.xephi.authme.datasource.SQLite;
import fr.xephi.authme.settings.NewSetting;
import fr.xephi.authme.settings.properties.DatabaseSettings;
import fr.xephi.authme.util.StringUtils;
import java.sql.SQLException;
/**

View File

@ -115,24 +115,6 @@ public class CacheDataSource implements DataSource {
return result;
}
@Override
public int getIps(String ip) {
return source.getIps(ip);
}
@Override
public int purgeDatabase(long until) {
int cleared = source.purgeDatabase(until);
if (cleared > 0) {
for (Optional<PlayerAuth> auth : cachedAuths.asMap().values()) {
if (auth.isPresent() && auth.get().getLastLogin() < until) {
cachedAuths.invalidate(auth.get().getNickname());
}
}
}
return cleared;
}
@Override
public List<String> autoPurgeDatabase(long until) {
List<String> cleared = source.autoPurgeDatabase(until);
@ -172,11 +154,6 @@ public class CacheDataSource implements DataSource {
return result;
}
@Override
public synchronized List<String> getAllAuthsByName(PlayerAuth auth) {
return source.getAllAuthsByName(auth);
}
@Override
public synchronized List<String> getAllAuthsByIp(final String ip) {
return source.getAllAuthsByIp(ip);
@ -239,6 +216,15 @@ public class CacheDataSource implements DataSource {
return result;
}
@Override
public boolean updateIp(String user, String ip) {
boolean result = source.updateIp(user, ip);
if (result) {
cachedAuths.refresh(user);
}
return result;
}
@Override
public List<PlayerAuth> getAllAuths() {
return source.getAllAuths();

View File

@ -6,146 +6,132 @@ import fr.xephi.authme.security.crypts.HashedPassword;
import java.util.List;
/**
* Interface for manipulating {@link PlayerAuth} objects from a data source.
*/
public interface DataSource {
/**
* Method isAuthAvailable.
* Return whether there is a record for the given username.
*
* @param user String
* @param user The username to look up
*
* @return boolean
* @return True if there is a record, false otherwise
*/
boolean isAuthAvailable(String user);
/**
* Method getPassword.
* Return the hashed password of the player.
*
* @param user String
* @param user The user whose password should be retrieve
*
* @return String
* @return The password hash of the player
*/
HashedPassword getPassword(String user);
/**
* Method getAuth.
* Retrieve the entire PlayerAuth object associated with the username.
*
* @param user String
* @param user The user to retrieve
*
* @return PlayerAuth
* @return The PlayerAuth object for the given username
*/
PlayerAuth getAuth(String user);
/**
* Method saveAuth.
* Save a new PlayerAuth object.
*
* @param auth PlayerAuth
* @param auth The new PlayerAuth to persist
*
* @return boolean
* @return True upon success, false upon failure
*/
boolean saveAuth(PlayerAuth auth);
/**
* Method updateSession.
* Update the session of a record (IP, last login, real name).
*
* @param auth PlayerAuth
* @param auth The PlayerAuth object to update in the database
*
* @return boolean
* @return True upon success, false upon failure
*/
boolean updateSession(PlayerAuth auth);
/**
* Method updatePassword.
* Update the password of the given PlayerAuth object.
*
* @param auth PlayerAuth
* @param auth The PlayerAuth whose password should be updated
*
* @return boolean
* @return True upon success, false upon failure
*/
boolean updatePassword(PlayerAuth auth);
/**
* Update the password of the given player.
*
* @param user The user whose password should be updated
* @param password The new password
*
* @return True upon success, false upon failure
*/
boolean updatePassword(String user, HashedPassword password);
/**
* Method purgeDatabase.
* Purge all records in the database whose last login was longer ago than
* the given time.
*
* @param until long
* @param until The minimum last login
*
* @return int
*/
int purgeDatabase(long until);
/**
* Method autoPurgeDatabase.
*
* @param until long
*
* @return List of String
* @return The account names that have been removed
*/
List<String> autoPurgeDatabase(long until);
/**
* Method removeAuth.
* Remove a user record from the database.
*
* @param user String
* @param user The user to remove
*
* @return boolean
* @return True upon success, false upon failure
*/
boolean removeAuth(String user);
/**
* Method updateQuitLoc.
* Update the quit location of a PlayerAuth.
*
* @param auth PlayerAuth
* @param auth The entry whose quit location should be updated
*
* @return boolean
* @return True upon success, false upon failure
*/
boolean updateQuitLoc(PlayerAuth auth);
/**
* Method getIps.
* Return all usernames associated with the given IP address.
*
* @param ip String
* @param ip The IP address to look up
*
* @return int
*/
int getIps(String ip);
/**
* Method getAllAuthsByName.
*
* @param auth PlayerAuth
*
* @return List of String
*/
List<String> getAllAuthsByName(PlayerAuth auth);
/**
* Method getAllAuthsByIp.
*
* @param ip String
*
* @return List of String * @throws Exception
* @return Usernames associated with the given IP address
*/
List<String> getAllAuthsByIp(String ip);
/**
* Method getAllAuthsByEmail.
* Return all usernames associated with the given email address.
*
* @param email String
* @param email The email address to look up
*
* @return List of String * @throws Exception
* @return Users using the given email address
*/
List<String> getAllAuthsByEmail(String email);
/**
* Method updateEmail.
* Update the email of the PlayerAuth in the data source.
*
* @param auth PlayerAuth
* @param auth The PlayerAuth whose email should be updated
*
* @return boolean
* @return True upon success, false upon failure
*/
boolean updateEmail(PlayerAuth auth);
/**
* Close the underlying connections to the data source.
*/
void close();
void reload();
@ -205,6 +191,9 @@ public interface DataSource {
void updateName(String oldOne, String newOne);
boolean updateRealName(String user, String realName);
boolean updateIp(String user, String ip);
/**
* Method getAllAuths.
*

View File

@ -278,82 +278,6 @@ public class FlatFile implements DataSource {
return true;
}
@Override
public int getIps(String ip) {
BufferedReader br = null;
int countIp = 0;
try {
br = new BufferedReader(new FileReader(source));
String line;
while ((line = br.readLine()) != null) {
String[] args = line.split(":");
if (args.length > 3 && args[2].equals(ip)) {
countIp++;
}
}
return countIp;
} catch (FileNotFoundException ex) {
ConsoleLogger.showError(ex.getMessage());
return 0;
} catch (IOException ex) {
ConsoleLogger.showError(ex.getMessage());
return 0;
} finally {
if (br != null) {
try {
br.close();
} catch (IOException ignored) {
}
}
}
}
@Override
public int purgeDatabase(long until) {
BufferedReader br = null;
BufferedWriter bw = null;
ArrayList<String> lines = new ArrayList<>();
int cleared = 0;
try {
br = new BufferedReader(new FileReader(source));
String line;
while ((line = br.readLine()) != null) {
String[] args = line.split(":");
if (args.length >= 4) {
if (Long.parseLong(args[3]) >= until) {
lines.add(line);
continue;
}
}
cleared++;
}
bw = new BufferedWriter(new FileWriter(source));
for (String l : lines) {
bw.write(l + "\n");
}
} catch (FileNotFoundException ex) {
ConsoleLogger.showError(ex.getMessage());
return cleared;
} catch (IOException ex) {
ConsoleLogger.showError(ex.getMessage());
return cleared;
} finally {
if (br != null) {
try {
br.close();
} catch (IOException ignored) {
}
}
if (bw != null) {
try {
bw.close();
} catch (IOException ignored) {
}
}
}
return cleared;
}
@Override
public List<String> autoPurgeDatabase(long until) {
BufferedReader br = null;
@ -532,36 +456,6 @@ public class FlatFile implements DataSource {
return true;
}
@Override
public List<String> getAllAuthsByName(PlayerAuth auth) {
BufferedReader br = null;
List<String> countIp = new ArrayList<>();
try {
br = new BufferedReader(new FileReader(source));
String line;
while ((line = br.readLine()) != null) {
String[] args = line.split(":");
if (args.length > 3 && args[2].equals(auth.getIp())) {
countIp.add(args[0]);
}
}
return countIp;
} catch (FileNotFoundException ex) {
ConsoleLogger.showError(ex.getMessage());
return new ArrayList<>();
} catch (IOException ex) {
ConsoleLogger.showError(ex.getMessage());
return new ArrayList<>();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException ignored) {
}
}
}
}
@Override
public List<String> getAllAuthsByIp(String ip) {
BufferedReader br = null;
@ -721,6 +615,11 @@ public class FlatFile implements DataSource {
return false;
}
@Override
public boolean updateIp(String user, String ip) {
throw new UnsupportedOperationException("Flat file no longer supported");
}
@Override
public List<PlayerAuth> getAllAuths() {
BufferedReader br = null;

View File

@ -562,16 +562,14 @@ public class MySQL implements DataSource {
@Override
public synchronized boolean updateSession(PlayerAuth auth) {
try (Connection con = getConnection()) {
String sql = "UPDATE " + tableName + " SET "
+ col.IP + "=?, " + col.LAST_LOGIN + "=?, " + col.REAL_NAME + "=? WHERE " + col.NAME + "=?;";
PreparedStatement pst = con.prepareStatement(sql);
String sql = "UPDATE " + tableName + " SET "
+ col.IP + "=?, " + col.LAST_LOGIN + "=?, " + col.REAL_NAME + "=? WHERE " + col.NAME + "=?;";
try (Connection con = getConnection(); PreparedStatement pst = con.prepareStatement(sql)) {
pst.setString(1, auth.getIp());
pst.setTimestamp(2, new Timestamp(auth.getLastLogin()));
pst.setString(3, auth.getRealName());
pst.setString(4, auth.getNickname());
pst.executeUpdate();
pst.close();
return true;
} catch (SQLException ex) {
logSqlException(ex);
@ -579,20 +577,6 @@ public class MySQL implements DataSource {
return false;
}
@Override
public synchronized int purgeDatabase(long until) {
int result = 0;
try (Connection con = getConnection()) {
String sql = "DELETE FROM " + tableName + " WHERE " + col.LAST_LOGIN + "<?;";
PreparedStatement pst = con.prepareStatement(sql);
pst.setLong(1, until);
result = pst.executeUpdate();
} catch (SQLException ex) {
logSqlException(ex);
}
return result;
}
@Override
public synchronized List<String> autoPurgeDatabase(long until) {
List<String> list = new ArrayList<>();
@ -669,25 +653,6 @@ public class MySQL implements DataSource {
return false;
}
@Override
public synchronized int getIps(String ip) {
int countIp = 0;
try (Connection con = getConnection()) {
String sql = "SELECT COUNT(*) FROM " + tableName + " WHERE " + col.IP + "=?;";
PreparedStatement pst = con.prepareStatement(sql);
pst.setString(1, ip);
ResultSet rs = pst.executeQuery();
while (rs.next()) {
countIp = rs.getInt(1);
}
rs.close();
pst.close();
} catch (SQLException ex) {
logSqlException(ex);
}
return countIp;
}
@Override
public synchronized boolean updateEmail(PlayerAuth auth) {
try (Connection con = getConnection()) {
@ -722,25 +687,6 @@ public class MySQL implements DataSource {
}
}
@Override
public synchronized List<String> getAllAuthsByName(PlayerAuth auth) {
List<String> result = new ArrayList<>();
try (Connection con = getConnection()) {
String sql = "SELECT " + col.NAME + " FROM " + tableName + " WHERE " + col.IP + "=?;";
PreparedStatement pst = con.prepareStatement(sql);
pst.setString(1, auth.getIp());
ResultSet rs = pst.executeQuery();
while (rs.next()) {
result.add(rs.getString(col.NAME));
}
rs.close();
pst.close();
} catch (SQLException ex) {
logSqlException(ex);
}
return result;
}
@Override
public synchronized List<String> getAllAuthsByIp(String ip) {
List<String> result = new ArrayList<>();
@ -900,6 +846,21 @@ public class MySQL implements DataSource {
return false;
}
@Override
public boolean updateIp(String user, String ip) {
try (Connection con = getConnection()) {
String sql = "UPDATE " + tableName + " SET " + col.IP + "=? WHERE " + col.NAME + "=?;";
PreparedStatement pst = con.prepareStatement(sql);
pst.setString(1, ip);
pst.setString(2, user);
pst.executeUpdate();
return true;
} catch (SQLException ex) {
logSqlException(ex);
}
return false;
}
@Override
public List<PlayerAuth> getAllAuths() {
List<PlayerAuth> auths = new ArrayList<>();

View File

@ -266,18 +266,6 @@ public class SQLite implements DataSource {
return false;
}
@Override
public int purgeDatabase(long until) {
String sql = "DELETE FROM " + tableName + " WHERE " + col.LAST_LOGIN + "<?;";
try (PreparedStatement pst = con.prepareStatement(sql)) {
pst.setLong(1, until);
return pst.executeUpdate();
} catch (SQLException ex) {
logSqlException(ex);
}
return 0;
}
@Override
public List<String> autoPurgeDatabase(long until) {
PreparedStatement pst = null;
@ -336,29 +324,6 @@ public class SQLite implements DataSource {
return false;
}
@Override
public int getIps(String ip) {
PreparedStatement pst = null;
ResultSet rs = null;
int countIp = 0;
try {
// TODO ljacqu 20151230: Simply fetch COUNT(1) and return that
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + col.IP + "=?;");
pst.setString(1, ip);
rs = pst.executeQuery();
while (rs.next()) {
countIp++;
}
return countIp;
} catch (SQLException ex) {
logSqlException(ex);
} finally {
close(rs);
close(pst);
}
return 0;
}
@Override
public boolean updateEmail(PlayerAuth auth) {
String sql = "UPDATE " + tableName + " SET " + col.EMAIL + "=? WHERE " + col.NAME + "=?;";
@ -406,37 +371,13 @@ public class SQLite implements DataSource {
}
}
@Override
public List<String> getAllAuthsByName(PlayerAuth auth) {
PreparedStatement pst = null;
ResultSet rs = null;
List<String> names = new ArrayList<>();
try {
// TODO ljacqu 20160214: Use SELECT name if only the name is required
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + col.IP + "=?;");
pst.setString(1, auth.getIp());
rs = pst.executeQuery();
while (rs.next()) {
names.add(rs.getString(col.NAME));
}
return names;
} catch (SQLException ex) {
logSqlException(ex);
} finally {
close(rs);
close(pst);
}
return new ArrayList<>();
}
@Override
public List<String> getAllAuthsByIp(String ip) {
PreparedStatement pst = null;
ResultSet rs = null;
List<String> countIp = new ArrayList<>();
try {
pst = con.prepareStatement("SELECT * FROM " + tableName + " WHERE " + col.IP + "=?;");
pst = con.prepareStatement("SELECT " + col.NAME + " FROM " + tableName + " WHERE " + col.IP + "=?;");
pst.setString(1, ip);
rs = pst.executeQuery();
while (rs.next()) {
@ -607,6 +548,20 @@ public class SQLite implements DataSource {
return false;
}
@Override
public boolean updateIp(String user, String ip) {
String sql = "UPDATE " + tableName + " SET " + col.IP + "=? WHERE " + col.NAME + "=?;";
try(PreparedStatement pst = con.prepareStatement(sql)) {
pst.setString(1, ip);
pst.setString(2, user);
pst.executeUpdate();
return true;
} catch (SQLException ex) {
logSqlException(ex);
}
return false;
}
@Override
public List<PlayerAuth> getAllAuths() {
List<PlayerAuth> auths = new ArrayList<>();

View File

@ -1,6 +1,7 @@
package fr.xephi.authme.process.email;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.datasource.DataSource;
@ -48,8 +49,13 @@ public class AsyncAddEmail {
messages.send(player, MessageKey.EMAIL_ALREADY_USED_ERROR);
} else {
auth.setEmail(email);
playerCache.updatePlayer(auth);
messages.send(player, MessageKey.EMAIL_ADDED_SUCCESS);
if (dataSource.updateEmail(auth)) {
playerCache.updatePlayer(auth);
messages.send(player, MessageKey.EMAIL_ADDED_SUCCESS);
} else {
ConsoleLogger.showError("Could not save email for player '" + player + "'");
messages.send(player, MessageKey.ERROR);
}
}
} else {
sendUnloggedMessage(dataSource);

View File

@ -7,12 +7,12 @@ import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.cache.limbo.LimboCache;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.events.AuthMeAsyncPreLoginEvent;
import fr.xephi.authme.output.MessageKey;
import fr.xephi.authme.output.Messages;
import fr.xephi.authme.permission.AdminPermission;
import fr.xephi.authme.permission.PlayerPermission;
import fr.xephi.authme.permission.PlayerStatePermission;
import fr.xephi.authme.security.RandomString;
import fr.xephi.authme.output.MessageKey;
import fr.xephi.authme.output.Messages;
import fr.xephi.authme.settings.NewSetting;
import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.settings.properties.RegistrationSettings;
@ -23,7 +23,6 @@ import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitTask;
import java.util.Date;
import java.util.List;
/**
@ -143,7 +142,7 @@ public class AsynchronousLogin {
if (pAuth.getIp().equals("127.0.0.1") && !pAuth.getIp().equals(ip)) {
pAuth.setIp(ip);
database.saveAuth(pAuth);
database.updateIp(pAuth.getNickname(), ip);
}
String email = pAuth.getEmail();
@ -226,7 +225,7 @@ public class AsynchronousLogin {
return;
}
List<String> auths = this.database.getAllAuthsByName(auth);
List<String> auths = this.database.getAllAuthsByIp(auth.getIp());
if (auths.size() < 2) {
return;
}

View File

@ -1,19 +1,18 @@
package fr.xephi.authme.process.register;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.output.MessageKey;
import fr.xephi.authme.output.Messages;
import fr.xephi.authme.permission.PlayerPermission;
import fr.xephi.authme.permission.PlayerStatePermission;
import fr.xephi.authme.security.HashAlgorithm;
import fr.xephi.authme.security.crypts.HashedPassword;
import fr.xephi.authme.security.crypts.TwoFactor;
import fr.xephi.authme.settings.NewSetting;
import fr.xephi.authme.settings.Settings;
import fr.xephi.authme.util.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
@ -21,11 +20,11 @@ import org.bukkit.entity.Player;
*/
public class AsyncRegister {
protected final Player player;
protected final String name;
protected final String password;
private final Player player;
private final String name;
private final String password;
private final String ip;
private String email = "";
private final String email;
private final AuthMe plugin;
private final DataSource database;
private final Messages m;
@ -88,7 +87,7 @@ public class AsyncRegister {
public void process() {
if (preRegisterCheck()) {
if (email != null && !email.isEmpty()) {
if (!StringUtils.isEmpty(email)) {
emailRegister();
} else {
passwordRegister();

View File

@ -1,6 +1,6 @@
package fr.xephi.authme.util;
import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip.LookupService;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.settings.Settings;
@ -9,18 +9,17 @@ import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.TimeUnit;
import java.util.zip.GZIPInputStream;
public class GeoLiteAPI {
private static final String LICENSE = "[LICENSE] This product includes GeoLite2 data created by MaxMind," +
" available from http://www.maxmind.com";
private static final String GEOIP_URL = "http://geolite.maxmind.com/download/geoip/database/GeoLite2-Country.mmdb.gz";
private static DatabaseReader databaseReader;
private static final String LICENSE =
"[LICENSE] This product uses data from the GeoLite API created by MaxMind, available at http://www.maxmind.com";
private static final String GEOIP_URL =
"http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz";
private static LookupService lookupService;
private static Thread downloadTask;
/**
@ -32,17 +31,17 @@ public class GeoLiteAPI {
if (downloadTask != null && downloadTask.isAlive()) {
return false;
}
if (databaseReader != null) {
if (lookupService != null) {
return true;
}
final File data = new File(Settings.PLUGIN_FOLDER, "GeoLite2-Country.mmdb");
final File data = new File(Settings.PLUGIN_FOLDER, "GeoIP.dat");
boolean dataIsOld = (System.currentTimeMillis() - data.lastModified()) > TimeUnit.DAYS.toMillis(30);
if (dataIsOld && !data.delete()) {
ConsoleLogger.showError("Failed to delete GeoLiteAPI database");
}
if (data.exists()) {
try {
databaseReader = new DatabaseReader.Builder(data).build();
lookupService = new LookupService(data);
ConsoleLogger.info(LICENSE);
return true;
} catch (IOException e) {
@ -90,11 +89,7 @@ public class GeoLiteAPI {
*/
public static String getCountryCode(String ip) {
if (!"127.0.0.1".equals(ip) && isDataAvailable()) {
try {
return databaseReader.country(InetAddress.getByName(ip)).getCountry().getIsoCode();
} catch (Exception e) {
ConsoleLogger.writeStackTrace(e);
}
return lookupService.getCountry(ip).getCode();
}
return "--";
}
@ -108,11 +103,7 @@ public class GeoLiteAPI {
*/
public static String getCountryName(String ip) {
if (!"127.0.0.1".equals(ip) && isDataAvailable()) {
try {
return databaseReader.country(InetAddress.getByName(ip)).getCountry().getName();
} catch (Exception e) {
ConsoleLogger.writeStackTrace(e);
}
return lookupService.getCountry(ip).getName();
}
return "N/A";
}

View File

@ -16,7 +16,7 @@ softdepend:
commands:
authme:
description: AuthMe op commands
usage: '/authme reload|register playername password|changepassword playername password|unregister playername|version'
usage: '/authme reload|register playername password|changepassword playername password|unregister playername|version|converter'
register:
description: Register an account
usage: /register <password> <confirmpassword>
@ -40,9 +40,6 @@ commands:
captcha:
description: Captcha command
usage: /captcha <code>
converter:
description: Converter from different other auth plugins
usage: /converter <datatype>
permissions:
authme.admin.*:
description: Give access to all admin commands.

View File

@ -50,7 +50,7 @@ public class CommandInitializerTest {
// 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.size(), equalTo(9));
assertThat(commands.size(), equalTo(8));
assertThat(commandsIncludeLabel(commands, "authme"), equalTo(true));
assertThat(commandsIncludeLabel(commands, "register"), equalTo(true));
assertThat(commandsIncludeLabel(commands, "help"), equalTo(false));

View File

@ -16,7 +16,6 @@ import java.util.List;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
@ -48,8 +47,8 @@ public class AccountsCommandTest {
// given
given(sender.getName()).willReturn("Tester");
List<String> arguments = Collections.EMPTY_LIST;
given(dataSource.getAuth("tester")).willReturn(mock(PlayerAuth.class));
given(dataSource.getAllAuthsByName(any(PlayerAuth.class))).willReturn(Arrays.asList("Toaster", "Pester"));
given(dataSource.getAuth("tester")).willReturn(authWithIp("123.45.67.89"));
given(dataSource.getAllAuthsByIp("123.45.67.89")).willReturn(Arrays.asList("Toaster", "Pester"));
// when
command.executeCommand(sender, arguments, service);
@ -81,7 +80,7 @@ public class AccountsCommandTest {
// given
List<String> arguments = Collections.singletonList("SomeUser");
given(dataSource.getAuth("someuser")).willReturn(mock(PlayerAuth.class));
given(dataSource.getAllAuthsByName(any(PlayerAuth.class))).willReturn(Collections.EMPTY_LIST);
given(dataSource.getAllAuthsByIp(anyString())).willReturn(Collections.EMPTY_LIST);
// when
command.executeCommand(sender, arguments, service);
@ -96,8 +95,8 @@ public class AccountsCommandTest {
public void shouldReturnSingleAccountMessage() {
// given
List<String> arguments = Collections.singletonList("SomeUser");
given(dataSource.getAuth("someuser")).willReturn(mock(PlayerAuth.class));
given(dataSource.getAllAuthsByName(any(PlayerAuth.class))).willReturn(Collections.singletonList("SomeUser"));
given(dataSource.getAuth("someuser")).willReturn(authWithIp("56.78.90.123"));
given(dataSource.getAllAuthsByIp("56.78.90.123")).willReturn(Collections.singletonList("SomeUser"));
// when
command.executeCommand(sender, arguments, service);
@ -169,4 +168,11 @@ public class AccountsCommandTest {
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")
.ip(ip)
.build();
}
}

View File

@ -1,6 +1,7 @@
package fr.xephi.authme.process.email;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLoggerTestInitializer;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.cache.auth.PlayerCache;
import fr.xephi.authme.datasource.DataSource;
@ -35,6 +36,7 @@ public class AsyncAddEmailTest {
@BeforeClass
public static void setUp() {
WrapperMock.createInstance();
ConsoleLoggerTestInitializer.setupLogger();
}
// Clean up the fields to ensure that no test uses elements of another test
@ -56,16 +58,38 @@ public class AsyncAddEmailTest {
given(auth.getEmail()).willReturn(null);
given(playerCache.getAuth("tester")).willReturn(auth);
given(dataSource.isEmailStored("my.mail@example.org")).willReturn(false);
given(dataSource.updateEmail(any(PlayerAuth.class))).willReturn(true);
// when
process.process();
// then
verify(dataSource).updateEmail(auth);
verify(messages).send(player, MessageKey.EMAIL_ADDED_SUCCESS);
verify(auth).setEmail("my.mail@example.org");
verify(playerCache).updatePlayer(auth);
}
@Test
public void shouldReturnErrorWhenMailCannotBeSaved() {
// given
AsyncAddEmail process = createProcess("my.mail@example.org");
given(player.getName()).willReturn("testEr");
given(playerCache.isAuthenticated("tester")).willReturn(true);
PlayerAuth auth = mock(PlayerAuth.class);
given(auth.getEmail()).willReturn(null);
given(playerCache.getAuth("tester")).willReturn(auth);
given(dataSource.isEmailStored("my.mail@example.org")).willReturn(false);
given(dataSource.updateEmail(any(PlayerAuth.class))).willReturn(false);
// when
process.process();
// then
verify(dataSource).updateEmail(auth);
verify(messages).send(player, MessageKey.ERROR);
}
@Test
public void shouldNotAddMailIfPlayerAlreadyHasEmail() {
// given

View File

@ -5,8 +5,7 @@ import fr.xephi.authme.settings.properties.TestConfiguration;
import fr.xephi.authme.settings.properties.TestEnum;
import org.bukkit.configuration.file.YamlConfiguration;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.mockito.internal.stubbing.answers.ReturnsArgumentAt;
import java.io.File;
@ -32,10 +31,10 @@ public class NewSettingTest {
public void shouldLoadAllConfigs() {
// given
YamlConfiguration configuration = mock(YamlConfiguration.class);
given(configuration.getString(anyString(), anyString())).willAnswer(withDefaultArgument());
given(configuration.getBoolean(anyString(), anyBoolean())).willAnswer(withDefaultArgument());
given(configuration.getDouble(anyString(), anyDouble())).willAnswer(withDefaultArgument());
given(configuration.getInt(anyString(), anyInt())).willAnswer(withDefaultArgument());
given(configuration.getString(anyString(), anyString())).willAnswer(new ReturnsArgumentAt(1));
given(configuration.getBoolean(anyString(), anyBoolean())).willAnswer(new ReturnsArgumentAt(1));
given(configuration.getDouble(anyString(), anyDouble())).willAnswer(new ReturnsArgumentAt(1));
given(configuration.getInt(anyString(), anyInt())).willAnswer(new ReturnsArgumentAt(1));
setReturnValue(configuration, TestConfiguration.VERSION_NUMBER, 20);
setReturnValue(configuration, TestConfiguration.SKIP_BORING_FEATURES, true);
@ -89,14 +88,4 @@ public class NewSettingTest {
setting.getProperty(property).equals(property.getDefaultValue()), equalTo(true));
}
private static <T> Answer<T> withDefaultArgument() {
return new Answer<T>() {
@Override
public T answer(InvocationOnMock invocation) throws Throwable {
// Return the second parameter -> the default
return (T) invocation.getArguments()[1];
}
};
}
}