Compare commits
10
Commits
83030c2a4e
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bf6f86b73c | ||
|
|
0ca7a31daa | ||
|
|
b7c221d765 | ||
|
|
1e4b8463ee | ||
|
|
34742c0759 | ||
|
|
43f3e8f0e7 | ||
|
|
5a27adf034 | ||
|
|
923d117369 | ||
|
|
e35d507fcd | ||
|
|
603a18e006 |
@@ -0,0 +1,44 @@
|
|||||||
|
using GameAuthApi.Services;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using GameAuthApi.Models;
|
||||||
|
|
||||||
|
namespace GameAuthApi.Controllers;
|
||||||
|
|
||||||
|
[ApiController]
|
||||||
|
[Route("api/[controller]")]
|
||||||
|
public class AdminController : ControllerBase
|
||||||
|
{
|
||||||
|
private readonly AdminService _adminService;
|
||||||
|
|
||||||
|
public AdminController(AdminService adminService)
|
||||||
|
{
|
||||||
|
_adminService = adminService;
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("status")]
|
||||||
|
[Authorize(Roles = "SUPER")]
|
||||||
|
public async Task<IActionResult> GetStatus()
|
||||||
|
{
|
||||||
|
var status = await _adminService.GetStatusAsync();
|
||||||
|
return Ok(status);
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPost("reset-locations")]
|
||||||
|
[Authorize(Roles = "SUPER")]
|
||||||
|
public async Task<IActionResult> ResetLocations()
|
||||||
|
{
|
||||||
|
var origin = await _adminService.ResetLocationsAsync();
|
||||||
|
return Ok(origin);
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPost("clear-items")]
|
||||||
|
[Authorize(Roles = "SUPER")]
|
||||||
|
public async Task<IActionResult> ClearItems()
|
||||||
|
{
|
||||||
|
await _adminService.ClearItemsAsync();
|
||||||
|
return Ok("All items cleared.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -4,6 +4,7 @@ using Microsoft.AspNetCore.Authorization;
|
|||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using Microsoft.Extensions.Configuration;
|
using Microsoft.Extensions.Configuration;
|
||||||
using Microsoft.IdentityModel.Tokens;
|
using Microsoft.IdentityModel.Tokens;
|
||||||
|
using Microsoft.AspNetCore.RateLimiting;
|
||||||
using System;
|
using System;
|
||||||
using System.IdentityModel.Tokens.Jwt;
|
using System.IdentityModel.Tokens.Jwt;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
@@ -20,20 +21,32 @@ public class AuthController : ControllerBase
|
|||||||
private readonly UserService _userService;
|
private readonly UserService _userService;
|
||||||
private readonly IConfiguration _config;
|
private readonly IConfiguration _config;
|
||||||
private readonly BlacklistService _blacklistService;
|
private readonly BlacklistService _blacklistService;
|
||||||
|
private readonly PasswordResetService _passwordResetService;
|
||||||
|
private readonly EmailService _emailService;
|
||||||
|
private readonly SteamAuthService _steamAuthService;
|
||||||
|
|
||||||
public AuthController(UserService userService, IConfiguration config, BlacklistService blacklistService)
|
public AuthController(UserService userService, IConfiguration config, BlacklistService blacklistService,
|
||||||
|
PasswordResetService passwordResetService = null, EmailService emailService = null,
|
||||||
|
SteamAuthService steamAuthService = null)
|
||||||
{
|
{
|
||||||
_userService = userService;
|
_userService = userService;
|
||||||
_config = config;
|
_config = config;
|
||||||
_blacklistService = blacklistService;
|
_blacklistService = blacklistService;
|
||||||
|
_passwordResetService = passwordResetService;
|
||||||
|
_emailService = emailService;
|
||||||
|
_steamAuthService = steamAuthService;
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpPost("register")]
|
[HttpPost("register")]
|
||||||
public async Task<IActionResult> Register([FromBody] RegisterRequest credentials)
|
public async Task<IActionResult> Register([FromBody] RegisterRequest credentials)
|
||||||
{
|
{
|
||||||
if (await _userService.GetByUsernameAsync(credentials.Username) != null)
|
if (await _userService.GetByLoginAsync(credentials.Username) != null ||
|
||||||
|
(!string.IsNullOrWhiteSpace(credentials.Email) && await _userService.GetByLoginAsync(credentials.Email) != null))
|
||||||
return BadRequest("User already exists");
|
return BadRequest("User already exists");
|
||||||
|
|
||||||
|
if (!IsValidUsername(credentials.Username) || !IsValidEmail(credentials.Email) || !IsValidPassword(credentials.Password))
|
||||||
|
return BadRequest("Username, email, or password is invalid");
|
||||||
|
|
||||||
var hash = BCrypt.Net.BCrypt.HashPassword(credentials.Password);
|
var hash = BCrypt.Net.BCrypt.HashPassword(credentials.Password);
|
||||||
|
|
||||||
var user = new User
|
var user = new User
|
||||||
@@ -51,7 +64,7 @@ public class AuthController : ControllerBase
|
|||||||
[HttpPost("login")]
|
[HttpPost("login")]
|
||||||
public async Task<IActionResult> Login([FromBody] LoginRequest credentials)
|
public async Task<IActionResult> Login([FromBody] LoginRequest credentials)
|
||||||
{
|
{
|
||||||
var user = await _userService.GetByUsernameAsync(credentials.Username);
|
var user = await _userService.GetByLoginAsync(credentials.Username);
|
||||||
if (user == null || !BCrypt.Net.BCrypt.Verify(credentials.Password, user.PasswordHash))
|
if (user == null || !BCrypt.Net.BCrypt.Verify(credentials.Password, user.PasswordHash))
|
||||||
return Unauthorized();
|
return Unauthorized();
|
||||||
|
|
||||||
@@ -66,6 +79,105 @@ public class AuthController : ControllerBase
|
|||||||
return Ok(new { accessToken, refreshToken, user.Username, user.Role });
|
return Ok(new { accessToken, refreshToken, user.Username, user.Role });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[HttpPost("password-reset/request")]
|
||||||
|
[EnableRateLimiting("password-reset")]
|
||||||
|
public async Task<IActionResult> RequestPasswordReset([FromBody] PasswordResetRequest request)
|
||||||
|
{
|
||||||
|
if (_passwordResetService == null || _emailService == null)
|
||||||
|
return StatusCode(503, "Password recovery is not configured");
|
||||||
|
var user = await _userService.GetByLoginAsync(request.Login ?? string.Empty);
|
||||||
|
if (user != null && !string.IsNullOrWhiteSpace(user.Email))
|
||||||
|
{
|
||||||
|
var code = await _passwordResetService.CreateAsync(user.Id);
|
||||||
|
await _emailService.SendPasswordResetCodeAsync(user.Email, code);
|
||||||
|
}
|
||||||
|
return Accepted(new { message = "If the account exists, a verification code has been sent." });
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPost("password-reset/confirm")]
|
||||||
|
[EnableRateLimiting("password-reset")]
|
||||||
|
public async Task<IActionResult> ConfirmPasswordReset([FromBody] PasswordResetConfirmRequest request)
|
||||||
|
{
|
||||||
|
if (_passwordResetService == null) return StatusCode(503, "Password recovery is not configured");
|
||||||
|
if (!IsValidPassword(request.NewPassword)) return BadRequest("Password must be at least 8 characters");
|
||||||
|
var user = await _userService.GetByLoginAsync(request.Login ?? string.Empty);
|
||||||
|
if (user == null || !await _passwordResetService.ConsumeAsync(user.Id, request.Code ?? string.Empty))
|
||||||
|
return BadRequest("The verification code is invalid or expired");
|
||||||
|
user.PasswordHash = BCrypt.Net.BCrypt.HashPassword(request.NewPassword);
|
||||||
|
user.RefreshToken = null;
|
||||||
|
user.RefreshTokenExpiry = DateTime.MinValue;
|
||||||
|
await _userService.UpdateAsync(user);
|
||||||
|
return Ok(new { message = "Password updated" });
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPost("steam/start")]
|
||||||
|
public async Task<IActionResult> StartSteamLogin()
|
||||||
|
{
|
||||||
|
if (_steamAuthService == null) return StatusCode(503, "Steam authentication is not configured");
|
||||||
|
var started = await _steamAuthService.StartAsync();
|
||||||
|
return Ok(new { transactionId = started.Transaction.Id, authUrl = started.AuthUrl, expiresUtc = started.Transaction.ExpiresUtc });
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("steam/callback")]
|
||||||
|
public async Task<IActionResult> SteamCallback([FromQuery] string transactionId)
|
||||||
|
{
|
||||||
|
if (_steamAuthService == null || !await _steamAuthService.VerifyCallbackAsync(transactionId, Request.Query))
|
||||||
|
return StatusCode(400, "Steam sign-in could not be verified. You may close this window.");
|
||||||
|
return Content("Steam sign-in verified. Return to MedMind to finish signing in.", "text/plain", Encoding.UTF8);
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("steam/status/{transactionId}")]
|
||||||
|
public async Task<IActionResult> SteamStatus(string transactionId)
|
||||||
|
{
|
||||||
|
if (_steamAuthService == null) return StatusCode(503, "Steam authentication is not configured");
|
||||||
|
var transaction = await _steamAuthService.GetAsync(transactionId);
|
||||||
|
if (transaction == null) return NotFound(new { status = "expired" });
|
||||||
|
if (transaction.Status == "authenticated" && !string.IsNullOrWhiteSpace(transaction.UserId))
|
||||||
|
{
|
||||||
|
var user = await _userService.GetByIdAsync(transaction.UserId);
|
||||||
|
if (user == null) return BadRequest("Linked account no longer exists");
|
||||||
|
var tokens = await IssueTokensAsync(user);
|
||||||
|
await _steamAuthService.CompleteAsync(transactionId, user, tokens.AccessToken, tokens.RefreshToken);
|
||||||
|
transaction = await _steamAuthService.GetAsync(transactionId);
|
||||||
|
}
|
||||||
|
return Ok(new
|
||||||
|
{
|
||||||
|
transaction.Status, transaction.Username, transaction.Role,
|
||||||
|
transaction.AccessToken, transaction.RefreshToken
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPost("steam/complete")]
|
||||||
|
public async Task<IActionResult> CompleteSteamLogin([FromBody] SteamCompleteRequest request)
|
||||||
|
{
|
||||||
|
if (_steamAuthService == null) return StatusCode(503, "Steam authentication is not configured");
|
||||||
|
User user;
|
||||||
|
if (string.Equals(request.Action, "link", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
user = await _userService.GetByLoginAsync(request.Username ?? string.Empty);
|
||||||
|
if (user == null || !BCrypt.Net.BCrypt.Verify(request.Password ?? string.Empty, user.PasswordHash))
|
||||||
|
return Unauthorized();
|
||||||
|
}
|
||||||
|
else if (string.Equals(request.Action, "create", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
if (!IsValidUsername(request.Username) || !IsValidEmail(request.Email) || !IsValidPassword(request.Password))
|
||||||
|
return BadRequest("Username, email, or password is invalid");
|
||||||
|
if (await _userService.GetByLoginAsync(request.Username) != null || await _userService.GetByLoginAsync(request.Email) != null)
|
||||||
|
return Conflict("Username or email is already in use");
|
||||||
|
user = new User
|
||||||
|
{
|
||||||
|
Username = request.Username.Trim(), Email = request.Email.Trim(),
|
||||||
|
PasswordHash = BCrypt.Net.BCrypt.HashPassword(request.Password), Role = "USER"
|
||||||
|
};
|
||||||
|
await _userService.CreateAsync(user);
|
||||||
|
}
|
||||||
|
else return BadRequest("Action must be create or link");
|
||||||
|
|
||||||
|
try { await _steamAuthService.LinkAsync(request.TransactionId, user.Id); }
|
||||||
|
catch (MongoDB.Driver.MongoWriteException) { return Conflict("This Steam account is already linked"); }
|
||||||
|
return Ok(new { status = "linked" });
|
||||||
|
}
|
||||||
|
|
||||||
[HttpPost("refresh")]
|
[HttpPost("refresh")]
|
||||||
public async Task<IActionResult> Refresh([FromBody] RefreshRequest req)
|
public async Task<IActionResult> Refresh([FromBody] RefreshRequest req)
|
||||||
{
|
{
|
||||||
@@ -140,6 +252,22 @@ public class AuthController : ControllerBase
|
|||||||
return new JwtSecurityTokenHandler().WriteToken(token);
|
return new JwtSecurityTokenHandler().WriteToken(token);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async Task<(string AccessToken, string RefreshToken)> IssueTokensAsync(User user)
|
||||||
|
{
|
||||||
|
var accessToken = GenerateJwtToken(user);
|
||||||
|
var refreshToken = Guid.NewGuid().ToString();
|
||||||
|
user.RefreshToken = refreshToken;
|
||||||
|
user.RefreshTokenExpiry = DateTime.UtcNow.AddDays(7);
|
||||||
|
await _userService.UpdateAsync(user);
|
||||||
|
return (accessToken, refreshToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsValidUsername(string value) =>
|
||||||
|
!string.IsNullOrWhiteSpace(value) && value.Length is >= 3 and <= 24 && value.All(c => char.IsLetterOrDigit(c) || c == '_');
|
||||||
|
private static bool IsValidEmail(string value) =>
|
||||||
|
!string.IsNullOrWhiteSpace(value) && value.Contains('@') && value.Length <= 254;
|
||||||
|
private static bool IsValidPassword(string value) => !string.IsNullOrEmpty(value) && value.Length >= 8;
|
||||||
|
|
||||||
public class RefreshRequest
|
public class RefreshRequest
|
||||||
{
|
{
|
||||||
public string Username { get; set; }
|
public string Username { get; set; }
|
||||||
|
|||||||
@@ -12,11 +12,13 @@ public class ItemController : ControllerBase
|
|||||||
{
|
{
|
||||||
private readonly ItemService _itemService;
|
private readonly ItemService _itemService;
|
||||||
private readonly LocationService _locationService;
|
private readonly LocationService _locationService;
|
||||||
|
private readonly SpawnableService _spawnableService;
|
||||||
|
|
||||||
public ItemController(ItemService itemService, LocationService locationService)
|
public ItemController(ItemService itemService, LocationService locationService, SpawnableService spawnableService)
|
||||||
{
|
{
|
||||||
_itemService = itemService;
|
_itemService = itemService;
|
||||||
_locationService = locationService;
|
_locationService = locationService;
|
||||||
|
_spawnableService = spawnableService;
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpPost]
|
[HttpPost]
|
||||||
@@ -27,10 +29,16 @@ public class ItemController : ControllerBase
|
|||||||
if (location == null)
|
if (location == null)
|
||||||
return BadRequest("Invalid location ID.");
|
return BadRequest("Invalid location ID.");
|
||||||
|
|
||||||
|
var uses = req.UsesRemaining;
|
||||||
|
var spawnable = await _spawnableService.GetByNameAsync(req.Name.ToLower());
|
||||||
|
if (spawnable != null && spawnable.Uses > 0)
|
||||||
|
uses = spawnable.Uses;
|
||||||
|
|
||||||
var item = new Item
|
var item = new Item
|
||||||
{
|
{
|
||||||
Name = req.Name,
|
Name = req.Name,
|
||||||
LocationId = req.LocationId
|
LocationId = req.LocationId,
|
||||||
|
UsesRemaining = uses
|
||||||
};
|
};
|
||||||
|
|
||||||
await _itemService.CreateAsync(item);
|
await _itemService.CreateAsync(item);
|
||||||
@@ -58,6 +66,7 @@ public class ItemController : ControllerBase
|
|||||||
|
|
||||||
item.Name = req.Name;
|
item.Name = req.Name;
|
||||||
item.LocationId = req.LocationId;
|
item.LocationId = req.LocationId;
|
||||||
|
item.UsesRemaining = req.UsesRemaining;
|
||||||
await _itemService.UpdateAsync(item);
|
await _itemService.UpdateAsync(item);
|
||||||
return Ok(item);
|
return Ok(item);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -45,6 +45,32 @@ public class LocationController : ControllerBase
|
|||||||
return Ok(newLoc);
|
return Ok(newLoc);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[HttpPost("inventory")]
|
||||||
|
[Authorize(Roles = "SUPER")]
|
||||||
|
public async Task<IActionResult> CreateInventory()
|
||||||
|
{
|
||||||
|
var inventoryLocation = new Location
|
||||||
|
{
|
||||||
|
LocationType = "Inventory",
|
||||||
|
X = null,
|
||||||
|
Y = null,
|
||||||
|
Z = null,
|
||||||
|
N = null,
|
||||||
|
NE = null,
|
||||||
|
E = null,
|
||||||
|
SE = null,
|
||||||
|
S = null,
|
||||||
|
SW = null,
|
||||||
|
W = null,
|
||||||
|
NW = null,
|
||||||
|
Players = new List<string>()
|
||||||
|
};
|
||||||
|
|
||||||
|
await _locationService.CreateAsync(inventoryLocation);
|
||||||
|
|
||||||
|
return Ok(inventoryLocation);
|
||||||
|
}
|
||||||
|
|
||||||
[HttpPut("{id}")]
|
[HttpPut("{id}")]
|
||||||
[Authorize(Roles = "SUPER")]
|
[Authorize(Roles = "SUPER")]
|
||||||
public async Task<IActionResult> Update(string id, [FromBody] UpdateLocationRequest req)
|
public async Task<IActionResult> Update(string id, [FromBody] UpdateLocationRequest req)
|
||||||
|
|||||||
@@ -94,7 +94,7 @@ public class PlayerController : ControllerBase
|
|||||||
}
|
}
|
||||||
|
|
||||||
[HttpPut]
|
[HttpPut]
|
||||||
[Authorize(Roles = "SUPER")]
|
[Authorize(Roles = "USER,SUPER")]
|
||||||
public async Task<IActionResult> Update([FromBody] UpdatePlayerRequest req)
|
public async Task<IActionResult> Update([FromBody] UpdatePlayerRequest req)
|
||||||
{
|
{
|
||||||
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||||
@@ -109,7 +109,7 @@ public class PlayerController : ControllerBase
|
|||||||
}
|
}
|
||||||
|
|
||||||
[HttpDelete]
|
[HttpDelete]
|
||||||
[Authorize(Roles = "SUPER")]
|
[Authorize(Roles = "USER,SUPER")]
|
||||||
public async Task<IActionResult> Delete()
|
public async Task<IActionResult> Delete()
|
||||||
{
|
{
|
||||||
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||||
@@ -223,7 +223,8 @@ public class PlayerController : ControllerBase
|
|||||||
var tempItem = new Item
|
var tempItem = new Item
|
||||||
{
|
{
|
||||||
Name = s.Name,
|
Name = s.Name,
|
||||||
LocationId = null
|
LocationId = null,
|
||||||
|
UsesRemaining = s.Uses
|
||||||
};
|
};
|
||||||
|
|
||||||
await _itemService.CreateAsync(tempItem);
|
await _itemService.CreateAsync(tempItem);
|
||||||
@@ -346,6 +347,19 @@ public class PlayerController : ControllerBase
|
|||||||
await _locationService.RemoveItemFromLocationAsync(location.Id, itemId);
|
await _locationService.RemoveItemFromLocationAsync(location.Id, itemId);
|
||||||
await _itemService.DeleteAsync(itemId);
|
await _itemService.DeleteAsync(itemId);
|
||||||
}
|
}
|
||||||
|
else if (item.UsesRemaining > 0)
|
||||||
|
{
|
||||||
|
item.UsesRemaining--;
|
||||||
|
if (item.UsesRemaining <= 0)
|
||||||
|
{
|
||||||
|
await _locationService.RemoveItemFromLocationAsync(location.Id, itemId);
|
||||||
|
await _itemService.DeleteAsync(itemId);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
await _itemService.UpdateAsync(item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return Ok(outcome.Result);
|
return Ok(outcome.Result);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,7 +26,9 @@ public class SpawnableController : ControllerBase
|
|||||||
Name = req.Name.ToLower(),
|
Name = req.Name.ToLower(),
|
||||||
SpawnRate = req.SpawnRate,
|
SpawnRate = req.SpawnRate,
|
||||||
CollectAction = req.CollectAction,
|
CollectAction = req.CollectAction,
|
||||||
CollectResults = req.CollectResults
|
CollectResults = req.CollectResults,
|
||||||
|
ConsumeOnSuccess = req.ConsumeOnSuccess,
|
||||||
|
Uses = req.Uses
|
||||||
};
|
};
|
||||||
|
|
||||||
await _spawnableService.CreateAsync(spawnable);
|
await _spawnableService.CreateAsync(spawnable);
|
||||||
@@ -45,6 +47,8 @@ public class SpawnableController : ControllerBase
|
|||||||
spawnable.SpawnRate = req.SpawnRate;
|
spawnable.SpawnRate = req.SpawnRate;
|
||||||
spawnable.CollectAction = req.CollectAction;
|
spawnable.CollectAction = req.CollectAction;
|
||||||
spawnable.CollectResults = req.CollectResults;
|
spawnable.CollectResults = req.CollectResults;
|
||||||
|
spawnable.ConsumeOnSuccess = req.ConsumeOnSuccess;
|
||||||
|
spawnable.Uses = req.Uses;
|
||||||
|
|
||||||
await _spawnableService.UpdateAsync(spawnable);
|
await _spawnableService.UpdateAsync(spawnable);
|
||||||
return Ok(spawnable);
|
return Ok(spawnable);
|
||||||
|
|||||||
@@ -0,0 +1,56 @@
|
|||||||
|
using GameAuthApi.Controllers;
|
||||||
|
using GameAuthApi.Services;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using GameAuthApi.Models;
|
||||||
|
|
||||||
|
public class AdminControllerTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public async Task GetStatus_ReturnsOk()
|
||||||
|
{
|
||||||
|
var expected = new Dictionary<string, string> { { "status", "ok" } };
|
||||||
|
var mockService = new Mock<AdminService>((LocationService)null, (ItemService)null, (PlayerService)null);
|
||||||
|
mockService.Setup(s => s.GetStatusAsync()).ReturnsAsync(expected);
|
||||||
|
var controller = new AdminController(mockService.Object);
|
||||||
|
|
||||||
|
var result = await controller.GetStatus();
|
||||||
|
|
||||||
|
var ok = Assert.IsType<OkObjectResult>(result);
|
||||||
|
Assert.Equal(expected, ok.Value);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task ResetLocations_ReturnsOk()
|
||||||
|
{
|
||||||
|
var newLoc = new Location { LocationType = "World", X = 0, Y = 0, Z = 0 };
|
||||||
|
var mockService = new Mock<AdminService>((LocationService)null, (ItemService)null, (PlayerService)null);
|
||||||
|
mockService.Setup(s => s.ResetLocationsAsync()).ReturnsAsync(newLoc);
|
||||||
|
var controller = new AdminController(mockService.Object);
|
||||||
|
|
||||||
|
var result = await controller.ResetLocations();
|
||||||
|
|
||||||
|
var ok = Assert.IsType<OkObjectResult>(result);
|
||||||
|
var origin = Assert.IsType<Location>(ok.Value);
|
||||||
|
Assert.Equal("World", origin.LocationType);
|
||||||
|
Assert.Equal(0, origin.X);
|
||||||
|
Assert.Equal(0, origin.Y);
|
||||||
|
Assert.Equal(0, origin.Z);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task ClearItems_ReturnsOk()
|
||||||
|
{
|
||||||
|
var mockService = new Mock<AdminService>((LocationService)null, (ItemService)null, (PlayerService)null);
|
||||||
|
mockService.Setup(s => s.ClearItemsAsync()).Returns(Task.CompletedTask).Verifiable();
|
||||||
|
var controller = new AdminController(mockService.Object);
|
||||||
|
|
||||||
|
var result = await controller.ClearItems();
|
||||||
|
|
||||||
|
var ok = Assert.IsType<OkObjectResult>(result);
|
||||||
|
Assert.Equal("All items cleared.", ok.Value);
|
||||||
|
mockService.Verify();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
using GameAuthApi.Services;
|
||||||
|
using GameAuthApi.Models;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
|
||||||
|
public class AdminServiceTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public async Task ResetLocations_DeletesWorldLocationsOnly()
|
||||||
|
{
|
||||||
|
var worldLocs = new List<Location> { new() { Id = "1", LocationType = "World" } };
|
||||||
|
|
||||||
|
var cfg = new ConfigurationBuilder()
|
||||||
|
.AddInMemoryCollection(new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
{"MongoDB:ConnectionString", "mongodb://localhost"},
|
||||||
|
{"MongoDB:DatabaseName", "test"}
|
||||||
|
}).Build();
|
||||||
|
|
||||||
|
var locSvc = new Mock<LocationService>(cfg);
|
||||||
|
locSvc.Setup(l => l.GetByTypeAsync("World")).ReturnsAsync(worldLocs);
|
||||||
|
locSvc.Setup(l => l.DeleteByTypeAsync("World")).Returns(Task.CompletedTask).Verifiable();
|
||||||
|
locSvc.Setup(l => l.CreateAsync(It.IsAny<Location>())).Returns(Task.CompletedTask);
|
||||||
|
|
||||||
|
var itemSvc = new Mock<ItemService>(cfg);
|
||||||
|
itemSvc.Setup(i => i.DeleteByLocationAsync("1")).Returns(Task.CompletedTask).Verifiable();
|
||||||
|
|
||||||
|
var playerSvc = new Mock<PlayerService>(cfg);
|
||||||
|
playerSvc.Setup(p => p.GetAllAsync()).ReturnsAsync(new List<Player>());
|
||||||
|
|
||||||
|
var adminSvc = new AdminService(locSvc.Object, itemSvc.Object, playerSvc.Object);
|
||||||
|
|
||||||
|
await adminSvc.ResetLocationsAsync();
|
||||||
|
|
||||||
|
locSvc.Verify();
|
||||||
|
itemSvc.Verify();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task ClearItems_RemovesAllItemsFromLocations()
|
||||||
|
{
|
||||||
|
var cfg = new ConfigurationBuilder()
|
||||||
|
.AddInMemoryCollection(new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
{"MongoDB:ConnectionString", "mongodb://localhost"},
|
||||||
|
{"MongoDB:DatabaseName", "test"}
|
||||||
|
}).Build();
|
||||||
|
|
||||||
|
var locSvc = new Mock<LocationService>(cfg);
|
||||||
|
locSvc.Setup(l => l.ClearAllItemsAsync()).Returns(Task.CompletedTask).Verifiable();
|
||||||
|
|
||||||
|
var itemSvc = new Mock<ItemService>(cfg);
|
||||||
|
itemSvc.Setup(i => i.DeleteAllAsync()).Returns(Task.CompletedTask).Verifiable();
|
||||||
|
|
||||||
|
var playerSvc = new Mock<PlayerService>(cfg);
|
||||||
|
|
||||||
|
var adminSvc = new AdminService(locSvc.Object, itemSvc.Object, playerSvc.Object);
|
||||||
|
|
||||||
|
await adminSvc.ClearItemsAsync();
|
||||||
|
|
||||||
|
locSvc.Verify();
|
||||||
|
itemSvc.Verify();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -48,6 +48,49 @@ public class AuthControllerTests
|
|||||||
Assert.IsType<UnauthorizedResult>(result);
|
Assert.IsType<UnauthorizedResult>(result);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Login_EmailIdentifier_ReturnsTokens()
|
||||||
|
{
|
||||||
|
var config = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>
|
||||||
|
{
|
||||||
|
["Jwt:Key"] = "abcdefghijklmnopqrstuvwxyz123456",
|
||||||
|
["Jwt:Issuer"] = "issuer",
|
||||||
|
["MongoDB:ConnectionString"] = "mongodb://localhost",
|
||||||
|
["MongoDB:DatabaseName"] = "test"
|
||||||
|
}).Build();
|
||||||
|
var user = new User
|
||||||
|
{
|
||||||
|
Id = "507f1f77bcf86cd799439011", Username = "student", Email = "[email protected]",
|
||||||
|
PasswordHash = BCrypt.Net.BCrypt.HashPassword("password123"), Role = "USER"
|
||||||
|
};
|
||||||
|
var users = new Mock<UserService>(config);
|
||||||
|
users.Setup(x => x.GetByLoginAsync("[email protected]")).ReturnsAsync(user);
|
||||||
|
users.Setup(x => x.UpdateAsync(user)).Returns(Task.CompletedTask);
|
||||||
|
var controller = new AuthController(users.Object, config, new Mock<BlacklistService>(config).Object);
|
||||||
|
|
||||||
|
var result = await controller.Login(new LoginRequest { Username = "[email protected]", Password = "password123" });
|
||||||
|
|
||||||
|
Assert.IsType<OkObjectResult>(result);
|
||||||
|
Assert.False(string.IsNullOrWhiteSpace(user.RefreshToken));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Register_DuplicateEmail_ReturnsBadRequest()
|
||||||
|
{
|
||||||
|
var config = GetConfig();
|
||||||
|
var users = new Mock<UserService>(config);
|
||||||
|
users.Setup(x => x.GetByLoginAsync("new_user")).ReturnsAsync((User?)null);
|
||||||
|
users.Setup(x => x.GetByLoginAsync("[email protected]")).ReturnsAsync(new User());
|
||||||
|
var controller = new AuthController(users.Object, config, new Mock<BlacklistService>(config).Object);
|
||||||
|
|
||||||
|
var result = await controller.Register(new RegisterRequest
|
||||||
|
{
|
||||||
|
Username = "new_user", Email = "[email protected]", Password = "password123"
|
||||||
|
});
|
||||||
|
|
||||||
|
Assert.IsType<BadRequestObjectResult>(result);
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task Refresh_InvalidToken_ReturnsUnauthorized()
|
public async Task Refresh_InvalidToken_ReturnsUnauthorized()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ public class ItemControllerTests
|
|||||||
{
|
{
|
||||||
var loc = new Mock<LocationService>(config);
|
var loc = new Mock<LocationService>(config);
|
||||||
loc.Setup(l => l.GetByIdAsync("bad")).ReturnsAsync((Location?)null);
|
loc.Setup(l => l.GetByIdAsync("bad")).ReturnsAsync((Location?)null);
|
||||||
var controller = new ItemController(new Mock<ItemService>(config).Object, loc.Object);
|
var controller = new ItemController(new Mock<ItemService>(config).Object, loc.Object, new Mock<SpawnableService>(config).Object);
|
||||||
|
|
||||||
var result = await controller.Create(new CreateItemRequest { LocationId = "bad", Name = "n" });
|
var result = await controller.Create(new CreateItemRequest { LocationId = "bad", Name = "n" });
|
||||||
|
|
||||||
@@ -30,7 +30,7 @@ public class ItemControllerTests
|
|||||||
{
|
{
|
||||||
var svc = new Mock<ItemService>(config);
|
var svc = new Mock<ItemService>(config);
|
||||||
svc.Setup(i => i.GetByIdAsync("id")).ReturnsAsync((Item?)null);
|
svc.Setup(i => i.GetByIdAsync("id")).ReturnsAsync((Item?)null);
|
||||||
var controller = new ItemController(svc.Object, new Mock<LocationService>(config).Object);
|
var controller = new ItemController(svc.Object, new Mock<LocationService>(config).Object, new Mock<SpawnableService>(config).Object);
|
||||||
|
|
||||||
var result = await controller.Update("id", new UpdateItemRequest { LocationId="loc", Name="x" });
|
var result = await controller.Update("id", new UpdateItemRequest { LocationId="loc", Name="x" });
|
||||||
|
|
||||||
@@ -42,7 +42,7 @@ public class ItemControllerTests
|
|||||||
{
|
{
|
||||||
var svc = new Mock<ItemService>(config);
|
var svc = new Mock<ItemService>(config);
|
||||||
svc.Setup(i => i.GetByIdAsync("id")).ReturnsAsync((Item?)null);
|
svc.Setup(i => i.GetByIdAsync("id")).ReturnsAsync((Item?)null);
|
||||||
var controller = new ItemController(svc.Object, new Mock<LocationService>(config).Object);
|
var controller = new ItemController(svc.Object, new Mock<LocationService>(config).Object, new Mock<SpawnableService>(config).Object);
|
||||||
|
|
||||||
var result = await controller.Delete("id");
|
var result = await controller.Delete("id");
|
||||||
|
|
||||||
|
|||||||
@@ -26,6 +26,19 @@ public class LocationControllerTests
|
|||||||
mockLoc.Verify();
|
mockLoc.Verify();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task CreateInventory_ReturnsOk()
|
||||||
|
{
|
||||||
|
var mockLoc = new Mock<LocationService>(config);
|
||||||
|
mockLoc.Setup(l => l.CreateAsync(It.IsAny<Location>())).Returns(Task.CompletedTask).Verifiable();
|
||||||
|
var controller = new LocationController(mockLoc.Object, new Mock<PlayerService>(config).Object);
|
||||||
|
|
||||||
|
var result = await controller.CreateInventory();
|
||||||
|
|
||||||
|
Assert.IsType<OkObjectResult>(result);
|
||||||
|
mockLoc.Verify();
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task GetById_NotFound()
|
public async Task GetById_NotFound()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -186,4 +186,77 @@ public class PlayerControllerTests
|
|||||||
locSvc.Verify();
|
locSvc.Verify();
|
||||||
itemSvc.Verify();
|
itemSvc.Verify();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task PerformAction_DecrementsUses()
|
||||||
|
{
|
||||||
|
var playerSvc = new Mock<PlayerService>(cfg);
|
||||||
|
var player = new Player { Id = "p", UserId = "u", LocationId = "loc", InventoryLocationId = "inv" };
|
||||||
|
playerSvc.Setup(p => p.GetByUserIdAsync("u")).ReturnsAsync(player);
|
||||||
|
var locSvc = new Mock<LocationService>(cfg);
|
||||||
|
var loc = new Location { Id = "loc", Content = new List<string> { "i" } };
|
||||||
|
locSvc.Setup(l => l.GetByIdAsync("loc")).ReturnsAsync(loc);
|
||||||
|
var itemSvc = new Mock<ItemService>(cfg);
|
||||||
|
var item = new Item { Id = "i", Name = "wood", UsesRemaining = 2 };
|
||||||
|
itemSvc.Setup(i => i.GetByIdAsync("i")).ReturnsAsync(item);
|
||||||
|
itemSvc.Setup(i => i.UpdateAsync(It.Is<Item>(it => it.UsesRemaining == 1))).Returns(Task.CompletedTask).Verifiable();
|
||||||
|
var spawnSvc = new Mock<SpawnableService>(cfg);
|
||||||
|
spawnSvc.Setup(s => s.GetByNameAsync("wood")).ReturnsAsync(new Spawnable
|
||||||
|
{
|
||||||
|
Name = "wood",
|
||||||
|
CollectAction = "chop",
|
||||||
|
CollectResults = new List<CollectOutcome> { new() { Result = "log", SuccessRate = 100 } },
|
||||||
|
ConsumeOnSuccess = false
|
||||||
|
});
|
||||||
|
|
||||||
|
var controller = new PlayerController(playerSvc.Object, locSvc.Object, spawnSvc.Object, itemSvc.Object)
|
||||||
|
{
|
||||||
|
ControllerContext = ContextWithUser("u")
|
||||||
|
};
|
||||||
|
|
||||||
|
await controller.PerformAction(new PerformActionRequest { Action = "chop" });
|
||||||
|
|
||||||
|
itemSvc.Verify();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Move_SpawnableSetsItemUses()
|
||||||
|
{
|
||||||
|
var playerSvc = new Mock<PlayerService>(cfg);
|
||||||
|
var player = new Player { Id = "p", UserId = "u", LocationId = "loc" };
|
||||||
|
playerSvc.Setup(p => p.GetByUserIdAsync("u")).ReturnsAsync(player);
|
||||||
|
playerSvc.Setup(p => p.UpdateAsync(It.IsAny<Player>())).Returns(Task.CompletedTask);
|
||||||
|
|
||||||
|
var current = new Location { Id = "loc", X = 0, Y = 0, Z = 0 };
|
||||||
|
var locSvc = new Mock<LocationService>(cfg);
|
||||||
|
locSvc.Setup(l => l.GetByIdAsync("loc")).ReturnsAsync(current);
|
||||||
|
locSvc.Setup(l => l.GetByCoordinatesAsync(It.IsAny<int>(), It.IsAny<int>(), It.IsAny<int>()))
|
||||||
|
.ReturnsAsync((Location?)null);
|
||||||
|
locSvc.Setup(l => l.CreateAsync(It.IsAny<Location>())).Returns(Task.CompletedTask);
|
||||||
|
locSvc.Setup(l => l.UpdateAsync(It.IsAny<Location>())).Returns(Task.CompletedTask);
|
||||||
|
locSvc.Setup(l => l.RemovePlayerFromLocationAsync("loc", "p")).Returns(Task.CompletedTask);
|
||||||
|
locSvc.Setup(l => l.AddPlayerToLocationAsync(It.IsAny<string>(), "p")).Returns(Task.CompletedTask);
|
||||||
|
|
||||||
|
var spawned = new Spawnable { Name = "wood", SpawnRate = 100, Uses = 3 };
|
||||||
|
var spawnSvc = new Mock<SpawnableService>(cfg);
|
||||||
|
spawnSvc.Setup(s => s.GetAllAsync()).ReturnsAsync([spawned]);
|
||||||
|
|
||||||
|
var itemSvc = new Mock<ItemService>(cfg);
|
||||||
|
Item? created = null;
|
||||||
|
itemSvc.Setup(i => i.CreateAsync(It.IsAny<Item>()))
|
||||||
|
.Callback<Item>(it => { created = it; it.Id = "i"; })
|
||||||
|
.Returns(Task.CompletedTask);
|
||||||
|
itemSvc.Setup(i => i.GetByIdAsync("i")).ReturnsAsync(() => created!);
|
||||||
|
itemSvc.Setup(i => i.UpdateAsync(It.IsAny<Item>())).Returns(Task.CompletedTask);
|
||||||
|
|
||||||
|
var controller = new PlayerController(playerSvc.Object, locSvc.Object, spawnSvc.Object, itemSvc.Object)
|
||||||
|
{
|
||||||
|
ControllerContext = ContextWithUser("u")
|
||||||
|
};
|
||||||
|
|
||||||
|
await controller.Move(new MoveRequest { Direction = "N" });
|
||||||
|
|
||||||
|
Assert.NotNull(created);
|
||||||
|
Assert.Equal(3, created!.UsesRemaining);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,7 +21,9 @@ public class SpawnableControllerTests
|
|||||||
sp.CollectAction == "gather" &&
|
sp.CollectAction == "gather" &&
|
||||||
sp.CollectResults.Count == 2 &&
|
sp.CollectResults.Count == 2 &&
|
||||||
sp.CollectResults[0].Result == "resource" &&
|
sp.CollectResults[0].Result == "resource" &&
|
||||||
sp.CollectResults[0].SuccessRate == 75)))
|
sp.CollectResults[0].SuccessRate == 75 &&
|
||||||
|
sp.ConsumeOnSuccess &&
|
||||||
|
sp.Uses == 0)))
|
||||||
.Returns(Task.CompletedTask).Verifiable();
|
.Returns(Task.CompletedTask).Verifiable();
|
||||||
var controller = new SpawnableController(svc.Object);
|
var controller = new SpawnableController(svc.Object);
|
||||||
|
|
||||||
@@ -34,7 +36,8 @@ public class SpawnableControllerTests
|
|||||||
{
|
{
|
||||||
new() { Result = "resource", SuccessRate = 75 },
|
new() { Result = "resource", SuccessRate = 75 },
|
||||||
new() { Result = "nothing", SuccessRate = 25 }
|
new() { Result = "nothing", SuccessRate = 25 }
|
||||||
}
|
},
|
||||||
|
ConsumeOnSuccess = true
|
||||||
});
|
});
|
||||||
|
|
||||||
Assert.IsType<OkObjectResult>(result);
|
Assert.IsType<OkObjectResult>(result);
|
||||||
@@ -74,7 +77,7 @@ public class SpawnableControllerTests
|
|||||||
svc.Setup(s => s.GetByIdAsync("id")).ReturnsAsync((Spawnable)null);
|
svc.Setup(s => s.GetByIdAsync("id")).ReturnsAsync((Spawnable)null);
|
||||||
var controller = new SpawnableController(svc.Object);
|
var controller = new SpawnableController(svc.Object);
|
||||||
|
|
||||||
var result = await controller.Update("id", new UpdateSpawnableRequest { Name="n", SpawnRate=1, CollectAction="a" });
|
var result = await controller.Update("id", new UpdateSpawnableRequest { Name="n", SpawnRate=1, CollectAction="a", ConsumeOnSuccess = false });
|
||||||
|
|
||||||
Assert.IsType<NotFoundObjectResult>(result);
|
Assert.IsType<NotFoundObjectResult>(result);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,4 +5,7 @@ public class CreateItemRequest
|
|||||||
public string LocationId { get; set; }
|
public string LocationId { get; set; }
|
||||||
|
|
||||||
public string Name { get; set; }
|
public string Name { get; set; }
|
||||||
|
|
||||||
|
// Optional number of uses before the item is removed.
|
||||||
|
public int UsesRemaining { get; set; } = 0;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,4 +12,10 @@ public class CreateSpawnableRequest
|
|||||||
|
|
||||||
// Possible outcomes of collecting the item
|
// Possible outcomes of collecting the item
|
||||||
public List<CollectOutcome> CollectResults { get; set; } = [];
|
public List<CollectOutcome> CollectResults { get; set; } = [];
|
||||||
|
|
||||||
|
// Should the spawnable be removed after a successful action?
|
||||||
|
public bool ConsumeOnSuccess { get; set; } = false;
|
||||||
|
|
||||||
|
// Number of successful actions allowed before it disappears (0 for unlimited)
|
||||||
|
public int Uses { get; set; } = 0;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
namespace GameAuthApi.Models;
|
||||||
|
|
||||||
|
public class PasswordResetRequest
|
||||||
|
{
|
||||||
|
public string Login { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class PasswordResetConfirmRequest
|
||||||
|
{
|
||||||
|
public string Login { get; set; }
|
||||||
|
public string Code { get; set; }
|
||||||
|
public string NewPassword { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
namespace GameAuthApi.Models;
|
||||||
|
|
||||||
|
public class SteamCompleteRequest
|
||||||
|
{
|
||||||
|
public string TransactionId { get; set; }
|
||||||
|
public string Action { get; set; }
|
||||||
|
public string Username { get; set; }
|
||||||
|
public string Email { get; set; }
|
||||||
|
public string Password { get; set; }
|
||||||
|
}
|
||||||
@@ -4,4 +4,7 @@ public class UpdateItemRequest
|
|||||||
{
|
{
|
||||||
public string LocationId { get; set; }
|
public string LocationId { get; set; }
|
||||||
public string Name { get; set; }
|
public string Name { get; set; }
|
||||||
|
|
||||||
|
// Adjust remaining uses for the item
|
||||||
|
public int UsesRemaining { get; set; } = 0;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,4 +8,10 @@ public class UpdateSpawnableRequest
|
|||||||
public int SpawnRate { get; set; }
|
public int SpawnRate { get; set; }
|
||||||
public string CollectAction { get; set; }
|
public string CollectAction { get; set; }
|
||||||
public List<CollectOutcome> CollectResults { get; set; } = [];
|
public List<CollectOutcome> CollectResults { get; set; } = [];
|
||||||
|
|
||||||
|
// Should the spawnable be removed after a successful action?
|
||||||
|
public bool ConsumeOnSuccess { get; set; } = false;
|
||||||
|
|
||||||
|
// Number of successful actions allowed before it disappears (0 for unlimited)
|
||||||
|
public int Uses { get; set; } = 0;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
using MongoDB.Bson;
|
||||||
|
using MongoDB.Bson.Serialization.Attributes;
|
||||||
|
using System;
|
||||||
|
|
||||||
|
namespace GameAuthApi.Models;
|
||||||
|
|
||||||
|
public class ExternalIdentityLink
|
||||||
|
{
|
||||||
|
[BsonId]
|
||||||
|
[BsonRepresentation(BsonType.ObjectId)]
|
||||||
|
public string Id { get; set; }
|
||||||
|
public string Provider { get; set; }
|
||||||
|
public string Subject { get; set; }
|
||||||
|
public string UserId { get; set; }
|
||||||
|
public DateTime CreatedUtc { get; set; }
|
||||||
|
}
|
||||||
@@ -13,4 +13,7 @@ public class Item
|
|||||||
public string LocationId { get; set; }
|
public string LocationId { get; set; }
|
||||||
|
|
||||||
public string Name { get; set; }
|
public string Name { get; set; }
|
||||||
|
|
||||||
|
// Remaining uses before this item disappears. 0 means unlimited.
|
||||||
|
public int UsesRemaining { get; set; } = 0;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
using MongoDB.Bson;
|
||||||
|
using MongoDB.Bson.Serialization.Attributes;
|
||||||
|
using System;
|
||||||
|
|
||||||
|
namespace GameAuthApi.Models;
|
||||||
|
|
||||||
|
public class PasswordResetChallenge
|
||||||
|
{
|
||||||
|
[BsonId]
|
||||||
|
[BsonRepresentation(BsonType.ObjectId)]
|
||||||
|
public string Id { get; set; }
|
||||||
|
public string UserId { get; set; }
|
||||||
|
public string CodeHash { get; set; }
|
||||||
|
public int FailedAttempts { get; set; }
|
||||||
|
public DateTime ExpiresUtc { get; set; }
|
||||||
|
public DateTime CreatedUtc { get; set; }
|
||||||
|
public bool Used { get; set; }
|
||||||
|
}
|
||||||
@@ -21,4 +21,8 @@ public class Spawnable
|
|||||||
|
|
||||||
// If true, the spawnable item is removed after a successful action
|
// If true, the spawnable item is removed after a successful action
|
||||||
public bool ConsumeOnSuccess { get; set; } = false;
|
public bool ConsumeOnSuccess { get; set; } = false;
|
||||||
|
|
||||||
|
// Number of times this spawnable can be successfully acted upon
|
||||||
|
// before it is removed. A value of 0 means unlimited uses.
|
||||||
|
public int Uses { get; set; } = 0;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace GameAuthApi.Models;
|
||||||
|
|
||||||
|
public class SteamAuthTransaction
|
||||||
|
{
|
||||||
|
public string Id { get; set; }
|
||||||
|
public string Status { get; set; } = "pending";
|
||||||
|
public string SteamId { get; set; }
|
||||||
|
public string UserId { get; set; }
|
||||||
|
public string AccessToken { get; set; }
|
||||||
|
public string RefreshToken { get; set; }
|
||||||
|
public string Username { get; set; }
|
||||||
|
public string Role { get; set; }
|
||||||
|
public DateTime ExpiresUtc { get; set; }
|
||||||
|
public DateTime CreatedUtc { get; set; }
|
||||||
|
}
|
||||||
@@ -16,4 +16,6 @@ public class User
|
|||||||
public string RefreshToken { get; set; }
|
public string RefreshToken { get; set; }
|
||||||
public DateTime RefreshTokenExpiry { get; set; }
|
public DateTime RefreshTokenExpiry { get; set; }
|
||||||
public string Email { get; set; }
|
public string Email { get; set; }
|
||||||
|
public string NormalizedUsername { get; set; }
|
||||||
|
public string NormalizedEmail { get; set; }
|
||||||
}
|
}
|
||||||
+29
@@ -9,6 +9,8 @@ using Microsoft.Extensions.Hosting;
|
|||||||
using Microsoft.IdentityModel.Tokens;
|
using Microsoft.IdentityModel.Tokens;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using Microsoft.AspNetCore.Http;
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using System.Threading.RateLimiting;
|
||||||
|
using System;
|
||||||
|
|
||||||
var builder = WebApplication.CreateBuilder(args);
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
builder.WebHost.ConfigureKestrel(serverOptions => {});
|
builder.WebHost.ConfigureKestrel(serverOptions => {});
|
||||||
@@ -54,6 +56,23 @@ builder.Services.AddSingleton<ItemService>();
|
|||||||
builder.Services.AddSingleton<BlacklistService>();
|
builder.Services.AddSingleton<BlacklistService>();
|
||||||
builder.Services.AddSingleton<AuctionService>();
|
builder.Services.AddSingleton<AuctionService>();
|
||||||
builder.Services.AddSingleton<ChatService>();
|
builder.Services.AddSingleton<ChatService>();
|
||||||
|
builder.Services.AddSingleton<AdminService>();
|
||||||
|
builder.Services.AddSingleton<PasswordResetService>();
|
||||||
|
builder.Services.AddSingleton<EmailService>();
|
||||||
|
builder.Services.AddSingleton<SteamAuthService>();
|
||||||
|
builder.Services.AddHttpClient();
|
||||||
|
builder.Services.AddRateLimiter(options =>
|
||||||
|
{
|
||||||
|
options.AddPolicy("password-reset", context => RateLimitPartition.GetFixedWindowLimiter(
|
||||||
|
context.Connection.RemoteIpAddress?.ToString() ?? "unknown",
|
||||||
|
_ => new FixedWindowRateLimiterOptions
|
||||||
|
{
|
||||||
|
PermitLimit = 5,
|
||||||
|
Window = TimeSpan.FromMinutes(15),
|
||||||
|
QueueLimit = 0
|
||||||
|
}));
|
||||||
|
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
|
||||||
|
});
|
||||||
|
|
||||||
var jwtKey = builder.Configuration["Jwt:Key"];
|
var jwtKey = builder.Configuration["Jwt:Key"];
|
||||||
var keyBytes = Encoding.UTF8.GetBytes(jwtKey);
|
var keyBytes = Encoding.UTF8.GetBytes(jwtKey);
|
||||||
@@ -84,7 +103,9 @@ builder.Services.AddCors(options =>
|
|||||||
});
|
});
|
||||||
|
|
||||||
var app = builder.Build();
|
var app = builder.Build();
|
||||||
|
app.UseRouting();
|
||||||
app.UseCors("AllowAll");
|
app.UseCors("AllowAll");
|
||||||
|
app.UseRateLimiter();
|
||||||
|
|
||||||
// Enable OPTIONS requests to reach controllers
|
// Enable OPTIONS requests to reach controllers
|
||||||
app.Use(async (context, next) =>
|
app.Use(async (context, next) =>
|
||||||
@@ -108,4 +129,12 @@ app.UseAuthorization();
|
|||||||
|
|
||||||
app.MapControllers();
|
app.MapControllers();
|
||||||
|
|
||||||
|
using (var scope = app.Services.CreateScope())
|
||||||
|
{
|
||||||
|
var users = scope.ServiceProvider.GetRequiredService<UserService>();
|
||||||
|
await users.BackfillNormalizedFieldsAsync();
|
||||||
|
await users.EnsureIndexesAsync();
|
||||||
|
await scope.ServiceProvider.GetRequiredService<PasswordResetService>().EnsureIndexesAsync();
|
||||||
|
await scope.ServiceProvider.GetRequiredService<SteamAuthService>().EnsureIndexesAsync();
|
||||||
|
}
|
||||||
app.Run();
|
app.Run();
|
||||||
@@ -1,12 +1,14 @@
|
|||||||
# gameauthapi
|
# gameauthapi
|
||||||
|
|
||||||
# Deploy
|
## MedMind authentication configuration
|
||||||
- git pull
|
|
||||||
- dotnet publish -c Release
|
|
||||||
- sudo systemctl restart gameapi.service
|
|
||||||
|
|
||||||
# Check logs
|
Configure production values through environment variables (double underscores map to nested .NET settings):
|
||||||
journalctl -u gameapi.service -b --no-pager --lines=100
|
|
||||||
|
- `Auth__PublicBaseUrl=https://pauth.ranaze.com`
|
||||||
|
- `Email__SmtpHost`, `Email__SmtpPort`, `Email__UseTls`
|
||||||
|
- `Email__Username`, `Email__Password`, `Email__Sender`
|
||||||
|
|
||||||
|
The public base URL must be reachable by Steam and route `/api/Auth/steam/callback` to this service.
|
||||||
|
|
||||||
## Spawnables
|
## Spawnables
|
||||||
|
|
||||||
@@ -19,3 +21,4 @@ performs the required collect action.
|
|||||||
succeeds. Each entry defines:
|
succeeds. Each entry defines:
|
||||||
- **Result** – textual description of the outcome.
|
- **Result** – textual description of the outcome.
|
||||||
- **SuccessRate** – percentage chance (0-100) for that outcome.
|
- **SuccessRate** – percentage chance (0-100) for that outcome.
|
||||||
|
- **Uses** – optional number of times the item can be successfully acted on before being removed. `0` means it never expires unless `ConsumeOnSuccess` is `true`.
|
||||||
|
|||||||
@@ -0,0 +1,64 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using GameAuthApi.Models;
|
||||||
|
|
||||||
|
namespace GameAuthApi.Services;
|
||||||
|
|
||||||
|
public class AdminService
|
||||||
|
{
|
||||||
|
private readonly LocationService _locationService;
|
||||||
|
private readonly ItemService _itemService;
|
||||||
|
private readonly PlayerService _playerService;
|
||||||
|
|
||||||
|
public AdminService(LocationService locationService, ItemService itemService, PlayerService playerService)
|
||||||
|
{
|
||||||
|
_locationService = locationService;
|
||||||
|
_itemService = itemService;
|
||||||
|
_playerService = playerService;
|
||||||
|
}
|
||||||
|
|
||||||
|
public virtual Task<Dictionary<string, string>> GetStatusAsync()
|
||||||
|
{
|
||||||
|
var status = new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
{"status", "ok"}
|
||||||
|
};
|
||||||
|
return Task.FromResult(status);
|
||||||
|
}
|
||||||
|
|
||||||
|
public virtual async Task<Location> ResetLocationsAsync()
|
||||||
|
{
|
||||||
|
var worldLocations = await _locationService.GetByTypeAsync("World");
|
||||||
|
foreach (var loc in worldLocations)
|
||||||
|
{
|
||||||
|
await _itemService.DeleteByLocationAsync(loc.Id);
|
||||||
|
}
|
||||||
|
await _locationService.DeleteByTypeAsync("World");
|
||||||
|
|
||||||
|
var origin = new Location
|
||||||
|
{
|
||||||
|
LocationType = "World",
|
||||||
|
X = 0,
|
||||||
|
Y = 0,
|
||||||
|
Z = 0
|
||||||
|
};
|
||||||
|
await _locationService.CreateAsync(origin);
|
||||||
|
|
||||||
|
var players = await _playerService.GetAllAsync();
|
||||||
|
foreach (var player in players)
|
||||||
|
{
|
||||||
|
player.LocationId = origin.Id;
|
||||||
|
await _playerService.UpdateAsync(player);
|
||||||
|
await _locationService.AddPlayerToLocationAsync(origin.Id, player.Id);
|
||||||
|
}
|
||||||
|
|
||||||
|
return origin;
|
||||||
|
}
|
||||||
|
|
||||||
|
public virtual async Task ClearItemsAsync()
|
||||||
|
{
|
||||||
|
await _itemService.DeleteAllAsync();
|
||||||
|
await _locationService.ClearAllItemsAsync();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Net.Mail;
|
||||||
|
using System;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
|
||||||
|
namespace GameAuthApi.Services;
|
||||||
|
|
||||||
|
public class EmailService
|
||||||
|
{
|
||||||
|
private readonly IConfiguration _config;
|
||||||
|
|
||||||
|
public EmailService(IConfiguration config) => _config = config;
|
||||||
|
|
||||||
|
public virtual async Task SendPasswordResetCodeAsync(string recipient, string code)
|
||||||
|
{
|
||||||
|
var host = _config["Email:SmtpHost"];
|
||||||
|
var sender = _config["Email:Sender"];
|
||||||
|
if (string.IsNullOrWhiteSpace(host) || string.IsNullOrWhiteSpace(sender))
|
||||||
|
throw new InvalidOperationException("SMTP email delivery is not configured.");
|
||||||
|
|
||||||
|
using var message = new MailMessage(sender, recipient)
|
||||||
|
{
|
||||||
|
Subject = "Your MedMind password reset code",
|
||||||
|
Body = $"Your MedMind verification code is {code}. It expires in 15 minutes. If you did not request this, you can ignore this email.",
|
||||||
|
IsBodyHtml = false
|
||||||
|
};
|
||||||
|
using var client = new SmtpClient(host, int.TryParse(_config["Email:SmtpPort"], out var port) ? port : 587)
|
||||||
|
{
|
||||||
|
EnableSsl = !bool.TryParse(_config["Email:UseTls"], out var tls) || tls
|
||||||
|
};
|
||||||
|
var username = _config["Email:Username"];
|
||||||
|
if (!string.IsNullOrWhiteSpace(username))
|
||||||
|
client.Credentials = new NetworkCredential(username, _config["Email:Password"]);
|
||||||
|
await client.SendMailAsync(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -44,4 +44,14 @@ public class ItemService
|
|||||||
{
|
{
|
||||||
await _items.DeleteOneAsync(i => i.Id == id);
|
await _items.DeleteOneAsync(i => i.Id == id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public virtual async Task DeleteByLocationAsync(string locationId)
|
||||||
|
{
|
||||||
|
await _items.DeleteManyAsync(i => i.LocationId == locationId);
|
||||||
|
}
|
||||||
|
|
||||||
|
public virtual async Task DeleteAllAsync()
|
||||||
|
{
|
||||||
|
await _items.DeleteManyAsync(_ => true);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
using System.Collections.Generic;
|
||||||
using GameAuthApi.Models;
|
using GameAuthApi.Models;
|
||||||
using Microsoft.Extensions.Configuration;
|
using Microsoft.Extensions.Configuration;
|
||||||
using MongoDB.Bson;
|
using MongoDB.Bson;
|
||||||
@@ -30,6 +31,17 @@ public class LocationService
|
|||||||
|
|
||||||
public virtual async Task DeleteAsync(string id) =>
|
public virtual async Task DeleteAsync(string id) =>
|
||||||
await _locations.DeleteOneAsync(loc => loc.Id == id);
|
await _locations.DeleteOneAsync(loc => loc.Id == id);
|
||||||
|
|
||||||
|
public virtual async Task<List<Location>> GetByTypeAsync(string type)
|
||||||
|
{
|
||||||
|
return await _locations.Find(l => l.LocationType == type).ToListAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
public virtual async Task DeleteByTypeAsync(string type) =>
|
||||||
|
await _locations.DeleteManyAsync(l => l.LocationType == type);
|
||||||
|
|
||||||
|
public virtual async Task DeleteAllAsync() =>
|
||||||
|
await _locations.DeleteManyAsync(_ => true);
|
||||||
public virtual async Task UpdateAsync(Location loc) =>
|
public virtual async Task UpdateAsync(Location loc) =>
|
||||||
await _locations.ReplaceOneAsync(l => l.Id == loc.Id, loc);
|
await _locations.ReplaceOneAsync(l => l.Id == loc.Id, loc);
|
||||||
|
|
||||||
@@ -57,13 +69,35 @@ public class LocationService
|
|||||||
|
|
||||||
public virtual async Task AddItemToLocationAsync(string locationId, string itemId)
|
public virtual async Task AddItemToLocationAsync(string locationId, string itemId)
|
||||||
{
|
{
|
||||||
|
if (!ObjectId.TryParse(locationId, out _) || !ObjectId.TryParse(itemId, out _))
|
||||||
|
return;
|
||||||
|
|
||||||
|
var idFilter = Builders<Location>.Filter.Eq(l => l.Id, locationId);
|
||||||
|
|
||||||
|
// if the Content array is null, initialize it first
|
||||||
|
// use a raw BsonDocument filter to avoid casting BsonNull to an ObjectId
|
||||||
|
var nullFilter = idFilter & new BsonDocument("Content", BsonNull.Value);
|
||||||
|
var initArray = Builders<Location>.Update.Set(l => l.Content, new List<string>());
|
||||||
|
await _locations.UpdateOneAsync(nullFilter, initArray);
|
||||||
|
|
||||||
var update = Builders<Location>.Update.Push(l => l.Content, itemId);
|
var update = Builders<Location>.Update.Push(l => l.Content, itemId);
|
||||||
await _locations.UpdateOneAsync(l => l.Id == locationId, update);
|
await _locations.UpdateOneAsync(idFilter, update);
|
||||||
}
|
}
|
||||||
|
|
||||||
public virtual async Task RemoveItemFromLocationAsync(string locationId, string itemId)
|
public virtual async Task RemoveItemFromLocationAsync(string locationId, string itemId)
|
||||||
{
|
{
|
||||||
|
if (!ObjectId.TryParse(locationId, out _) || !ObjectId.TryParse(itemId, out _))
|
||||||
|
return;
|
||||||
|
|
||||||
|
// check that the Content array exists by using a raw BsonDocument filter
|
||||||
|
var filter = Builders<Location>.Filter.Eq(l => l.Id, locationId) & new BsonDocument("Content", new BsonDocument("$ne", BsonNull.Value));
|
||||||
var update = Builders<Location>.Update.Pull(l => l.Content, itemId);
|
var update = Builders<Location>.Update.Pull(l => l.Content, itemId);
|
||||||
await _locations.UpdateOneAsync(l => l.Id == locationId, update);
|
await _locations.UpdateOneAsync(filter, update);
|
||||||
|
}
|
||||||
|
|
||||||
|
public virtual async Task ClearAllItemsAsync()
|
||||||
|
{
|
||||||
|
var update = Builders<Location>.Update.Set(l => l.Content, new List<string>());
|
||||||
|
await _locations.UpdateManyAsync(_ => true, update);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,57 @@
|
|||||||
|
using System.Security.Cryptography;
|
||||||
|
using GameAuthApi.Models;
|
||||||
|
using MongoDB.Driver;
|
||||||
|
using System;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
|
||||||
|
namespace GameAuthApi.Services;
|
||||||
|
|
||||||
|
public class PasswordResetService
|
||||||
|
{
|
||||||
|
private readonly IMongoCollection<PasswordResetChallenge> _challenges;
|
||||||
|
|
||||||
|
public PasswordResetService(IConfiguration config)
|
||||||
|
{
|
||||||
|
var client = new MongoClient(config["MongoDB:ConnectionString"]);
|
||||||
|
var database = client.GetDatabase(config["MongoDB:DatabaseName"]);
|
||||||
|
_challenges = database.GetCollection<PasswordResetChallenge>("PasswordResetChallenges");
|
||||||
|
}
|
||||||
|
|
||||||
|
public virtual async Task<string> CreateAsync(string userId)
|
||||||
|
{
|
||||||
|
await _challenges.UpdateManyAsync(x => x.UserId == userId && !x.Used,
|
||||||
|
Builders<PasswordResetChallenge>.Update.Set(x => x.Used, true));
|
||||||
|
var code = RandomNumberGenerator.GetInt32(0, 1_000_000).ToString("D6");
|
||||||
|
await _challenges.InsertOneAsync(new PasswordResetChallenge
|
||||||
|
{
|
||||||
|
UserId = userId,
|
||||||
|
CodeHash = BCrypt.Net.BCrypt.HashPassword(code),
|
||||||
|
CreatedUtc = DateTime.UtcNow,
|
||||||
|
ExpiresUtc = DateTime.UtcNow.AddMinutes(15)
|
||||||
|
});
|
||||||
|
return code;
|
||||||
|
}
|
||||||
|
|
||||||
|
public virtual async Task<bool> ConsumeAsync(string userId, string code)
|
||||||
|
{
|
||||||
|
var challenge = await _challenges.Find(x => x.UserId == userId && !x.Used && x.ExpiresUtc > DateTime.UtcNow)
|
||||||
|
.SortByDescending(x => x.CreatedUtc).FirstOrDefaultAsync();
|
||||||
|
if (challenge == null || challenge.FailedAttempts >= 5)
|
||||||
|
return false;
|
||||||
|
if (!BCrypt.Net.BCrypt.Verify(code, challenge.CodeHash))
|
||||||
|
{
|
||||||
|
await _challenges.UpdateOneAsync(x => x.Id == challenge.Id,
|
||||||
|
Builders<PasswordResetChallenge>.Update.Inc(x => x.FailedAttempts, 1));
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
await _challenges.UpdateOneAsync(x => x.Id == challenge.Id,
|
||||||
|
Builders<PasswordResetChallenge>.Update.Set(x => x.Used, true));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task EnsureIndexesAsync() => await _challenges.Indexes.CreateOneAsync(
|
||||||
|
new CreateIndexModel<PasswordResetChallenge>(
|
||||||
|
Builders<PasswordResetChallenge>.IndexKeys.Ascending(x => x.ExpiresUtc),
|
||||||
|
new CreateIndexOptions { ExpireAfter = TimeSpan.Zero, Name = "password_reset_ttl" }));
|
||||||
|
}
|
||||||
@@ -29,6 +29,11 @@ public class PlayerService
|
|||||||
public virtual async Task<Player> GetByIdAsync(string id) =>
|
public virtual async Task<Player> GetByIdAsync(string id) =>
|
||||||
await _players.Find(p => p.Id == id).FirstOrDefaultAsync();
|
await _players.Find(p => p.Id == id).FirstOrDefaultAsync();
|
||||||
|
|
||||||
|
public virtual async Task<List<Player>> GetAllAsync()
|
||||||
|
{
|
||||||
|
return await _players.Find(_ => true).ToListAsync();
|
||||||
|
}
|
||||||
|
|
||||||
public virtual async Task CreateAsync(Player player) =>
|
public virtual async Task CreateAsync(Player player) =>
|
||||||
await _players.InsertOneAsync(player);
|
await _players.InsertOneAsync(player);
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,111 @@
|
|||||||
|
using System.Security.Cryptography;
|
||||||
|
using GameAuthApi.Models;
|
||||||
|
using MongoDB.Driver;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Net.Http;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
|
||||||
|
namespace GameAuthApi.Services;
|
||||||
|
|
||||||
|
public class SteamAuthService
|
||||||
|
{
|
||||||
|
private const string Provider = "steam";
|
||||||
|
private readonly IMongoCollection<SteamAuthTransaction> _transactions;
|
||||||
|
private readonly IMongoCollection<ExternalIdentityLink> _links;
|
||||||
|
private readonly IConfiguration _config;
|
||||||
|
private readonly HttpClient _http;
|
||||||
|
|
||||||
|
public SteamAuthService(IConfiguration config, IHttpClientFactory factory)
|
||||||
|
{
|
||||||
|
_config = config;
|
||||||
|
_http = factory.CreateClient();
|
||||||
|
var client = new MongoClient(config["MongoDB:ConnectionString"]);
|
||||||
|
var database = client.GetDatabase(config["MongoDB:DatabaseName"]);
|
||||||
|
_transactions = database.GetCollection<SteamAuthTransaction>("SteamAuthTransactions");
|
||||||
|
_links = database.GetCollection<ExternalIdentityLink>("ExternalIdentityLinks");
|
||||||
|
}
|
||||||
|
|
||||||
|
public virtual async Task<(SteamAuthTransaction Transaction, string AuthUrl)> StartAsync()
|
||||||
|
{
|
||||||
|
var id = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)).ToLowerInvariant();
|
||||||
|
var transaction = new SteamAuthTransaction { Id = id, CreatedUtc = DateTime.UtcNow, ExpiresUtc = DateTime.UtcNow.AddMinutes(10) };
|
||||||
|
await _transactions.InsertOneAsync(transaction);
|
||||||
|
var baseUrl = (_config["Auth:PublicBaseUrl"] ?? "https://pauth.ranaze.com").TrimEnd('/');
|
||||||
|
var returnTo = $"{baseUrl}/api/Auth/steam/callback?transactionId={Uri.EscapeDataString(id)}";
|
||||||
|
var realm = baseUrl + "/";
|
||||||
|
var query = new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["openid.ns"] = "http://specs.openid.net/auth/2.0",
|
||||||
|
["openid.mode"] = "checkid_setup",
|
||||||
|
["openid.return_to"] = returnTo,
|
||||||
|
["openid.realm"] = realm,
|
||||||
|
["openid.identity"] = "http://specs.openid.net/auth/2.0/identifier_select",
|
||||||
|
["openid.claimed_id"] = "http://specs.openid.net/auth/2.0/identifier_select"
|
||||||
|
};
|
||||||
|
var authUrl = "https://steamcommunity.com/openid/login?" + string.Join("&", query.Select(x => $"{Uri.EscapeDataString(x.Key)}={Uri.EscapeDataString(x.Value)}"));
|
||||||
|
return (transaction, authUrl);
|
||||||
|
}
|
||||||
|
|
||||||
|
public virtual async Task<SteamAuthTransaction> GetAsync(string id) =>
|
||||||
|
await _transactions.Find(x => x.Id == id && x.ExpiresUtc > DateTime.UtcNow).FirstOrDefaultAsync();
|
||||||
|
|
||||||
|
public virtual async Task<bool> VerifyCallbackAsync(string transactionId, IQueryCollection query)
|
||||||
|
{
|
||||||
|
var transaction = await GetAsync(transactionId);
|
||||||
|
if (transaction == null) return false;
|
||||||
|
var payload = query.Where(x => x.Key.StartsWith("openid.")).ToDictionary(x => x.Key, x => x.Value.ToString());
|
||||||
|
payload["openid.mode"] = "check_authentication";
|
||||||
|
using var response = await _http.PostAsync("https://steamcommunity.com/openid/login", new FormUrlEncodedContent(payload));
|
||||||
|
var result = await response.Content.ReadAsStringAsync();
|
||||||
|
if (!response.IsSuccessStatusCode || !result.Contains("is_valid:true", StringComparison.Ordinal)) return false;
|
||||||
|
var claimed = query["openid.claimed_id"].ToString();
|
||||||
|
const string prefix = "https://steamcommunity.com/openid/id/";
|
||||||
|
if (!claimed.StartsWith(prefix, StringComparison.Ordinal) || !claimed[prefix.Length..].All(char.IsDigit)) return false;
|
||||||
|
var steamId = claimed[prefix.Length..];
|
||||||
|
var link = await _links.Find(x => x.Provider == Provider && x.Subject == steamId).FirstOrDefaultAsync();
|
||||||
|
await _transactions.UpdateOneAsync(x => x.Id == transactionId,
|
||||||
|
Builders<SteamAuthTransaction>.Update
|
||||||
|
.Set(x => x.SteamId, steamId)
|
||||||
|
.Set(x => x.UserId, link?.UserId)
|
||||||
|
.Set(x => x.Status, link == null ? "requires_account" : "authenticated"));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public virtual async Task LinkAsync(string transactionId, string userId)
|
||||||
|
{
|
||||||
|
var transaction = await GetAsync(transactionId) ?? throw new InvalidOperationException("Steam transaction expired.");
|
||||||
|
if (transaction.Status != "requires_account" || string.IsNullOrWhiteSpace(transaction.SteamId))
|
||||||
|
throw new InvalidOperationException("Steam transaction is not ready.");
|
||||||
|
await _links.InsertOneAsync(new ExternalIdentityLink
|
||||||
|
{
|
||||||
|
Provider = Provider, Subject = transaction.SteamId, UserId = userId, CreatedUtc = DateTime.UtcNow
|
||||||
|
});
|
||||||
|
await _transactions.UpdateOneAsync(x => x.Id == transactionId,
|
||||||
|
Builders<SteamAuthTransaction>.Update.Set(x => x.UserId, userId).Set(x => x.Status, "authenticated"));
|
||||||
|
}
|
||||||
|
|
||||||
|
public virtual async Task CompleteAsync(string transactionId, User user, string accessToken, string refreshToken)
|
||||||
|
{
|
||||||
|
await _transactions.UpdateOneAsync(x => x.Id == transactionId,
|
||||||
|
Builders<SteamAuthTransaction>.Update
|
||||||
|
.Set(x => x.Status, "complete")
|
||||||
|
.Set(x => x.AccessToken, accessToken)
|
||||||
|
.Set(x => x.RefreshToken, refreshToken)
|
||||||
|
.Set(x => x.Username, user.Username)
|
||||||
|
.Set(x => x.Role, user.Role));
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task EnsureIndexesAsync()
|
||||||
|
{
|
||||||
|
await _transactions.Indexes.CreateOneAsync(new CreateIndexModel<SteamAuthTransaction>(
|
||||||
|
Builders<SteamAuthTransaction>.IndexKeys.Ascending(x => x.ExpiresUtc),
|
||||||
|
new CreateIndexOptions { ExpireAfter = TimeSpan.Zero, Name = "steam_transaction_ttl" }));
|
||||||
|
await _links.Indexes.CreateOneAsync(new CreateIndexModel<ExternalIdentityLink>(
|
||||||
|
Builders<ExternalIdentityLink>.IndexKeys.Ascending(x => x.Provider).Ascending(x => x.Subject),
|
||||||
|
new CreateIndexOptions { Unique = true, Name = "external_identity_unique" }));
|
||||||
|
}
|
||||||
|
}
|
||||||
+60
-2
@@ -3,6 +3,8 @@ using System.Threading.Tasks;
|
|||||||
using GameAuthApi.Models;
|
using GameAuthApi.Models;
|
||||||
using Microsoft.Extensions.Configuration;
|
using Microsoft.Extensions.Configuration;
|
||||||
using MongoDB.Driver;
|
using MongoDB.Driver;
|
||||||
|
using System;
|
||||||
|
using System.Linq;
|
||||||
|
|
||||||
namespace GameAuthApi.Services;
|
namespace GameAuthApi.Services;
|
||||||
|
|
||||||
@@ -20,6 +22,19 @@ public class UserService
|
|||||||
public virtual async Task<User> GetByUsernameAsync(string username) =>
|
public virtual async Task<User> GetByUsernameAsync(string username) =>
|
||||||
await _users.Find(u => u.Username == username).FirstOrDefaultAsync();
|
await _users.Find(u => u.Username == username).FirstOrDefaultAsync();
|
||||||
|
|
||||||
|
public virtual async Task<User> GetByLoginAsync(string login)
|
||||||
|
{
|
||||||
|
var normalized = Normalize(login);
|
||||||
|
return await _users.Find(u =>
|
||||||
|
u.NormalizedUsername == normalized ||
|
||||||
|
u.NormalizedEmail == normalized ||
|
||||||
|
u.Username == login ||
|
||||||
|
u.Email == login).FirstOrDefaultAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
public virtual async Task<User> GetByIdAsync(string id) =>
|
||||||
|
await _users.Find(u => u.Id == id).FirstOrDefaultAsync();
|
||||||
|
|
||||||
public virtual async Task<List<User>> GetAllAsync() =>
|
public virtual async Task<List<User>> GetAllAsync() =>
|
||||||
await _users.Find(_ => true).ToListAsync();
|
await _users.Find(_ => true).ToListAsync();
|
||||||
|
|
||||||
@@ -29,9 +44,52 @@ public class UserService
|
|||||||
return result.DeletedCount > 0;
|
return result.DeletedCount > 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
public virtual async Task CreateAsync(User user) =>
|
public virtual async Task CreateAsync(User user)
|
||||||
|
{
|
||||||
|
ApplyNormalizedFields(user);
|
||||||
await _users.InsertOneAsync(user);
|
await _users.InsertOneAsync(user);
|
||||||
|
}
|
||||||
|
|
||||||
public virtual async Task UpdateAsync(User user) =>
|
public virtual async Task UpdateAsync(User user)
|
||||||
|
{
|
||||||
|
ApplyNormalizedFields(user);
|
||||||
await _users.ReplaceOneAsync(u => u.Id == user.Id, user);
|
await _users.ReplaceOneAsync(u => u.Id == user.Id, user);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public virtual async Task EnsureIndexesAsync()
|
||||||
|
{
|
||||||
|
var username = new CreateIndexModel<User>(
|
||||||
|
Builders<User>.IndexKeys.Ascending(u => u.NormalizedUsername),
|
||||||
|
new CreateIndexOptions { Unique = true, Sparse = true, Name = "normalized_username_unique" });
|
||||||
|
var email = new CreateIndexModel<User>(
|
||||||
|
Builders<User>.IndexKeys.Ascending(u => u.NormalizedEmail),
|
||||||
|
new CreateIndexOptions { Unique = true, Sparse = true, Name = "normalized_email_unique" });
|
||||||
|
await _users.Indexes.CreateManyAsync(new[] { username, email });
|
||||||
|
}
|
||||||
|
|
||||||
|
public virtual async Task BackfillNormalizedFieldsAsync()
|
||||||
|
{
|
||||||
|
var users = await _users.Find(_ => true).ToListAsync();
|
||||||
|
var duplicateUsername = users.GroupBy(u => Normalize(u.Username)).FirstOrDefault(g => g.Key != string.Empty && g.Count() > 1);
|
||||||
|
var duplicateEmail = users.Where(u => !string.IsNullOrWhiteSpace(u.Email)).GroupBy(u => Normalize(u.Email)).FirstOrDefault(g => g.Count() > 1);
|
||||||
|
if (duplicateUsername != null || duplicateEmail != null)
|
||||||
|
throw new InvalidOperationException("Duplicate normalized usernames or emails must be resolved before starting the authentication service.");
|
||||||
|
foreach (var user in users)
|
||||||
|
{
|
||||||
|
var normalizedUsername = Normalize(user.Username);
|
||||||
|
var normalizedEmail = string.IsNullOrWhiteSpace(user.Email) ? null : Normalize(user.Email);
|
||||||
|
if (user.NormalizedUsername == normalizedUsername && user.NormalizedEmail == normalizedEmail) continue;
|
||||||
|
user.NormalizedUsername = normalizedUsername;
|
||||||
|
user.NormalizedEmail = normalizedEmail;
|
||||||
|
await _users.ReplaceOneAsync(u => u.Id == user.Id, user);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string Normalize(string value) => value?.Trim().ToUpperInvariant() ?? string.Empty;
|
||||||
|
|
||||||
|
private static void ApplyNormalizedFields(User user)
|
||||||
|
{
|
||||||
|
user.NormalizedUsername = Normalize(user.Username);
|
||||||
|
user.NormalizedEmail = string.IsNullOrWhiteSpace(user.Email) ? null : Normalize(user.Email);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user