Authentication Service

This commit is contained in:
dingo
2025-11-10 09:01:46 -05:00
parent 72bc097a71
commit a45cc41f4a
16 changed files with 1016 additions and 23 deletions
+478
View File
@@ -0,0 +1,478 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Server.Data;
#nullable disable
namespace SystemRevivalServer.Migrations
{
[DbContext(typeof(GameDbContext))]
[Migration("20251110131236_UpdateSessions")]
partial class UpdateSessions
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "9.0.10")
.HasAnnotation("Relational:MaxIdentifierLength", 64);
MySqlModelBuilderExtensions.AutoIncrementColumns(modelBuilder);
modelBuilder.Entity("Server.Data.Account", b =>
{
b.Property<ulong>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint unsigned");
MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property<ulong>("Id"));
b.Property<DateTime?>("BannedUntil")
.HasColumnType("datetime(6)");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
b.Property<string>("Email")
.HasMaxLength(255)
.HasColumnType("varchar(255)");
b.Property<bool>("IsBanned")
.HasColumnType("tinyint(1)");
b.Property<byte[]>("PasswordHash")
.IsRequired()
.HasColumnType("varbinary(64)");
b.Property<byte[]>("PasswordSalt")
.IsRequired()
.HasColumnType("varbinary(32)");
b.Property<DateTime>("UpdatedAt")
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property<DateTime>("UpdatedAt"));
b.Property<string>("Username")
.IsRequired()
.HasMaxLength(32)
.HasColumnType("varchar(32)");
b.HasKey("Id");
b.HasIndex("Email")
.IsUnique();
b.HasIndex("Username")
.IsUnique();
b.ToTable("accounts", (string)null);
});
modelBuilder.Entity("Server.Data.Character", b =>
{
b.Property<ulong>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint unsigned");
MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property<ulong>("Id"));
b.Property<ulong>("AccountId")
.HasColumnType("bigint unsigned");
b.Property<string>("AppearanceJson")
.HasColumnType("json");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
b.Property<float>("FacingDeg")
.HasColumnType("float");
b.Property<uint>("HpCurrent")
.HasColumnType("int unsigned");
b.Property<uint>("HpMax")
.HasColumnType("int unsigned");
b.Property<uint>("Level")
.HasColumnType("int unsigned");
b.Property<uint>("MpCurrent")
.HasColumnType("int unsigned");
b.Property<uint>("MpMax")
.HasColumnType("int unsigned");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(32)
.HasColumnType("varchar(32)");
b.Property<double>("PosX")
.HasColumnType("double");
b.Property<double>("PosY")
.HasColumnType("double");
b.Property<double>("PosZ")
.HasColumnType("double");
b.Property<uint>("StaminaCurrent")
.HasColumnType("int unsigned");
b.Property<uint>("StaminaMax")
.HasColumnType("int unsigned");
b.Property<uint>("StatDexterity")
.HasColumnType("int unsigned");
b.Property<uint>("StatEndurance")
.HasColumnType("int unsigned");
b.Property<uint>("StatIntelligence")
.HasColumnType("int unsigned");
b.Property<uint>("StatStrength")
.HasColumnType("int unsigned");
b.Property<uint>("StatWisdom")
.HasColumnType("int unsigned");
b.Property<DateTime>("UpdatedAt")
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property<DateTime>("UpdatedAt"));
b.Property<ulong>("Xp")
.HasColumnType("bigint unsigned");
b.Property<ulong>("ZoneId")
.HasColumnType("bigint unsigned");
b.HasKey("Id");
b.HasIndex("AccountId")
.IsUnique();
b.HasIndex("ZoneId");
b.ToTable("characters", (string)null);
});
modelBuilder.Entity("Server.Data.EquipmentSlot", b =>
{
b.Property<ulong>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint unsigned");
MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property<ulong>("Id"));
b.Property<ulong>("CharacterId")
.HasColumnType("bigint unsigned");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
b.Property<ulong>("ItemTemplateId")
.HasColumnType("bigint unsigned");
b.Property<byte>("SlotCode")
.HasColumnType("tinyint unsigned");
b.Property<DateTime>("UpdatedAt")
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property<DateTime>("UpdatedAt"));
b.HasKey("Id");
b.HasIndex("ItemTemplateId");
b.HasIndex("CharacterId", "SlotCode")
.IsUnique();
b.ToTable("equipment", (string)null);
});
modelBuilder.Entity("Server.Data.InventoryItem", b =>
{
b.Property<ulong>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint unsigned");
MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property<ulong>("Id"));
b.Property<ulong>("CharacterId")
.HasColumnType("bigint unsigned");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
b.Property<ulong>("ItemTemplateId")
.HasColumnType("bigint unsigned");
b.Property<uint>("Quantity")
.HasColumnType("int unsigned");
b.Property<uint>("SlotIndex")
.HasColumnType("int unsigned");
b.Property<DateTime>("UpdatedAt")
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property<DateTime>("UpdatedAt"));
b.HasKey("Id");
b.HasIndex("CharacterId");
b.HasIndex("ItemTemplateId");
b.HasIndex("CharacterId", "SlotIndex")
.IsUnique();
b.ToTable("inventories", (string)null);
});
modelBuilder.Entity("Server.Data.ItemTemplate", b =>
{
b.Property<ulong>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint unsigned");
MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property<ulong>("Id"));
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
b.Property<byte>("ItemType")
.HasColumnType("tinyint unsigned");
b.Property<uint>("MaxStack")
.HasColumnType("int unsigned");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("varchar(64)");
b.Property<byte>("Rarity")
.HasColumnType("tinyint unsigned");
b.Property<string>("StatsJson")
.HasColumnType("json");
b.Property<DateTime>("UpdatedAt")
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property<DateTime>("UpdatedAt"));
b.Property<uint>("Weight")
.HasColumnType("int unsigned");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("item_templates", (string)null);
});
modelBuilder.Entity("Server.Data.Session", b =>
{
b.Property<ulong>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint unsigned");
MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property<ulong>("Id"));
b.Property<ulong>("AccountId")
.HasColumnType("bigint unsigned");
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
b.Property<string>("CreatedIp")
.HasMaxLength(64)
.HasColumnType("varchar(64)");
b.Property<DateTime>("ExpiresAt")
.HasColumnType("datetime(6)");
b.Property<string>("TokenHash")
.IsRequired()
.HasMaxLength(128)
.HasColumnType("varchar(128)");
b.Property<string>("UserAgent")
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.HasKey("Id");
b.HasIndex("AccountId");
b.HasIndex("TokenHash")
.IsUnique();
b.ToTable("sessions", (string)null);
});
modelBuilder.Entity("Server.Data.Zone", b =>
{
b.Property<ulong>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint unsigned");
MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property<ulong>("Id"));
b.Property<DateTime>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
b.Property<double>("MaxX")
.HasColumnType("double");
b.Property<double>("MaxY")
.HasColumnType("double");
b.Property<double>("MaxZ")
.HasColumnType("double");
b.Property<double>("MinX")
.HasColumnType("double");
b.Property<double>("MinY")
.HasColumnType("double");
b.Property<double>("MinZ")
.HasColumnType("double");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("varchar(64)");
b.Property<DateTime>("UpdatedAt")
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property<DateTime>("UpdatedAt"));
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.ToTable("zones", (string)null);
});
modelBuilder.Entity("Server.Data.Character", b =>
{
b.HasOne("Server.Data.Account", "Account")
.WithMany("Characters")
.HasForeignKey("AccountId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Server.Data.Zone", "Zone")
.WithMany()
.HasForeignKey("ZoneId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Account");
b.Navigation("Zone");
});
modelBuilder.Entity("Server.Data.EquipmentSlot", b =>
{
b.HasOne("Server.Data.Character", "Character")
.WithMany()
.HasForeignKey("CharacterId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Server.Data.ItemTemplate", "ItemTemplate")
.WithMany()
.HasForeignKey("ItemTemplateId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Character");
b.Navigation("ItemTemplate");
});
modelBuilder.Entity("Server.Data.InventoryItem", b =>
{
b.HasOne("Server.Data.Character", "Character")
.WithMany()
.HasForeignKey("CharacterId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Server.Data.ItemTemplate", "ItemTemplate")
.WithMany()
.HasForeignKey("ItemTemplateId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Character");
b.Navigation("ItemTemplate");
});
modelBuilder.Entity("Server.Data.Session", b =>
{
b.HasOne("Server.Data.Account", "Account")
.WithMany("Sessions")
.HasForeignKey("AccountId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Account");
});
modelBuilder.Entity("Server.Data.Account", b =>
{
b.Navigation("Characters");
b.Navigation("Sessions");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,88 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SystemRevivalServer.Migrations
{
/// <inheritdoc />
public partial class UpdateSessions : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_sessions_Token",
table: "sessions");
migrationBuilder.DropColumn(
name: "Token",
table: "sessions");
migrationBuilder.AddColumn<string>(
name: "CreatedIp",
table: "sessions",
type: "varchar(64)",
maxLength: 64,
nullable: true)
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.AddColumn<string>(
name: "TokenHash",
table: "sessions",
type: "varchar(128)",
maxLength: 128,
nullable: false,
defaultValue: "")
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.AddColumn<string>(
name: "UserAgent",
table: "sessions",
type: "varchar(256)",
maxLength: 256,
nullable: true)
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.CreateIndex(
name: "IX_sessions_TokenHash",
table: "sessions",
column: "TokenHash",
unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_sessions_TokenHash",
table: "sessions");
migrationBuilder.DropColumn(
name: "CreatedIp",
table: "sessions");
migrationBuilder.DropColumn(
name: "TokenHash",
table: "sessions");
migrationBuilder.DropColumn(
name: "UserAgent",
table: "sessions");
migrationBuilder.AddColumn<string>(
name: "Token",
table: "sessions",
type: "varchar(64)",
maxLength: 64,
nullable: false,
defaultValue: "")
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.CreateIndex(
name: "IX_sessions_Token",
table: "sessions",
column: "Token",
unique: true);
}
}
}
+12 -4
View File
@@ -318,19 +318,27 @@ namespace SystemRevivalServer.Migrations
.HasColumnType("datetime(6)")
.HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
b.Property<string>("CreatedIp")
.HasMaxLength(64)
.HasColumnType("varchar(64)");
b.Property<DateTime>("ExpiresAt")
.HasColumnType("datetime(6)");
b.Property<string>("Token")
b.Property<string>("TokenHash")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("varchar(64)");
.HasMaxLength(128)
.HasColumnType("varchar(128)");
b.Property<string>("UserAgent")
.HasMaxLength(256)
.HasColumnType("varchar(256)");
b.HasKey("Id");
b.HasIndex("AccountId");
b.HasIndex("Token")
b.HasIndex("TokenHash")
.IsUnique();
b.ToTable("sessions", (string)null);
+87 -10
View File
@@ -1,17 +1,26 @@
using System;
// Networking/MessageRouter.cs
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Server.Networking.Messages;
using Server.Services.Auth;
namespace Server.Networking;
public sealed class MessageRouter
{
private readonly ILogger<MessageRouter> _logger;
private readonly IAuthService _auth;
private readonly ISessionRegistry _sessions;
private readonly IMessageSerializer _serializer = new JsonSerializerAdapter();
public MessageRouter(ILogger<MessageRouter> logger) => _logger = logger;
public MessageRouter(ILogger<MessageRouter> logger, IAuthService auth, ISessionRegistry sessions)
{
_logger = logger;
_auth = auth;
_sessions = sessions;
}
public async Task OnMessageAsync(IConnection connection, ReadOnlyMemory<byte> data, CancellationToken cancellationToken)
{
@@ -19,20 +28,88 @@ public sealed class MessageRouter
switch (clientMessage.OpCode)
{
case 1: // Hello / Echo
_logger.LogDebug("HELLO from {ConnectionId}", connection.Id);
await SendAsync(connection, new ServerMessage(1, clientMessage.Payload), cancellationToken);
break;
case OpCodes.ECHO:
_logger.LogDebug("ECHO from {ConnectionId}", connection.Id);
await ReplyAsync(connection, OpCodes.ECHO, clientMessage.Payload, cancellationToken);
return;
case OpCodes.AUTH_REGISTER:
{
var req = _serializer.Deserialize<AuthRegisterRequest>(clientMessage.Payload);
var (ok, error) = await _auth.RegisterAsync(req.Username, req.Password, req.Email, cancellationToken);
string? msg = error switch
{
"invalid_username" => "Username must be 3–32 characters.",
"weak_password" => "Password must be at least 8 characters.",
"username_taken" => "That username is already in use.",
"email_taken" => "That email is already registered.",
_ => null
};
await ReplyObjectAsync(connection, OpCodes.AUTH_REGISTER_RESULT,
new AuthRegisterResponse(ok, error, msg), cancellationToken);
return;
}
case OpCodes.AUTH_LOGIN:
{
var req = _serializer.Deserialize<AuthLoginRequest>(clientMessage.Payload);
var ip = connection.RemoteEndPoint?.ToString();
var ua = "gameclient";
var (ok, error, token, accountId) = await _auth.LoginAsync(req.UsernameOrEmail, req.Password, ip, ua, TimeSpan.FromHours(24), cancellationToken);
// Optionally fetch ban-until if banned (extend AuthService to return it directly if you prefer)
DateTime? bannedUntil = null;
if (ok) _sessions.Bind(connection.Id, accountId, token!);
await ReplyObjectAsync(connection, OpCodes.AUTH_LOGIN_RESULT,
new AuthLoginResponse(ok, error, token, accountId, bannedUntil), cancellationToken);
return;
}
case OpCodes.AUTH_WITH_TOKEN:
{
var req = _serializer.Deserialize<AuthWithTokenRequest>(clientMessage.Payload);
var (ok, error, accountId) = await _auth.ValidateTokenAsync(req.Token, cancellationToken);
if (ok) _sessions.Bind(connection.Id, accountId, req.Token);
await ReplyObjectAsync(connection, OpCodes.AUTH_WITH_TOKEN_RESULT,
new AuthWithTokenResponse(ok, error, accountId), cancellationToken);
return;
}
default:
// Gate all other opcodes behind auth
if (!_sessions.IsAuthenticated(connection.Id))
{
// Either ignore or send a standard error
await ReplyErrorAsync(connection, "auth_required", cancellationToken);
_logger.LogWarning("Unauthenticated message opcode={Op} from {Conn}", clientMessage.OpCode, connection.Id);
return;
}
_logger.LogWarning("Unknown opcode {OpCode} from {ConnectionId}", clientMessage.OpCode, connection.Id);
break;
return;
}
}
public Task SendAsync(IConnection connection, ServerMessage message, CancellationToken cancellationToken)
// Helpers
private Task ReplyAsync(IConnection connection, int opCode, byte[] payloadBytes, CancellationToken ct)
{
var bytes = _serializer.Serialize(message);
return connection.SendAsync(bytes, cancellationToken).AsTask();
var msg = new ServerMessage(opCode, payloadBytes);
var wire = _serializer.Serialize(msg);
return connection.SendAsync(wire, ct).AsTask();
}
private Task ReplyObjectAsync<T>(IConnection connection, int opCode, T obj, CancellationToken ct)
{
var payload = _serializer.Serialize(obj);
return ReplyAsync(connection, opCode, payload, ct);
}
private Task ReplyErrorAsync(IConnection connection, string code, CancellationToken ct)
=> ReplyObjectAsync(connection, OpCodes.ERROR, new { error = code }, ct);
}
+10
View File
@@ -0,0 +1,10 @@
namespace Server.Networking.Messages;
public sealed record AuthRegisterRequest(string Username, string Password, string? Email);
public sealed record AuthRegisterResponse(bool Ok, string? Error, string? Message);
public sealed record AuthLoginRequest(string UsernameOrEmail, string Password);
public sealed record AuthLoginResponse(bool Ok, string? Error, string? Token, ulong AccountId, System.DateTime? BannedUntilUtc);
public sealed record AuthWithTokenRequest(string Token);
public sealed record AuthWithTokenResponse(bool Ok, string? Error, ulong AccountId);
+17
View File
@@ -0,0 +1,17 @@
namespace Server.Networking.Messages;
public static class OpCodes
{
public const int ECHO = 1;
public const int AUTH_REGISTER = 100;
public const int AUTH_REGISTER_RESULT = 101;
public const int AUTH_LOGIN = 110;
public const int AUTH_LOGIN_RESULT = 111;
public const int AUTH_WITH_TOKEN = 112;
public const int AUTH_WITH_TOKEN_RESULT = 113;
public const int ERROR = 900; // generic error envelope if you want
}
+40 -3
View File
@@ -4,6 +4,9 @@ using System.Net.Sockets;
using System.Net.WebSockets;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Server.Redis;
using Server.Services.Auth;
using StackExchange.Redis;
namespace Server.Networking;
@@ -12,15 +15,19 @@ public sealed class NetworkManager
private readonly ILogger<NetworkManager> _log;
private readonly MessageRouter _router;
private readonly ConcurrentDictionary<Guid, IConnection> _connections = new();
private readonly ISessionRegistry _sessions;
private readonly IRedisManager _redis;
private readonly TimeSpan _tickInterval;
private readonly TimeSpan _idleTimeout;
private readonly int _maxConnections;
public NetworkManager(ILogger<NetworkManager> log, MessageRouter router)
public NetworkManager(ILogger<NetworkManager> log, MessageRouter router, ISessionRegistry sessions, IRedisManager redis)
{
_log = log;
_router = router;
_sessions = sessions;
_redis = redis;
var tickHz = int.TryParse(Environment.GetEnvironmentVariable("TICK_RATE_HZ"), out var hz) ? Math.Clamp(hz, 1, 120) : 20;
_tickInterval = TimeSpan.FromMilliseconds(1000.0 / tickHz);
@@ -136,9 +143,39 @@ public sealed class NetworkManager
{
if (_connections.TryRemove(conn.Id, out _))
{
// If this connection was authenticated, log it out atomically
if (_sessions.TryGet(conn.Id, out var accountId, out var token) && accountId != 0 && !string.IsNullOrEmpty(token))
{
try
{
var onlineKey = $"online:acct:{accountId}";
var sessKey = $"sess:{token}";
const string lua = @"
if redis.call('GET', KEYS[1]) == ARGV[1] then
redis.call('DEL', KEYS[1])
end
redis.call('DEL', KEYS[2])
return 1";
await _redis.Db.ScriptEvaluateAsync(lua,
new RedisKey[] { onlineKey, sessKey },
new RedisValue[] { token });
_sessions.Unbind(conn.Id);
_log.LogInformation("Logged out account {AccountId} on disconnect", accountId);
}
catch (Exception ex)
{
_log.LogWarning(ex, "Failed Redis logout cleanup for account {AccountId}", accountId);
_sessions.Unbind(conn.Id);
}
}
_log.LogInformation("Disconnected {Id} ({Reason})", conn.Id, reason);
await conn.CloseAsync(reason);
await conn.DisposeAsync();
try { await conn.CloseAsync(reason); } catch { }
try { await conn.DisposeAsync(); } catch { }
}
}
}
+5
View File
@@ -11,6 +11,7 @@ using Server.Networking;
using Server.Persistence;
using Server.Redis;
using Server.Services;
using Server.Services.Auth;
var builder = WebApplication.CreateBuilder(args);
@@ -40,6 +41,10 @@ builder.Services.AddSingleton<IRedisManager, RedisManager>();
builder.Services.AddSingleton<IZoneLeaseService, ZoneLeaseService>();
builder.Services.AddHostedService(sp => (ZoneLeaseService)sp.GetRequiredService<IZoneLeaseService>());
builder.Services.AddSingleton<IWalPublisher, WalPublisher>();
builder.Services.AddScoped<IAccountsRepository, AccountsRepository>();
builder.Services.AddSingleton<IPasswordHasher, Pbkdf2PasswordHasher>();
builder.Services.AddScoped<IAuthService, AuthService>();
builder.Services.AddSingleton<ISessionRegistry, SessionRegistry>();
// Health checks (optional DB/Redis implementations)
builder.Services.AddHealthChecks()
+29
View File
@@ -0,0 +1,29 @@
using Microsoft.EntityFrameworkCore;
using Server.Data;
namespace Server.Services.Auth;
public sealed class AccountsRepository : IAccountsRepository
{
private readonly GameDbContext _db;
public AccountsRepository(GameDbContext db) => _db = db;
public Task<Account?> FindByUsernameAsync(string username, CancellationToken ct = default) =>
_db.Set<Account>().FirstOrDefaultAsync(a => a.Username == username, ct);
public Task<Account?> FindByEmailAsync(string email, CancellationToken ct = default) =>
_db.Set<Account>().FirstOrDefaultAsync(a => a.Email == email, ct);
public async Task<Account> AddAsync(Account account, CancellationToken ct = default)
{
_db.Add(account);
await _db.SaveChangesAsync(ct);
return account;
}
public async Task AddSessionAsync(Session s, CancellationToken ct = default)
{
_db.Add(s);
await _db.SaveChangesAsync(ct);
}
}
+151
View File
@@ -0,0 +1,151 @@
using System.Security.Cryptography;
using System.Text;
using Microsoft.Extensions.Logging;
using Server.Data;
using Server.Redis;
using StackExchange.Redis;
namespace Server.Services.Auth;
public interface IAuthService
{
Task<(bool ok, string? error)> RegisterAsync(string username, string password, string? email, CancellationToken ct = default);
Task<(bool ok, string? error, string? token, ulong accountId)> LoginAsync(string usernameOrEmail, string password, string? ip, string? userAgent, TimeSpan? ttl = null, CancellationToken ct = default);
Task<(bool ok, string? error, ulong accountId)> ValidateTokenAsync(string token, CancellationToken ct = default);
}
public sealed class AuthService : IAuthService
{
private readonly IAccountsRepository _repo;
private readonly IPasswordHasher _hasher;
private readonly IRedisManager _redis;
private readonly ILogger<AuthService> _log;
private const string LuaLoginAtom = @"
-- KEYS[1] = online:acct:{accountId}
-- KEYS[2] = sess:{token}
-- ARGV[1] = token
-- ARGV[2] = ttlSeconds
-- ARGV[3] = accountId (string)
if redis.call('EXISTS', KEYS[1]) == 1 then
return 0
end
redis.call('SET', KEYS[1], ARGV[1])
redis.call('SETEX', KEYS[2], ARGV[2], ARGV[3])
return 1
";
private const string LuaLogoutAtom = @"
-- KEYS[1] = online:acct:{accountId}
-- KEYS[2] = sess:{token}
-- ARGV[1] = token
if redis.call('GET', KEYS[1]) == ARGV[1] then
redis.call('DEL', KEYS[1])
end
redis.call('DEL', KEYS[2])
return 1
";
public AuthService(IAccountsRepository repo, IPasswordHasher hasher, IRedisManager redis, ILogger<AuthService> log)
{
_repo = repo; _hasher = hasher; _redis = redis; _log = log;
}
public async Task<(bool ok, string? error)> RegisterAsync(string username, string password, string? email, CancellationToken ct = default)
{
if (string.IsNullOrWhiteSpace(username) || username.Length is < 3 or > 32) return (false, "invalid_username");
if (string.IsNullOrWhiteSpace(password) || password.Length < 8) return (false, "weak_password");
if (email is { Length: > 255 }) return (false, "invalid_email");
username = username.Trim();
email = email?.Trim();
if (await _repo.FindByUsernameAsync(username, ct) is not null) return (false, "username_taken");
if (!string.IsNullOrWhiteSpace(email) && await _repo.FindByEmailAsync(email!, ct) is not null) return (false, "email_taken");
_hasher.Hash(password, out var hash, out var salt);
var now = DateTime.UtcNow;
var acct = new Account
{
Username = username,
Email = email,
PasswordHash = hash,
PasswordSalt = salt,
CreatedAt = now,
UpdatedAt = now
};
await _repo.AddAsync(acct, ct);
_log.LogInformation("Registered account {Username} ({AccountId})", username, acct.Id);
return (true, null);
}
public async Task<(bool ok, string? error, string? token, ulong accountId)> LoginAsync(
string usernameOrEmail, string password, string? ip, string? userAgent, TimeSpan? ttl = null, CancellationToken ct = default)
{
ttl ??= TimeSpan.FromHours(24);
Account? acct = usernameOrEmail.Contains('@')
? await _repo.FindByEmailAsync(usernameOrEmail, ct)
: await _repo.FindByUsernameAsync(usernameOrEmail, ct);
if (acct is null) return (false, "not_found", null, 0);
if (acct.IsBanned && (!acct.BannedUntil.HasValue || acct.BannedUntil > DateTime.UtcNow))
return (false, "banned", null, 0);
if (!_hasher.Verify(password, acct.PasswordHash, acct.PasswordSalt))
return (false, "bad_credentials", null, 0);
// Create token
var tokenBytes = RandomNumberGenerator.GetBytes(32);
var token = Convert.ToHexString(tokenBytes).ToLowerInvariant();
// Atomically: if not already online, mark online and create sess:{token}
var ttlSeconds = (long)Math.Ceiling(ttl.Value.TotalSeconds);
var onlineKey = $"online:acct:{acct.Id}";
var sessKey = $"sess:{token}";
var res = (int)(long)await _redis.Db.ScriptEvaluateAsync(LuaLoginAtom,
new RedisKey[] { onlineKey, sessKey },
new RedisValue[] { token, ttlSeconds, (long)acct.Id });
if (res != 1)
return (false, "already_online", null, 0);
// Optional: audit to SQL (store hash, not raw token)
var tokenHash = Sha256(token);
await _repo.AddSessionAsync(new Session
{
AccountId = acct.Id,
TokenHash = tokenHash,
CreatedAt = DateTime.UtcNow,
ExpiresAt = DateTime.UtcNow.AddSeconds(ttlSeconds),
CreatedIp = ip,
UserAgent = userAgent
}, ct);
return (true, null, token, acct.Id);
}
public async Task<(bool ok, string? error, ulong accountId)> ValidateTokenAsync(string token, CancellationToken ct = default)
{
if (string.IsNullOrWhiteSpace(token))
return (false, "no_token", 0);
var val = await _redis.Db.StringGetAsync($"sess:{token}");
if (val.IsNullOrEmpty) return (false, "invalid_or_expired", 0);
var accountId = (ulong)(long)val; // stored as long
return (true, null, accountId);
}
private static string Sha256(string input)
{
using var sha = SHA256.Create();
var bytes = sha.ComputeHash(Encoding.UTF8.GetBytes(input));
return Convert.ToHexString(bytes).ToLowerInvariant();
}
}
+11
View File
@@ -0,0 +1,11 @@
using Server.Data;
namespace Server.Services.Auth;
public interface IAccountsRepository
{
Task<Account?> FindByUsernameAsync(string username, CancellationToken ct = default);
Task<Account?> FindByEmailAsync(string email, CancellationToken ct = default);
Task<Account> AddAsync(Account account, CancellationToken ct = default);
Task AddSessionAsync(Session s, CancellationToken ct = default);
}
+7
View File
@@ -0,0 +1,7 @@
namespace Server.Services.Auth;
public interface IPasswordHasher
{
void Hash(string password, out byte[] hash, out byte[] salt);
bool Verify(string password, byte[] hash, byte[] salt);
}
+13
View File
@@ -0,0 +1,13 @@
using System;
using System.Threading.Tasks;
namespace Server.Services.Auth;
public interface ISessionRegistry
{
void Bind(Guid connectionId, ulong accountId, string token);
void Unbind(Guid connectionId);
bool IsAuthenticated(Guid connectionId);
bool TryGetAccountId(Guid connectionId, out ulong accountId);
bool TryGet(Guid connectionId, out ulong accountId, out string token);
}
+24
View File
@@ -0,0 +1,24 @@
using System.Security.Cryptography;
namespace Server.Services.Auth;
public sealed class Pbkdf2PasswordHasher : IPasswordHasher
{
private const int SaltSize = 32;
private const int HashSize = 64;
private const int Iterations = 150_000; // good default; tune for your hardware
public void Hash(string password, out byte[] hash, out byte[] salt)
{
salt = RandomNumberGenerator.GetBytes(SaltSize);
using var pbkdf2 = new Rfc2898DeriveBytes(password, salt, Iterations, HashAlgorithmName.SHA256);
hash = pbkdf2.GetBytes(HashSize);
}
public bool Verify(string password, byte[] hash, byte[] salt)
{
using var pbkdf2 = new Rfc2898DeriveBytes(password, salt, Iterations, HashAlgorithmName.SHA256);
var test = pbkdf2.GetBytes(HashSize);
return CryptographicOperations.FixedTimeEquals(test, hash);
}
}
+31
View File
@@ -0,0 +1,31 @@
using System;
using System.Collections.Concurrent;
namespace Server.Services.Auth;
public sealed class SessionRegistry : ISessionRegistry
{
private readonly ConcurrentDictionary<Guid, (ulong accountId, string token)> _byConn = new();
public void Bind(Guid connectionId, ulong accountId, string token)
=> _byConn[connectionId] = (accountId, token);
public void Unbind(Guid connectionId)
=> _byConn.TryRemove(connectionId, out _);
public bool IsAuthenticated(Guid connectionId)
=> _byConn.ContainsKey(connectionId);
public bool TryGetAccountId(Guid connectionId, out ulong accountId)
{
if (_byConn.TryGetValue(connectionId, out var v)) { accountId = v.accountId; return true; }
accountId = 0; return false;
}
public bool TryGet(Guid connectionId, out ulong accountId, out string token)
{
if (_byConn.TryGetValue(connectionId, out var v))
{ accountId = v.accountId; token = v.token; return true; }
accountId = 0; token = string.Empty; return false;
}
}
+13 -6
View File
@@ -7,10 +7,11 @@ public sealed class Session
{
public ulong Id { get; set; }
public ulong AccountId { get; set; }
public string Token { get; set; } = ""; // 64-char base64url/hex
public string TokenHash { get; set; } = ""; // 64-char base64url/hex
public DateTime ExpiresAt { get; set; }
public DateTime CreatedAt { get; set; }
public string? CreatedIp { get; set; }
public string? UserAgent { get; set; }
public Account? Account { get; set; }
}
@@ -21,10 +22,16 @@ public sealed class SessionConfig : IEntityTypeConfiguration<Session>
e.ToTable("sessions");
e.HasKey(x => x.Id);
e.Property(x => x.Id).ValueGeneratedOnAdd();
e.HasIndex(x => x.Token).IsUnique();
e.HasIndex(x => x.AccountId);
e.Property(x => x.Token).HasMaxLength(64).IsRequired();
e.Property(x => x.TokenHash).HasMaxLength(128).IsRequired();
e.Property(x => x.CreatedIp).HasMaxLength(64);
e.Property(x => x.UserAgent).HasMaxLength(256);
e.Property(x => x.CreatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
e.HasOne(x => x.Account).WithMany(a => a.Sessions).HasForeignKey(x => x.AccountId).OnDelete(DeleteBehavior.Cascade);
e.HasIndex(x => x.AccountId);
e.HasIndex(x => x.TokenHash).IsUnique();
e.HasOne(x => x.Account)
.WithMany(a => a.Sessions)
.HasForeignKey(x => x.AccountId)
.OnDelete(DeleteBehavior.Cascade);
}
}