Full mongodb support, along with #33

This commit is contained in:
samo_lego 2020-11-09 13:29:51 +01:00
parent 48dd9ce00b
commit 7d6d238def
6 changed files with 67 additions and 58 deletions

View File

@ -20,5 +20,5 @@ bcrypt_version = 0.9.0
bytes_version = 1.3.0 bytes_version = 1.3.0
# Carpet for debugging # Carpet for debugging
carpet_core_version = 1.4.0+v200623 carpet_core_version = 1.4.16+v201105
carpet_branch = master carpet_branch = master

View File

@ -67,19 +67,25 @@ public class AuthEventHandler {
return; return;
// Checking if session is still valid // Checking if session is still valid
String uuid = ((PlayerAuth) player).getFakeUuid(); String uuid = ((PlayerAuth) player).getFakeUuid();
PlayerCache playerCache = playerCacheMap.getOrDefault(uuid, null); PlayerCache playerCache;
if(!playerCacheMap.containsKey(uuid)) {
// First join
playerCache = PlayerCache.fromJson(player, uuid);
playerCacheMap.put(uuid, playerCache);
}
else {
playerCache = playerCacheMap.get(uuid);
}
if (playerCache != null) {
if ( if (
playerCache.isAuthenticated && playerCache.isAuthenticated &&
playerCache.validUntil >= System.currentTimeMillis() && playerCache.validUntil >= System.currentTimeMillis() &&
player.getIp().equals(playerCache.lastIp) player.getIp().equals(playerCache.lastIp)
) { ) {
// Valid session // Valid session
((PlayerAuth) player).setAuthenticated(true);
return; return;
} }
}
((PlayerAuth) player).setAuthenticated(false); ((PlayerAuth) player).setAuthenticated(false);
@ -113,10 +119,9 @@ public class AuthEventHandler {
if(config.main.sessionTimeoutTime != -1) if(config.main.sessionTimeoutTime != -1)
playerCache.validUntil = System.currentTimeMillis() + config.main.sessionTimeoutTime * 1000; playerCache.validUntil = System.currentTimeMillis() + config.main.sessionTimeoutTime * 1000;
} }
else { else if(config.main.spawnOnJoin)
((PlayerAuth) player).hidePosition(false); ((PlayerAuth) player).hidePosition(false);
} }
}
// Player chatting // Player chatting
public static ActionResult onPlayerChat(PlayerEntity player, ChatMessageC2SPacket chatMessageC2SPacket) { public static ActionResult onPlayerChat(PlayerEntity player, ChatMessageC2SPacket chatMessageC2SPacket) {

View File

@ -46,10 +46,8 @@ public class MixinServerPlayerEntity implements PlayerAuth {
*/ */
@Override @Override
public void hidePosition(boolean hide) { public void hidePosition(boolean hide) {
assert server != null;
PlayerCache cache = playerCacheMap.get(this.getFakeUuid()); PlayerCache cache = playerCacheMap.get(this.getFakeUuid());
if(config.main.spawnOnJoin) if(config.experimental.debugMode)
logInfo("Teleporting " + player.getName().asString() + (hide ? " to spawn." : " to original position.")); logInfo("Teleporting " + player.getName().asString() + (hide ? " to spawn." : " to original position."));
if (hide) { if (hide) {
// Saving position // Saving position
@ -110,19 +108,11 @@ public class MixinServerPlayerEntity implements PlayerAuth {
*/ */
@Override @Override
public void setAuthenticated(boolean authenticated) { public void setAuthenticated(boolean authenticated) {
PlayerCache playerCache; PlayerCache playerCache = playerCacheMap.get(this.getFakeUuid());
if(!playerCacheMap.containsKey(this.getFakeUuid())) {
// First join
playerCache = PlayerCache.fromJson(player, this.getFakeUuid());
playerCacheMap.put(this.getFakeUuid(), playerCache);
}
else {
playerCache = playerCacheMap.get(this.getFakeUuid());
if(this.isAuthenticated() == authenticated) if(this.isAuthenticated() == authenticated)
return; return;
playerCache.isAuthenticated = authenticated; playerCache.isAuthenticated = authenticated;
}
player.setInvulnerable(!authenticated && config.experimental.playerInvulnerable); player.setInvulnerable(!authenticated && config.experimental.playerInvulnerable);
player.setInvisible(!authenticated && config.experimental.playerInvisible); player.setInvisible(!authenticated && config.experimental.playerInvisible);

View File

@ -30,6 +30,7 @@ import static org.samo_lego.simpleauth.utils.SimpleLogger.logInfo;
public class AuthConfig { public class AuthConfig {
private static final Gson gson = new GsonBuilder() private static final Gson gson = new GsonBuilder()
.setPrettyPrinting() .setPrettyPrinting()
.serializeNulls()
.create(); .create();
// If player is not authenticated, following conditions apply // If player is not authenticated, following conditions apply
@ -112,15 +113,15 @@ public class AuthConfig {
public static class MongoDBCredentials { public static class MongoDBCredentials {
/** /**
* Credentials for MongoDB database. * Credentials for MongoDB database.
* Leave this as-is if you are using LevelDB or don't need * Leave this as-is if you are using LevelDB.
* special credentials.
*/ */
public String username = "";
public String password = "";
public String host = "localhost"; public String host = "localhost";
public int port = 27017; public int port = 27017;
public String simpleAuthDatabase = "SimpleAuthPlayerData";
public String userSourceDatabase = "";
public boolean useSsl = true; public boolean useSsl = true;
public String databaseName = "SimpleAuthPlayerData";
public String password = "";
public String username = "";
} }
} }

View File

@ -3,6 +3,7 @@ package org.samo_lego.simpleauth.storage;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import com.google.gson.annotations.Expose; import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import net.minecraft.block.Blocks; import net.minecraft.block.Blocks;
import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.server.world.ServerWorld; import net.minecraft.server.world.ServerWorld;
@ -23,6 +24,7 @@ public class PlayerCache {
* Used for {@link org.samo_lego.simpleauth.event.AuthEventHandler#onPlayerJoin(ServerPlayerEntity) session validation}. * Used for {@link org.samo_lego.simpleauth.event.AuthEventHandler#onPlayerJoin(ServerPlayerEntity) session validation}.
*/ */
@Expose @Expose
@SerializedName("is_authenticated")
public boolean isAuthenticated = false; public boolean isAuthenticated = false;
/** /**
* Hashed password of player. * Hashed password of player.
@ -38,11 +40,13 @@ public class PlayerCache {
* Used for {@link org.samo_lego.simpleauth.event.AuthEventHandler#onPlayerJoin(ServerPlayerEntity) sessions}. * Used for {@link org.samo_lego.simpleauth.event.AuthEventHandler#onPlayerJoin(ServerPlayerEntity) sessions}.
*/ */
@Expose @Expose
@SerializedName("last_ip")
public String lastIp; public String lastIp;
/** /**
* Time until session is valid. * Time until session is valid.
*/ */
@Expose @Expose
@SerializedName("valid_until")
public long validUntil; public long validUntil;
/** /**
@ -72,30 +76,23 @@ public class PlayerCache {
* *
* @param player player to create cache for * @param player player to create cache for
*/ */
public PlayerCache(ServerPlayerEntity player) {
if(player != null) {
this.lastIp = player.getIp();
// Setting position cache
this.lastLocation.dimension = player.getServerWorld();
this.lastLocation.position = player.getPos();
this.lastLocation.yaw = player.yaw;
this.lastLocation.pitch = player.pitch;
this.wasInPortal = player.getBlockState().getBlock().equals(Blocks.NETHER_PORTAL);
}
}
public static PlayerCache fromJson(ServerPlayerEntity player, String fakeUuid) { public static PlayerCache fromJson(ServerPlayerEntity player, String fakeUuid) {
if(config.experimental.debugMode) if(config.experimental.debugMode)
logInfo("Creating cache for " + Objects.requireNonNull(player).getGameProfile().getName()); logInfo("Creating cache for " + Objects.requireNonNull(player).getGameProfile().getName());
PlayerCache playerCache = new PlayerCache(player);;
String json = DB.getUserData(fakeUuid); String json = DB.getUserData(fakeUuid);
if(!json.isEmpty()) {
// Parsing data from DB // Parsing data from DB
playerCache = gson.fromJson(json, PlayerCache.class); PlayerCache playerCache = gson.fromJson(json, PlayerCache.class);
if(player != null) {
// Setting position cache
playerCache.lastLocation.dimension = player.getServerWorld();
playerCache.lastLocation.position = player.getPos();
playerCache.lastLocation.yaw = player.yaw;
playerCache.lastLocation.pitch = player.pitch;
playerCache.wasInPortal = player.getBlockState().getBlock().equals(Blocks.NETHER_PORTAL);
} }
return playerCache; return playerCache;

View File

@ -22,20 +22,33 @@ public class MongoDB {
private static MongoClient mongoClient; private static MongoClient mongoClient;
public static void initialize() { public static void initialize() {
/*mongoClient = MongoClients.create(
/*MongoCredential credential = MongoCredential.createCredential(
config.mongoDBCredentials.username,
config.mongoDBCredentials.userSourceDatabase,
config.mongoDBCredentials.password.toCharArray()
);
mongoClient = MongoClients.create(
MongoClientSettings.builder()
.applyToClusterSettings(builder ->
builder.hosts(Collections.singletonList(new ServerAddress(config.mongoDBCredentials.host, config.mongoDBCredentials.port))))
.applyToSslSettings(builder -> builder.enabled(config.mongoDBCredentials.useSsl))
.credential(credential)
.build());*/
mongoClient = MongoClients.create(
String.format( String.format(
"mongodb://%s:%s@%s:%s/?authSource=db1&ssl=%s", "mongodb://%s:%s@%s:%d/?authSource=%s&useSsl=%b",
config.mongoDBCredentials.username, config.mongoDBCredentials.username,
config.mongoDBCredentials.password, config.mongoDBCredentials.password,
config.mongoDBCredentials.host, config.mongoDBCredentials.host,
config.mongoDBCredentials.port, config.mongoDBCredentials.port,
config.mongoDBCredentials.userSourceDatabase,
config.mongoDBCredentials.useSsl config.mongoDBCredentials.useSsl
) )
playerCache.wasOnFire = false; );
);*/ //mongoClient = MongoClients.create(String.format("mongodb://%s:%d", config.mongoDBCredentials.host, config.mongoDBCredentials.port));
mongoClient = MongoClients.create(String.format("mongodb://%s:%d", config.mongoDBCredentials.host, config.mongoDBCredentials.port)); MongoDatabase database = mongoClient.getDatabase(config.mongoDBCredentials.simpleAuthDatabase);
MongoDatabase database = mongoClient.getDatabase(config.mongoDBCredentials.databaseName);
collection = database.getCollection("players"); collection = database.getCollection("players");
} }
@ -71,6 +84,9 @@ public class MongoDB {
updateList.add(new ReplaceOneModel<>(eq("UUID", uuid), updateList.add(new ReplaceOneModel<>(eq("UUID", uuid),
new Document("UUID", uuid) new Document("UUID", uuid)
.append("password", playerCache.password) .append("password", playerCache.password)
.append("is_authenticated", playerCache.isAuthenticated)
.append("last_ip", playerCache.lastIp)
.append("valid_until", playerCache.validUntil)
) )
); );
} }