Skip to content

Commit

Permalink
Remove IP addresses from game tokens and matchmaking
Browse files Browse the repository at this point in the history
  • Loading branch information
sudokoko committed Mar 18, 2024
1 parent a9944ec commit 5283001
Show file tree
Hide file tree
Showing 13 changed files with 44 additions and 73 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ public async Task<IActionResult> Login()
switch (npTicket.Platform)
{
case Platform.RPCS3:
user = await this.database.Users.FirstOrDefaultAsync(u => u.LinkedRpcnId == npTicket.UserId);
user = await this.database.Users.FirstOrDefaultAsync(u => u.LinkedRpcnId == npTicket.UserId);
break;
case Platform.PS3:
case Platform.Vita:
Expand All @@ -88,7 +88,7 @@ public async Task<IActionResult> Login()
// If this user id hasn't been linked to any accounts
if (user == null)
{
// Check if there is an account with that username already
// Check if there is an account with that username already
UserEntity? targetUsername = await this.database.Users.FirstOrDefaultAsync(u => u.Username == npTicket.Username);
if (targetUsername != null)
{
Expand Down Expand Up @@ -175,7 +175,7 @@ public async Task<IActionResult> Login()
}

GameTokenEntity? token = await this.database.GameTokens.Include(t => t.User)
.FirstOrDefaultAsync(t => t.UserLocation == ipAddress && t.User.Username == npTicket.Username && t.TicketHash == npTicket.TicketHash);
.FirstOrDefaultAsync(t => t.User.Username == npTicket.Username && t.TicketHash == npTicket.TicketHash);

if (token != null)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,27 +87,20 @@ public async Task<IActionResult> Match()
{
case UpdateMyPlayerData playerData:
{
MatchHelper.SetUserLocation(user.UserId, token.UserLocation);
Room? room = RoomHelper.FindRoomByUser(user.UserId, token.GameVersion, token.Platform, true);

if (playerData.RoomState != null)
if (room != null && Equals(room.HostId, user.UserId))
room.State = (RoomState)playerData.RoomState;
break;
}
// Check how many people are online in release builds, disabled for debug for ..well debugging.
#if DEBUG
case FindBestRoom diveInData:
#else
case FindBestRoom diveInData when MatchHelper.UserLocations.Count > 1:
#endif
{
FindBestRoomResponse? response = RoomHelper.FindBestRoom(this.database,
user,
token.GameVersion,
diveInData.RoomSlot,
token.Platform,
token.UserLocation);
token.Platform);

if (response == null) return this.NotFound();

Expand All @@ -117,7 +110,7 @@ public async Task<IActionResult> Match()

return this.Ok($"[{{\"StatusCode\":200}},{serialized}]");
}
case CreateRoom createRoom when !MatchHelper.UserLocations.IsEmpty:
case CreateRoom createRoom:
{
List<int> users = new();
foreach (string playerUsername in createRoom.Players)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,6 @@ public async Task<IActionResult> Announce()
#if DEBUG
announceText.Append("\n\n---DEBUG INFO---\n" +
$"user.UserId: {token.UserId}\n" +
$"token.UserLocation: {token.UserLocation}\n" +
$"token.GameVersion: {token.GameVersion}\n" +
$"token.TicketHash: {token.TicketHash}\n" +
$"token.ExpiresAt: {token.ExpiresAt.ToString()}\n" +
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
using LBPUnion.ProjectLighthouse.Database;
using LBPUnion.ProjectLighthouse.Helpers;
using LBPUnion.ProjectLighthouse.Types.Users;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace LBPUnion.ProjectLighthouse.Servers.Website.Controllers.Debug;

Expand All @@ -27,10 +24,6 @@ public async Task<IActionResult> CreateFakeRoom()
List<int> users = await this.database.Users.OrderByDescending(_ => EF.Functions.Random()).Take(2).Select(u => u.UserId).ToListAsync();
RoomHelper.CreateRoom(users, GameVersion.LittleBigPlanet2, Platform.PS3);

foreach (int user in users)
{
MatchHelper.SetUserLocation(user, "127.0.0.1");
}
return this.Redirect("/debug/roomVisualizer");
#endif
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,15 @@

<script>
let shouldRefresh = true;
setTimeout(() => {
if (shouldRefresh) window.location.reload();
}, @(refreshSeconds * 1000));
function stopRefreshing() {
shouldRefresh = false;
console.log("Stopped refresh");
const stopRefreshButton = document.getElementById("stop-refresh-button");
stopRefreshButton.parentElement.removeChild(stopRefreshButton);
console.log("Removed stop refresh button");
Expand Down Expand Up @@ -61,7 +61,7 @@
#nullable enable
if (version == GameVersion.LittleBigPlanet1 || version == GameVersion.LittleBigPlanetPSP || version == GameVersion.Unknown) continue;

FindBestRoomResponse? response = RoomHelper.FindBestRoom(Database, null, version, null, null, null);
FindBestRoomResponse? response = RoomHelper.FindBestRoom(Database, null, version, null, null);
string text = response == null ? "No room found." : "Room " + response.RoomId;

<p><b>Best room for @version.ToPrettyString()</b>: @text</p>
Expand Down
1 change: 0 additions & 1 deletion ProjectLighthouse.Tests/Helpers/MockHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ public static GameTokenEntity GetUnitTestToken() =>
UserId = 1,
ExpiresAt = DateTime.MaxValue,
TokenId = 1,
UserLocation = "127.0.0.1",
UserToken = "unittest",
};

Expand Down
1 change: 0 additions & 1 deletion ProjectLighthouse/Database/DatabaseContext.Utils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,6 @@ public async Task<int> UserIdFromUsername(string? username)
UserToken = CryptoHelper.GenerateAuthToken(),
User = user,
UserId = user.UserId,
UserLocation = userLocation,
GameVersion = npTicket.GameVersion,
Platform = npTicket.Platform,
TicketHash = npTicket.TicketHash,
Expand Down
7 changes: 0 additions & 7 deletions ProjectLighthouse/Helpers/MatchHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,8 @@ namespace LBPUnion.ProjectLighthouse.Helpers;

public static partial class MatchHelper
{
public static readonly ConcurrentDictionary<int, string?> UserLocations = new();
public static readonly ConcurrentDictionary<int, List<int>?> UserRecentlyDivedIn = new();

public static void SetUserLocation(int userId, string location)
{
if (UserLocations.TryGetValue(userId, out string? _)) UserLocations.TryRemove(userId, out _);
UserLocations.TryAdd(userId, location);
}

public static void AddUserRecentlyDivedIn(int userId, int otherUserId)
{
if (!UserRecentlyDivedIn.TryGetValue(userId, out List<int>? recentlyDivedIn)) UserRecentlyDivedIn.TryAdd(userId, recentlyDivedIn = new List<int>());
Expand Down
33 changes: 4 additions & 29 deletions ProjectLighthouse/Helpers/RoomHelper.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
#nullable enable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading.Tasks;
Expand All @@ -27,7 +26,7 @@ public static class RoomHelper
private static int roomIdIncrement;
internal static int RoomIdIncrement => roomIdIncrement++;

public static FindBestRoomResponse? FindBestRoom(DatabaseContext database, UserEntity? user, GameVersion roomVersion, RoomSlot? slot, Platform? platform, string? location)
public static FindBestRoomResponse? FindBestRoom(DatabaseContext database, UserEntity? user, GameVersion roomVersion, RoomSlot? slot, Platform? platform)
{
if (roomVersion == GameVersion.LittleBigPlanet1 || roomVersion == GameVersion.LittleBigPlanetPSP)
{
Expand Down Expand Up @@ -61,30 +60,10 @@ public static class RoomHelper
{
if (user != null && MatchHelper.DidUserRecentlyDiveInWith(user.UserId, room.HostId)) continue;

Dictionary<int, string> relevantUserLocations = new();

// Determine if all players in a room have UserLocations stored, also store the relevant userlocations while we're at it
bool allPlayersHaveLocations = room.PlayerIds.All
(
p =>
{
bool gotValue = MatchHelper.UserLocations.TryGetValue(p, out string? value);

if (gotValue && value != null) relevantUserLocations.TryAdd(p, value);
return gotValue;
}
);

// If we don't have all locations then the game won't know how to communicate. Thus, it's not a valid room.
if (!allPlayersHaveLocations) continue;

// If we got here then it should be a valid room.

FindBestRoomResponse response = new()
{
RoomId = room.RoomId,
Players = new List<Player>(),
Locations = new List<string>(),
};

foreach (UserEntity player in room.GetPlayers(database))
Expand All @@ -97,8 +76,6 @@ public static class RoomHelper
User = player,
}
);

response.Locations.Add(relevantUserLocations.GetValueOrDefault(player.UserId)); // Already validated to exist
}

if (user != null)
Expand All @@ -111,8 +88,6 @@ public static class RoomHelper
}
);

if (location == null) response.Locations.Add(location);

response.Slots = new List<List<int>>
{
new()
Expand Down Expand Up @@ -189,7 +164,7 @@ public static Task CleanupRooms(DatabaseContext database, int? hostId = null, Ro
{
StorableList<Room> rooms = Rooms; // cache rooms so we dont gen a new one every time
List<Room> roomsToUpdate = new();

#if DEBUG
Logger.Debug($"Cleaning up rooms... (took {stopwatch.ElapsedMilliseconds}ms to get lock on {nameof(RoomLock)})", LogArea.Match);
#endif
Expand All @@ -205,7 +180,7 @@ public static Task CleanupRooms(DatabaseContext database, int? hostId = null, Ro
.ToList();

foreach (int player in playersToRemove) room.PlayerIds.Remove(player);

roomsToUpdate.Add(room);
}

Expand Down Expand Up @@ -248,7 +223,7 @@ public static Task CleanupRooms(DatabaseContext database, int? hostId = null, Ro
int roomCountAfterCleanup = rooms.Count();

// Log the amount of rooms cleaned up.
// If we didnt clean any rooms, it's not useful to log in a
// If we didnt clean any rooms, it's not useful to log in a
// production environment but it's still quite useful for debugging.
//
// So, we handle that case here:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using LBPUnion.ProjectLighthouse.Database;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace LBPUnion.ProjectLighthouse.Migrations
{
[DbContext(typeof(DatabaseContext))]
[Migration("20240317231145_RemoveUserLocationFromGameTokens")]
public partial class RemoveUserLocationFromGameTokens : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "UserLocation",
table: "GameTokens");
}

protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "UserLocation",
table: "GameTokens",
type: "longtext",
nullable: true)
.Annotation("MySql:CharSet", "utf8mb4");
}
}
}
5 changes: 1 addition & 4 deletions ProjectLighthouse/Migrations/DatabaseContextModelSnapshot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.13")
.HasAnnotation("ProductVersion", "8.0.2")
.HasAnnotation("Relational:MaxIdentifierLength", 64);

modelBuilder.Entity("LBPUnion.ProjectLighthouse.Types.Entities.Interaction.HeartedLevelEntity", b =>
Expand Down Expand Up @@ -995,9 +995,6 @@ protected override void BuildModel(ModelBuilder modelBuilder)
b.Property<int>("UserId")
.HasColumnType("int");

b.Property<string>("UserLocation")
.HasColumnType("longtext");

b.Property<string>("UserToken")
.HasColumnType("longtext");

Expand Down
2 changes: 0 additions & 2 deletions ProjectLighthouse/Types/Entities/Token/GameTokenEntity.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@ public class GameTokenEntity

public string UserToken { get; set; }

public string UserLocation { get; set; }

public GameVersion GameVersion { get; set; }

public Platform Platform { get; set; }
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json.Serialization;

namespace LBPUnion.ProjectLighthouse.Types.Matchmaking.Rooms;
Expand All @@ -14,8 +13,4 @@ public class FindBestRoomResponse

[JsonIgnore]
public IEnumerable<int> FirstSlot => this.Slots[0];

[JsonPropertyName("Location")]
[SuppressMessage("ReSharper", "CollectionNeverQueried.Global")]
public List<string> Locations { get; set; }
}

0 comments on commit 5283001

Please sign in to comment.