Recommiting glbs for LFS
Deploy Promiscuity Auth API / deploy (push) Successful in 1m59s
Deploy Promiscuity Character API / deploy (push) Successful in 1m16s
Deploy Promiscuity Inventory API / deploy (push) Has been cancelled
Deploy Promiscuity Locations API / deploy (push) Has been cancelled
Deploy Promiscuity Mail API / deploy (push) Has been cancelled
Deploy Promiscuity World API / deploy (push) Has been cancelled
Deploy Promiscuity Crafting API / deploy (push) Has been cancelled
k8s smoke test / test (push) Has been cancelled

This commit is contained in:
2026-05-12 15:34:12 -05:00
parent a9e546a121
commit fecbefc15c
141 changed files with 7099 additions and 2601 deletions
+17 -17
View File
@@ -1,17 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Bcrypt.Net-Next" Version="4.0.3" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.8" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.8" />
<PackageReference Include="MongoDB.Driver" Version="3.4.3" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
</ItemGroup>
</Project>
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Bcrypt.Net-Next" Version="4.0.3" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.8" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.8" />
<PackageReference Include="MongoDB.Driver" Version="3.4.3" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
</ItemGroup>
</Project>
@@ -1,113 +1,113 @@
using AuthApi.Models;
using AuthApi.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
namespace AuthApi.Controllers;
[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
private readonly UserService _users;
private readonly IConfiguration _cfg;
private readonly BlacklistService _blacklist;
public AuthController(UserService users, IConfiguration cfg, BlacklistService blacklist)
{
_users = users; _cfg = cfg; _blacklist = blacklist;
}
[HttpPost("register")]
public async Task<IActionResult> Register([FromBody] RegisterRequest req)
{
if (string.IsNullOrWhiteSpace(req.Username) || string.IsNullOrWhiteSpace(req.Password))
return BadRequest("Username and password required");
if (await _users.GetByUsernameAsync(req.Username) != null)
return BadRequest("User already exists");
var hash = BCrypt.Net.BCrypt.HashPassword(req.Password);
var user = new User { Username = req.Username, PasswordHash = hash, Role = "USER", Email = req.Email };
await _users.CreateAsync(user);
return Ok("User created");
}
[HttpPost("login")]
public async Task<IActionResult> Login([FromBody] LoginRequest req)
{
var user = await _users.GetByUsernameAsync(req.Username);
if (user == null || !BCrypt.Net.BCrypt.Verify(req.Password, user.PasswordHash))
return Unauthorized();
var (accessToken, jti, expUtc) = GenerateJwtToken(user);
user.RefreshToken = Guid.NewGuid().ToString("N");
user.RefreshTokenExpiry = DateTime.UtcNow.AddDays(7);
await _users.UpdateAsync(user);
return Ok(new { accessToken, refreshToken = user.RefreshToken, user.Username, user.Role, jti, exp = expUtc });
}
[HttpPost("refresh")]
public async Task<IActionResult> Refresh([FromBody] RefreshRequest req)
{
var user = await _users.GetByUsernameAsync(req.Username);
if (user == null || user.RefreshToken != req.RefreshToken || user.RefreshTokenExpiry < DateTime.UtcNow)
return Unauthorized("Invalid or expired refresh token");
var (accessToken, _, expUtc) = GenerateJwtToken(user);
return Ok(new { accessToken, exp = expUtc });
}
[HttpPost("logout")]
[Authorize(Roles = "USER,SUPER")]
public async Task<IActionResult> Logout()
{
var token = HttpContext.Request.Headers["Authorization"].FirstOrDefault()?.Replace("Bearer ", "");
if (string.IsNullOrWhiteSpace(token)) return BadRequest("Token missing");
var jwt = new JwtSecurityTokenHandler().ReadJwtToken(token);
await _blacklist.AddToBlacklistAsync(jwt.Id, jwt.ValidTo);
return Ok("Logged out.");
}
[HttpPost("role")]
[Authorize(Roles = "SUPER")]
public async Task<IActionResult> ChangeUserRole([FromBody] ChangeRoleRequest req)
{
if (req.NewRole is not ("USER" or "SUPER")) return BadRequest("Role must be 'USER' or 'SUPER'");
var user = await _users.GetByUsernameAsync(req.Username);
if (user is null) return NotFound("User not found");
user.Role = req.NewRole;
await _users.UpdateAsync(user);
return Ok($"{req.Username}'s role updated to {req.NewRole}");
}
[HttpGet("users")]
[Authorize(Roles = "SUPER")]
public async Task<IActionResult> GetAllUsers() => Ok(await _users.GetAllAsync());
private (string token, string jti, DateTime expUtc) GenerateJwtToken(User user)
{
var key = Encoding.UTF8.GetBytes(_cfg["Jwt:Key"]!);
var issuer = _cfg["Jwt:Issuer"] ?? "GameAuthApi";
var audience = _cfg["Jwt:Audience"] ?? issuer;
var creds = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256);
var jti = Guid.NewGuid().ToString("N");
var claims = new[]
{
new Claim(ClaimTypes.Name, user.Username),
new Claim(ClaimTypes.NameIdentifier, user.Id),
new Claim(ClaimTypes.Role, user.Role),
new Claim(JwtRegisteredClaimNames.Jti, jti)
};
var exp = DateTime.UtcNow.AddMinutes(15);
var token = new JwtSecurityToken(issuer, audience, claims, expires: exp, signingCredentials: creds);
return (new JwtSecurityTokenHandler().WriteToken(token), jti, exp);
}
}
using AuthApi.Models;
using AuthApi.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
namespace AuthApi.Controllers;
[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
private readonly UserService _users;
private readonly IConfiguration _cfg;
private readonly BlacklistService _blacklist;
public AuthController(UserService users, IConfiguration cfg, BlacklistService blacklist)
{
_users = users; _cfg = cfg; _blacklist = blacklist;
}
[HttpPost("register")]
public async Task<IActionResult> Register([FromBody] RegisterRequest req)
{
if (string.IsNullOrWhiteSpace(req.Username) || string.IsNullOrWhiteSpace(req.Password))
return BadRequest("Username and password required");
if (await _users.GetByUsernameAsync(req.Username) != null)
return BadRequest("User already exists");
var hash = BCrypt.Net.BCrypt.HashPassword(req.Password);
var user = new User { Username = req.Username, PasswordHash = hash, Role = "USER", Email = req.Email };
await _users.CreateAsync(user);
return Ok("User created");
}
[HttpPost("login")]
public async Task<IActionResult> Login([FromBody] LoginRequest req)
{
var user = await _users.GetByUsernameAsync(req.Username);
if (user == null || !BCrypt.Net.BCrypt.Verify(req.Password, user.PasswordHash))
return Unauthorized();
var (accessToken, jti, expUtc) = GenerateJwtToken(user);
user.RefreshToken = Guid.NewGuid().ToString("N");
user.RefreshTokenExpiry = DateTime.UtcNow.AddDays(7);
await _users.UpdateAsync(user);
return Ok(new { accessToken, refreshToken = user.RefreshToken, user.Username, user.Role, jti, exp = expUtc });
}
[HttpPost("refresh")]
public async Task<IActionResult> Refresh([FromBody] RefreshRequest req)
{
var user = await _users.GetByUsernameAsync(req.Username);
if (user == null || user.RefreshToken != req.RefreshToken || user.RefreshTokenExpiry < DateTime.UtcNow)
return Unauthorized("Invalid or expired refresh token");
var (accessToken, _, expUtc) = GenerateJwtToken(user);
return Ok(new { accessToken, exp = expUtc });
}
[HttpPost("logout")]
[Authorize(Roles = "USER,SUPER")]
public async Task<IActionResult> Logout()
{
var token = HttpContext.Request.Headers["Authorization"].FirstOrDefault()?.Replace("Bearer ", "");
if (string.IsNullOrWhiteSpace(token)) return BadRequest("Token missing");
var jwt = new JwtSecurityTokenHandler().ReadJwtToken(token);
await _blacklist.AddToBlacklistAsync(jwt.Id, jwt.ValidTo);
return Ok("Logged out.");
}
[HttpPost("role")]
[Authorize(Roles = "SUPER")]
public async Task<IActionResult> ChangeUserRole([FromBody] ChangeRoleRequest req)
{
if (req.NewRole is not ("USER" or "SUPER")) return BadRequest("Role must be 'USER' or 'SUPER'");
var user = await _users.GetByUsernameAsync(req.Username);
if (user is null) return NotFound("User not found");
user.Role = req.NewRole;
await _users.UpdateAsync(user);
return Ok($"{req.Username}'s role updated to {req.NewRole}");
}
[HttpGet("users")]
[Authorize(Roles = "SUPER")]
public async Task<IActionResult> GetAllUsers() => Ok(await _users.GetAllAsync());
private (string token, string jti, DateTime expUtc) GenerateJwtToken(User user)
{
var key = Encoding.UTF8.GetBytes(_cfg["Jwt:Key"]!);
var issuer = _cfg["Jwt:Issuer"] ?? "GameAuthApi";
var audience = _cfg["Jwt:Audience"] ?? issuer;
var creds = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256);
var jti = Guid.NewGuid().ToString("N");
var claims = new[]
{
new Claim(ClaimTypes.Name, user.Username),
new Claim(ClaimTypes.NameIdentifier, user.Id),
new Claim(ClaimTypes.Role, user.Role),
new Claim(JwtRegisteredClaimNames.Jti, jti)
};
var exp = DateTime.UtcNow.AddMinutes(15);
var token = new JwtSecurityToken(issuer, audience, claims, expires: exp, signingCredentials: creds);
return (new JwtSecurityTokenHandler().WriteToken(token), jti, exp);
}
}
+6 -6
View File
@@ -1,6 +1,6 @@
namespace AuthApi.Models;
public class RegisterRequest { public string Username { get; set; } = ""; public string Password { get; set; } = ""; public string? Email { get; set; } }
public class LoginRequest { public string Username { get; set; } = ""; public string Password { get; set; } = ""; }
public class ChangeRoleRequest { public string Username { get; set; } = ""; public string NewRole { get; set; } = ""; }
public class RefreshRequest { public string Username { get; set; } = ""; public string RefreshToken { get; set; } = ""; }
namespace AuthApi.Models;
public class RegisterRequest { public string Username { get; set; } = ""; public string Password { get; set; } = ""; public string? Email { get; set; } }
public class LoginRequest { public string Username { get; set; } = ""; public string Password { get; set; } = ""; }
public class ChangeRoleRequest { public string Username { get; set; } = ""; public string NewRole { get; set; } = ""; }
public class RefreshRequest { public string Username { get; set; } = ""; public string RefreshToken { get; set; } = ""; }
+16 -16
View File
@@ -1,16 +1,16 @@
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
namespace AuthApi.Models;
public class User
{
[BsonId] [BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; } = default!;
public string Username { get; set; } = default!;
public string PasswordHash { get; set; } = default!;
public string Role { get; set; } = "USER";
public string? Email { get; set; }
public string? RefreshToken { get; set; }
public DateTime? RefreshTokenExpiry { get; set; }
}
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
namespace AuthApi.Models;
public class User
{
[BsonId] [BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; } = default!;
public string Username { get; set; } = default!;
public string PasswordHash { get; set; } = default!;
public string Role { get; set; } = "USER";
public string? Email { get; set; }
public string? RefreshToken { get; set; }
public DateTime? RefreshTokenExpiry { get; set; }
}
+86 -86
View File
@@ -1,86 +1,86 @@
using AuthApi.Services;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System.Security.Claims;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
// DI
builder.Services.AddSingleton<UserService>();
builder.Services.AddSingleton<BlacklistService>();
// Swagger + JWT auth in Swagger
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Auth API", Version = "v1" });
c.AddSecurityDefinition("bearerAuth", new OpenApiSecurityScheme
{
Type = SecuritySchemeType.Http,
Scheme = "bearer",
BearerFormat = "JWT",
Description = "Paste your access token here (no 'Bearer ' prefix needed)."
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{ Type = ReferenceType.SecurityScheme, Id = "bearerAuth" }
},
Array.Empty<string>()
}
});
});
// AuthN/JWT
var cfg = builder.Configuration;
var jwtKey = cfg["Jwt:Key"] ?? throw new Exception("Jwt:Key missing");
var issuer = cfg["Jwt:Issuer"] ?? "GameAuthApi";
var aud = cfg["Jwt:Audience"] ?? issuer;
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(o =>
{
o.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true, ValidIssuer = issuer,
ValidateAudience = true, ValidAudience = aud,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey)),
ValidateLifetime = true,
ClockSkew = TimeSpan.FromSeconds(30)
};
o.Events = new JwtBearerEvents
{
OnTokenValidated = async ctx =>
{
var jti = ctx.Principal?.FindFirstValue(System.IdentityModel.Tokens.Jwt.JwtRegisteredClaimNames.Jti);
if (!string.IsNullOrEmpty(jti))
{
var bl = ctx.HttpContext.RequestServices.GetRequiredService<BlacklistService>();
if (await bl.IsBlacklistedAsync(jti)) ctx.Fail("Token revoked");
}
}
};
});
builder.Services.AddAuthorization();
var app = builder.Build();
app.MapGet("/healthz", () => Results.Ok("ok"));
app.UseSwagger();
app.UseSwaggerUI(o =>
{
o.SwaggerEndpoint("/swagger/v1/swagger.json", "Auth API v1");
o.RoutePrefix = "swagger";
});
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
using AuthApi.Services;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System.Security.Claims;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
// DI
builder.Services.AddSingleton<UserService>();
builder.Services.AddSingleton<BlacklistService>();
// Swagger + JWT auth in Swagger
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Auth API", Version = "v1" });
c.AddSecurityDefinition("bearerAuth", new OpenApiSecurityScheme
{
Type = SecuritySchemeType.Http,
Scheme = "bearer",
BearerFormat = "JWT",
Description = "Paste your access token here (no 'Bearer ' prefix needed)."
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{ Type = ReferenceType.SecurityScheme, Id = "bearerAuth" }
},
Array.Empty<string>()
}
});
});
// AuthN/JWT
var cfg = builder.Configuration;
var jwtKey = cfg["Jwt:Key"] ?? throw new Exception("Jwt:Key missing");
var issuer = cfg["Jwt:Issuer"] ?? "GameAuthApi";
var aud = cfg["Jwt:Audience"] ?? issuer;
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(o =>
{
o.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true, ValidIssuer = issuer,
ValidateAudience = true, ValidAudience = aud,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey)),
ValidateLifetime = true,
ClockSkew = TimeSpan.FromSeconds(30)
};
o.Events = new JwtBearerEvents
{
OnTokenValidated = async ctx =>
{
var jti = ctx.Principal?.FindFirstValue(System.IdentityModel.Tokens.Jwt.JwtRegisteredClaimNames.Jti);
if (!string.IsNullOrEmpty(jti))
{
var bl = ctx.HttpContext.RequestServices.GetRequiredService<BlacklistService>();
if (await bl.IsBlacklistedAsync(jti)) ctx.Fail("Token revoked");
}
}
};
});
builder.Services.AddAuthorization();
var app = builder.Build();
app.MapGet("/healthz", () => Results.Ok("ok"));
app.UseSwagger();
app.UseSwaggerUI(o =>
{
o.SwaggerEndpoint("/swagger/v1/swagger.json", "Auth API v1");
o.RoutePrefix = "swagger";
});
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
@@ -1,23 +1,23 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": false,
"applicationUrl": "http://localhost:5279",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": false,
"applicationUrl": "https://localhost:7295;http://localhost:5279",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": false,
"applicationUrl": "http://localhost:5279",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": false,
"applicationUrl": "https://localhost:7295;http://localhost:5279",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
@@ -1,36 +1,36 @@
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
namespace AuthApi.Services;
public class BlacklistedToken
{
[BsonId] public string Jti { get; set; } = default!;
public DateTime ExpiresAt { get; set; }
}
public class BlacklistService
{
private readonly IMongoCollection<BlacklistedToken> _col;
public BlacklistService(IConfiguration cfg)
{
var cs = cfg["MongoDB:ConnectionString"] ?? "mongodb://127.0.0.1:27017";
var dbName = cfg["MongoDB:DatabaseName"] ?? "GameDb";
var client = new MongoClient(cs);
var db = client.GetDatabase(dbName);
_col = db.GetCollection<BlacklistedToken>("BlacklistedTokens");
// TTL index so revocations expire automatically
var keys = Builders<BlacklistedToken>.IndexKeys.Ascending(x => x.ExpiresAt);
_col.Indexes.CreateOne(new CreateIndexModel<BlacklistedToken>(keys, new CreateIndexOptions { ExpireAfter = TimeSpan.Zero }));
}
public Task AddToBlacklistAsync(string jti, DateTime expiresAt) =>
_col.ReplaceOneAsync(x => x.Jti == jti,
new BlacklistedToken { Jti = jti, ExpiresAt = expiresAt },
new ReplaceOptions { IsUpsert = true });
public Task<bool> IsBlacklistedAsync(string jti) =>
_col.Find(x => x.Jti == jti).AnyAsync();
}
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
namespace AuthApi.Services;
public class BlacklistedToken
{
[BsonId] public string Jti { get; set; } = default!;
public DateTime ExpiresAt { get; set; }
}
public class BlacklistService
{
private readonly IMongoCollection<BlacklistedToken> _col;
public BlacklistService(IConfiguration cfg)
{
var cs = cfg["MongoDB:ConnectionString"] ?? "mongodb://127.0.0.1:27017";
var dbName = cfg["MongoDB:DatabaseName"] ?? "GameDb";
var client = new MongoClient(cs);
var db = client.GetDatabase(dbName);
_col = db.GetCollection<BlacklistedToken>("BlacklistedTokens");
// TTL index so revocations expire automatically
var keys = Builders<BlacklistedToken>.IndexKeys.Ascending(x => x.ExpiresAt);
_col.Indexes.CreateOne(new CreateIndexModel<BlacklistedToken>(keys, new CreateIndexOptions { ExpireAfter = TimeSpan.Zero }));
}
public Task AddToBlacklistAsync(string jti, DateTime expiresAt) =>
_col.ReplaceOneAsync(x => x.Jti == jti,
new BlacklistedToken { Jti = jti, ExpiresAt = expiresAt },
new ReplaceOptions { IsUpsert = true });
public Task<bool> IsBlacklistedAsync(string jti) =>
_col.Find(x => x.Jti == jti).AnyAsync();
}
+32 -32
View File
@@ -1,32 +1,32 @@
using AuthApi.Models;
using MongoDB.Driver;
namespace AuthApi.Services;
public class UserService
{
private readonly IMongoCollection<User> _col;
public UserService(IConfiguration cfg)
{
var cs = cfg["MongoDB:ConnectionString"] ?? "mongodb://127.0.0.1:27017";
var dbName = cfg["MongoDB:DatabaseName"] ?? "GameDb";
var client = new MongoClient(cs);
var db = client.GetDatabase(dbName);
_col = db.GetCollection<User>("Users");
var keys = Builders<User>.IndexKeys.Ascending(u => u.Username);
_col.Indexes.CreateOne(new CreateIndexModel<User>(keys, new CreateIndexOptions { Unique = true }));
}
public Task<User?> GetByUsernameAsync(string username) =>
_col.Find(u => u.Username == username).FirstOrDefaultAsync();
public Task CreateAsync(User user) => _col.InsertOneAsync(user);
public Task UpdateAsync(User user) =>
_col.ReplaceOneAsync(u => u.Id == user.Id, user);
public Task<List<User>> GetAllAsync() =>
_col.Find(FilterDefinition<User>.Empty).ToListAsync();
}
using AuthApi.Models;
using MongoDB.Driver;
namespace AuthApi.Services;
public class UserService
{
private readonly IMongoCollection<User> _col;
public UserService(IConfiguration cfg)
{
var cs = cfg["MongoDB:ConnectionString"] ?? "mongodb://127.0.0.1:27017";
var dbName = cfg["MongoDB:DatabaseName"] ?? "GameDb";
var client = new MongoClient(cs);
var db = client.GetDatabase(dbName);
_col = db.GetCollection<User>("Users");
var keys = Builders<User>.IndexKeys.Ascending(u => u.Username);
_col.Indexes.CreateOne(new CreateIndexModel<User>(keys, new CreateIndexOptions { Unique = true }));
}
public Task<User?> GetByUsernameAsync(string username) =>
_col.Find(u => u.Username == username).FirstOrDefaultAsync();
public Task CreateAsync(User user) => _col.InsertOneAsync(user);
public Task UpdateAsync(User user) =>
_col.ReplaceOneAsync(u => u.Id == user.Id, user);
public Task<List<User>> GetAllAsync() =>
_col.Find(FilterDefinition<User>.Empty).ToListAsync();
}
@@ -1,8 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
+7 -7
View File
@@ -1,7 +1,7 @@
{
"Kestrel": { "Endpoints": { "Http": { "Url": "http://0.0.0.0:5000" } } },
"MongoDB": { "ConnectionString": "mongodb://192.168.86.50:27017", "DatabaseName": "promiscuity" },
"Jwt": { "Key": "SuperUltraSecureJwtKeyWithAtLeast32Chars!!", "Issuer": "promiscuity", "Audience": "promiscuity-auth-api" },
"Logging": { "LogLevel": { "Default": "Information" } },
"AllowedHosts": "*"
}
{
"Kestrel": { "Endpoints": { "Http": { "Url": "http://0.0.0.0:5000" } } },
"MongoDB": { "ConnectionString": "mongodb://192.168.86.50:27017", "DatabaseName": "promiscuity" },
"Jwt": { "Key": "SuperUltraSecureJwtKeyWithAtLeast32Chars!!", "Issuer": "promiscuity", "Audience": "promiscuity-auth-api" },
"Logging": { "LogLevel": { "Default": "Information" } },
"AllowedHosts": "*"
}
+28 -28
View File
@@ -1,28 +1,28 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: promiscuity-auth
labels:
app: promiscuity-auth
spec:
replicas: 2
selector:
matchLabels:
app: promiscuity-auth
template:
metadata:
labels:
app: promiscuity-auth
spec:
containers:
- name: promiscuity-auth
image: promiscuity-auth:latest
imagePullPolicy: IfNotPresent
ports:
- containerPort: 5000
readinessProbe:
httpGet:
path: /healthz
port: 5000
initialDelaySeconds: 5
periodSeconds: 10
apiVersion: apps/v1
kind: Deployment
metadata:
name: promiscuity-auth
labels:
app: promiscuity-auth
spec:
replicas: 2
selector:
matchLabels:
app: promiscuity-auth
template:
metadata:
labels:
app: promiscuity-auth
spec:
containers:
- name: promiscuity-auth
image: promiscuity-auth:latest
imagePullPolicy: IfNotPresent
ports:
- containerPort: 5000
readinessProbe:
httpGet:
path: /healthz
port: 5000
initialDelaySeconds: 5
periodSeconds: 10
+15 -15
View File
@@ -1,15 +1,15 @@
apiVersion: v1
kind: Service
metadata:
name: promiscuity-auth
labels:
app: promiscuity-auth
spec:
selector:
app: promiscuity-auth
type: NodePort
ports:
- name: http
port: 80 # cluster port
targetPort: 5000 # container port
nodePort: 30080 # same external port you've been using
apiVersion: v1
kind: Service
metadata:
name: promiscuity-auth
labels:
app: promiscuity-auth
spec:
selector:
app: promiscuity-auth
type: NodePort
ports:
- name: http
port: 80 # cluster port
targetPort: 5000 # container port
nodePort: 30080 # same external port you've been using
+16 -16
View File
@@ -1,16 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.8" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.8" />
<PackageReference Include="MongoDB.Driver" Version="3.4.3" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
</ItemGroup>
</Project>
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.8" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.8" />
<PackageReference Include="MongoDB.Driver" Version="3.4.3" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
</ItemGroup>
</Project>
@@ -7,11 +7,11 @@ using System.Net.Http.Headers;
using System.Security.Claims;
using System.Text;
using System.Text.Json;
namespace CharacterApi.Controllers;
[ApiController]
[Route("api/[controller]")]
namespace CharacterApi.Controllers;
[ApiController]
[Route("api/[controller]")]
public class CharactersController : ControllerBase
{
private static readonly TimeSpan PresenceTimeout = TimeSpan.FromSeconds(45);
@@ -27,18 +27,18 @@ public class CharactersController : ControllerBase
_configuration = configuration;
_logger = logger;
}
[HttpPost]
[Authorize(Roles = "USER,SUPER")]
[HttpPost]
[Authorize(Roles = "USER,SUPER")]
public async Task<IActionResult> Create([FromBody] CreateCharacterRequest req)
{
if (string.IsNullOrWhiteSpace(req.Name))
return BadRequest("Name required");
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (string.IsNullOrWhiteSpace(userId))
return Unauthorized();
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (string.IsNullOrWhiteSpace(userId))
return Unauthorized();
var character = new Character
{
OwnerUserId = userId,
@@ -60,9 +60,9 @@ public class CharactersController : ControllerBase
return Ok(character);
}
[HttpGet]
[Authorize(Roles = "USER,SUPER")]
[HttpGet]
[Authorize(Roles = "USER,SUPER")]
public async Task<IActionResult> ListMine()
{
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
@@ -269,16 +269,16 @@ public class CharactersController : ControllerBase
[HttpDelete("{id}")]
[Authorize(Roles = "USER,SUPER")]
public async Task<IActionResult> Delete(string id)
{
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (string.IsNullOrWhiteSpace(userId))
return Unauthorized();
var allowAnyOwner = User.IsInRole("SUPER");
var deleted = await _characters.DeleteForOwnerAsync(id, userId, allowAnyOwner);
if (!deleted)
return NotFound();
return Ok("Deleted");
}
}
{
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (string.IsNullOrWhiteSpace(userId))
return Unauthorized();
var allowAnyOwner = User.IsInRole("SUPER");
var deleted = await _characters.DeleteForOwnerAsync(id, userId, allowAnyOwner);
if (!deleted)
return NotFound();
return Ok("Deleted");
}
}
+8 -8
View File
@@ -1,9 +1,9 @@
# CharacterApi document shapes
This service expects JSON request bodies for character creation and stores
character documents in MongoDB.
Inbound JSON documents
# CharacterApi document shapes
This service expects JSON request bodies for character creation and stores
character documents in MongoDB.
Inbound JSON documents
- CreateCharacterRequest (`POST /api/characters`)
```json
{
@@ -19,8 +19,8 @@ Inbound JSON documents
}
}
```
Stored documents (MongoDB)
Stored documents (MongoDB)
- Character
```json
{
+13 -13
View File
@@ -1,16 +1,16 @@
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
namespace CharacterApi.Models;
public class Character
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string? Id { get; set; }
public string OwnerUserId { get; set; } = string.Empty;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
namespace CharacterApi.Models;
public class Character
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string? Id { get; set; }
public string OwnerUserId { get; set; } = string.Empty;
public string Name { get; set; } = string.Empty;
public Coord Coord { get; set; } = new();
@@ -1,6 +1,6 @@
namespace CharacterApi.Models;
public class CreateCharacterRequest
{
public string Name { get; set; } = string.Empty;
}
namespace CharacterApi.Models;
public class CreateCharacterRequest
{
public string Name { get; set; } = string.Empty;
}
@@ -1,18 +1,18 @@
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson;
namespace CharacterApi.Models;
[BsonIgnoreExtraElements]
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson;
namespace CharacterApi.Models;
[BsonIgnoreExtraElements]
public class VisibleLocation
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string? Id { get; set; }
[BsonElement("name")]
public string Name { get; set; } = string.Empty;
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string? Id { get; set; }
[BsonElement("name")]
public string Name { get; set; } = string.Empty;
[BsonElement("coord")]
public LocationCoord Coord { get; set; } = new();
+58 -58
View File
@@ -4,61 +4,61 @@ using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
// DI
builder.Services.AddSingleton<CharacterStore>();
builder.Services.AddHttpClient();
// Swagger + JWT auth in Swagger
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Character API", Version = "v1" });
c.AddSecurityDefinition("bearerAuth", new OpenApiSecurityScheme
{
Type = SecuritySchemeType.Http,
Scheme = "bearer",
BearerFormat = "JWT",
Description = "Paste your access token here (no 'Bearer ' prefix needed)."
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{ Type = ReferenceType.SecurityScheme, Id = "bearerAuth" }
},
Array.Empty<string>()
}
});
});
// AuthN/JWT
var cfg = builder.Configuration;
var jwtKey = cfg["Jwt:Key"] ?? throw new Exception("Jwt:Key missing");
var issuer = cfg["Jwt:Issuer"] ?? "promiscuity";
var aud = cfg["Jwt:Audience"] ?? issuer;
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(o =>
{
o.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true, ValidIssuer = issuer,
ValidateAudience = true, ValidAudience = aud,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey)),
ValidateLifetime = true,
ClockSkew = TimeSpan.FromSeconds(30)
};
});
builder.Services.AddAuthorization();
// Swagger + JWT auth in Swagger
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Character API", Version = "v1" });
c.AddSecurityDefinition("bearerAuth", new OpenApiSecurityScheme
{
Type = SecuritySchemeType.Http,
Scheme = "bearer",
BearerFormat = "JWT",
Description = "Paste your access token here (no 'Bearer ' prefix needed)."
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{ Type = ReferenceType.SecurityScheme, Id = "bearerAuth" }
},
Array.Empty<string>()
}
});
});
// AuthN/JWT
var cfg = builder.Configuration;
var jwtKey = cfg["Jwt:Key"] ?? throw new Exception("Jwt:Key missing");
var issuer = cfg["Jwt:Issuer"] ?? "promiscuity";
var aud = cfg["Jwt:Audience"] ?? issuer;
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(o =>
{
o.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true, ValidIssuer = issuer,
ValidateAudience = true, ValidAudience = aud,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey)),
ValidateLifetime = true,
ClockSkew = TimeSpan.FromSeconds(30)
};
});
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseExceptionHandler(errorApp =>
@@ -98,11 +98,11 @@ app.UseExceptionHandler(errorApp =>
app.MapGet("/healthz", () => Results.Ok("ok"));
app.UseSwagger();
app.UseSwaggerUI(o =>
{
o.SwaggerEndpoint("/swagger/v1/swagger.json", "Character API v1");
o.RoutePrefix = "swagger";
});
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
{
o.SwaggerEndpoint("/swagger/v1/swagger.json", "Character API v1");
o.RoutePrefix = "swagger";
});
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
@@ -1,12 +1,12 @@
{
"profiles": {
"CharacterApi": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "https://localhost:50784;http://localhost:50785"
}
}
{
"profiles": {
"CharacterApi": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "https://localhost:50784;http://localhost:50785"
}
}
}
@@ -1,4 +1,4 @@
{
{
"Kestrel": { "Endpoints": { "Http": { "Url": "http://0.0.0.0:5001" } } },
"MongoDB": { "ConnectionString": "mongodb://192.168.86.50:27017", "DatabaseName": "promiscuity" },
"Services": { "LocationsApiBaseUrl": "http://localhost:5002" },
+1 -1
View File
@@ -1,4 +1,4 @@
{
{
"Kestrel": { "Endpoints": { "Http": { "Url": "http://0.0.0.0:5001" } } },
"MongoDB": { "ConnectionString": "mongodb://192.168.86.50:27017", "DatabaseName": "promiscuity" },
"Services": { "LocationsApiBaseUrl": "https://ploc.ranaze.com" },
+28 -28
View File
@@ -1,28 +1,28 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: promiscuity-character
labels:
app: promiscuity-character
spec:
replicas: 2
selector:
matchLabels:
app: promiscuity-character
template:
metadata:
labels:
app: promiscuity-character
spec:
containers:
- name: promiscuity-character
image: promiscuity-character:latest
imagePullPolicy: IfNotPresent
ports:
- containerPort: 5001
readinessProbe:
httpGet:
path: /healthz
port: 5001
initialDelaySeconds: 5
periodSeconds: 10
apiVersion: apps/v1
kind: Deployment
metadata:
name: promiscuity-character
labels:
app: promiscuity-character
spec:
replicas: 2
selector:
matchLabels:
app: promiscuity-character
template:
metadata:
labels:
app: promiscuity-character
spec:
containers:
- name: promiscuity-character
image: promiscuity-character:latest
imagePullPolicy: IfNotPresent
ports:
- containerPort: 5001
readinessProbe:
httpGet:
path: /healthz
port: 5001
initialDelaySeconds: 5
periodSeconds: 10
+15 -15
View File
@@ -1,15 +1,15 @@
apiVersion: v1
kind: Service
metadata:
name: promiscuity-character
labels:
app: promiscuity-character
spec:
selector:
app: promiscuity-character
type: NodePort
ports:
- name: http
port: 80 # cluster port
targetPort: 5001 # container port
nodePort: 30081 # external port
apiVersion: v1
kind: Service
metadata:
name: promiscuity-character
labels:
app: promiscuity-character
spec:
selector:
app: promiscuity-character
type: NodePort
ports:
- name: http
port: 80 # cluster port
targetPort: 5001 # container port
nodePort: 30081 # external port
@@ -89,6 +89,7 @@ public class CraftingController : ControllerBase
CraftingStore.CraftStatus.RecipeNotFound => NotFound("Recipe not found"),
CraftingStore.CraftStatus.MissingStation => Conflict("Required crafting station is not available"),
CraftingStore.CraftStatus.MissingInputs => Conflict(new { missingRequirements = result.MissingRequirements }),
CraftingStore.CraftStatus.InventoryFull => Conflict(new { missingRequirements = result.MissingRequirements }),
CraftingStore.CraftStatus.InvalidRecipe => BadRequest(new { missingRequirements = result.MissingRequirements }),
_ => Ok(new CraftRecipeResponse
{
@@ -99,7 +99,7 @@ public class CraftingStore
{
var recipes = await _recipes.Find(r => r.Enabled).SortBy(r => r.Category).ThenBy(r => r.Name).ToListAsync();
var items = await GetCharacterItemsAsync(character.CharacterId);
var itemTotals = items.GroupBy(i => i.ItemKey).ToDictionary(g => g.Key, g => g.Sum(x => x.Quantity), StringComparer.Ordinal);
var itemTotals = GetCraftableItemTotals(items);
var location = await GetLocationAtCoordAsync(character.CoordX, character.CoordY);
return recipes.Select(recipe =>
@@ -126,7 +126,7 @@ public class CraftingStore
return new CraftAttemptResult { Status = CraftStatus.MissingStation };
var items = await GetCharacterItemsAsync(character.CharacterId);
var totals = items.GroupBy(i => i.ItemKey).ToDictionary(g => g.Key, g => g.Sum(x => x.Quantity), StringComparer.Ordinal);
var totals = GetCraftableItemTotals(items);
var missing = GetMissingRequirements(recipe, totals, location, craftCount);
if (missing.Count > 0)
return new CraftAttemptResult { Status = CraftStatus.MissingInputs, MissingRequirements = missing };
@@ -139,6 +139,10 @@ public class CraftingStore
return new CraftAttemptResult { Status = CraftStatus.InvalidRecipe, MissingRequirements = [$"Missing item definition for output '{output.ItemKey}'"] };
}
var capacityError = GetOutputCapacityError(recipe, craftCount, items, definitionMap);
if (capacityError is not null)
return new CraftAttemptResult { Status = CraftStatus.InventoryFull, MissingRequirements = [capacityError] };
foreach (var input in recipe.Inputs)
await ConsumeItemKeyAsync(character, input.ItemKey, input.Quantity * craftCount);
@@ -157,6 +161,12 @@ public class CraftingStore
private async Task<List<InventoryItemDocument>> GetCharacterItemsAsync(string characterId) =>
await _items.Find(i => i.OwnerType == CharacterOwnerType && i.OwnerId == characterId).SortBy(i => i.Slot).ThenBy(i => i.ItemKey).ToListAsync();
private static Dictionary<string, int> GetCraftableItemTotals(IEnumerable<InventoryItemDocument> items) =>
items
.Where(i => i.EquippedSlot is null)
.GroupBy(i => i.ItemKey)
.ToDictionary(g => g.Key, g => g.Sum(x => x.Quantity), StringComparer.Ordinal);
private async Task<LocationDocument?> GetLocationAtCoordAsync(int x, int y) =>
await _locations.Find(l => l.Coord.X == x && l.Coord.Y == y).FirstOrDefaultAsync();
@@ -216,6 +226,74 @@ public class CraftingStore
return string.Equals(recipe.StationType, stationType, StringComparison.Ordinal);
}
private static string? GetOutputCapacityError(CraftingRecipe recipe, int craftCount, List<InventoryItemDocument> currentItems, IReadOnlyDictionary<string, ItemDefinitionDocument> definitions)
{
var simulatedItems = currentItems
.Select(item => new SimulatedInventoryItem
{
ItemKey = item.ItemKey,
Quantity = item.Quantity,
Slot = item.Slot,
EquippedSlot = item.EquippedSlot,
CreatedUtc = item.CreatedUtc
})
.ToList();
foreach (var input in recipe.Inputs)
SimulateConsume(simulatedItems, input.ItemKey, input.Quantity * craftCount);
var usedSlots = simulatedItems
.Where(i => i.Slot.HasValue)
.Select(i => i.Slot!.Value)
.ToHashSet();
var openSlots = Enumerable.Range(0, InventorySlotCount).Count(slot => !usedSlots.Contains(slot));
foreach (var outputGroup in recipe.Outputs.GroupBy(output => output.ItemKey, StringComparer.Ordinal))
{
var itemKey = outputGroup.Key;
var requiredQuantity = outputGroup.Sum(output => output.Quantity * craftCount);
var definition = definitions[itemKey];
if (definition.Stackable)
{
var existingSpace = simulatedItems
.Where(i => i.EquippedSlot is null && i.Slot.HasValue && i.ItemKey == itemKey)
.Sum(i => Math.Max(0, definition.MaxStackSize - i.Quantity));
var remaining = Math.Max(0, requiredQuantity - existingSpace);
var slotsNeeded = (int)Math.Ceiling(remaining / (double)Math.Max(1, definition.MaxStackSize));
if (slotsNeeded > openSlots)
return $"Not enough inventory space for output '{itemKey}'";
openSlots -= slotsNeeded;
continue;
}
if (requiredQuantity > openSlots)
return $"Not enough inventory space for output '{itemKey}'";
openSlots -= requiredQuantity;
}
return null;
}
private static void SimulateConsume(List<SimulatedInventoryItem> items, string itemKey, int quantity)
{
var remaining = quantity;
foreach (var item in items
.Where(i => i.EquippedSlot is null && i.ItemKey == itemKey)
.OrderBy(i => i.Slot)
.ThenBy(i => i.CreatedUtc))
{
if (remaining <= 0)
break;
var consumed = Math.Min(remaining, item.Quantity);
item.Quantity -= consumed;
remaining -= consumed;
}
items.RemoveAll(i => i.Quantity <= 0);
}
private async Task ConsumeItemKeyAsync(CharacterAccessResult character, string itemKey, int quantity)
{
var remaining = quantity;
@@ -302,7 +380,7 @@ public class CraftingStore
{
var items = await GetCharacterItemsAsync(characterId);
var used = items.Where(i => i.Slot.HasValue).Select(i => i.Slot!.Value).ToHashSet();
for (var slot = 0; slot < 6; slot++)
for (var slot = 0; slot < InventorySlotCount; slot++)
{
if (!used.Contains(slot))
return slot;
@@ -344,7 +422,23 @@ public class CraftingStore
RecipeNotFound,
MissingInputs,
MissingStation,
InvalidRecipe
InvalidRecipe,
InventoryFull
}
private const int InventorySlotCount = 6;
private class SimulatedInventoryItem
{
public string ItemKey { get; set; } = string.Empty;
public int Quantity { get; set; }
public int? Slot { get; set; }
public string? EquippedSlot { get; set; }
public DateTime CreatedUtc { get; set; }
}
[BsonIgnoreExtraElements]
+19 -19
View File
@@ -1,17 +1,17 @@
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
namespace LocationsApi.Models;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
namespace LocationsApi.Models;
public class Location
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string? Id { get; set; }
[BsonElement("name")]
public string Name { get; set; } = string.Empty;
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string? Id { get; set; }
[BsonElement("name")]
public string Name { get; set; } = string.Empty;
[BsonElement("coord")]
public required Coord Coord { get; set; }
@@ -26,10 +26,10 @@ public class Location
[BsonElement("locationObject")]
public LocationObject? LocationObject { get; set; }
[BsonElement("locationObjectResolved")]
public bool LocationObjectResolved { get; set; }
[BsonElement("createdUtc")]
public DateTime CreatedUtc { get; set; } = DateTime.UtcNow;
}
[BsonElement("locationObjectResolved")]
public bool LocationObjectResolved { get; set; }
[BsonElement("createdUtc")]
public DateTime CreatedUtc { get; set; } = DateTime.UtcNow;
}
@@ -1,9 +1,9 @@
using LocationsApi.Models;
using MongoDB.Bson;
using MongoDB.Driver;
namespace LocationsApi.Services;
using LocationsApi.Models;
using MongoDB.Bson;
using MongoDB.Driver;
namespace LocationsApi.Services;
public class LocationStore
{
private readonly IMongoCollection<Location> _col;
@@ -19,7 +19,7 @@ public class LocationStore
{
var cs = cfg["MongoDB:ConnectionString"] ?? "mongodb://127.0.0.1:27017";
var dbName = cfg["MongoDB:DatabaseName"] ?? "GameDb";
var client = new MongoClient(cs);
var client = new MongoClient(cs);
var db = client.GetDatabase(dbName);
var collectionName = "Locations";
EnsureLocationSchema(db, collectionName);
@@ -32,33 +32,33 @@ public class LocationStore
EnsureOriginLocation();
}
private static void EnsureLocationSchema(IMongoDatabase db, string collectionName)
{
var validator = new BsonDocument
{
{
"$jsonSchema", new BsonDocument
{
{ "bsonType", "object" },
private static void EnsureLocationSchema(IMongoDatabase db, string collectionName)
{
var validator = new BsonDocument
{
{
"$jsonSchema", new BsonDocument
{
{ "bsonType", "object" },
{ "required", new BsonArray { "name", "coord", "biomeKey", "elevation", "createdUtc" } },
{
"properties", new BsonDocument
{
{ "name", new BsonDocument { { "bsonType", "string" } } },
{
"coord", new BsonDocument
{
{ "bsonType", "object" },
{ "required", new BsonArray { "x", "y" } },
{
"properties", new BsonDocument
{
{ "x", new BsonDocument { { "bsonType", "int" } } },
{ "y", new BsonDocument { { "bsonType", "int" } } }
}
}
}
{
"coord", new BsonDocument
{
{ "bsonType", "object" },
{ "required", new BsonArray { "x", "y" } },
{
"properties", new BsonDocument
{
{ "x", new BsonDocument { { "bsonType", "int" } } },
{ "y", new BsonDocument { { "bsonType", "int" } } }
}
}
}
},
{ "biomeKey", new BsonDocument { { "bsonType", "string" } } },
{ "elevation", new BsonDocument { { "bsonType", "int" } } },
@@ -118,42 +118,42 @@ public class LocationStore
}
}
}
};
var collections = db.ListCollectionNames().ToList();
if (!collections.Contains(collectionName))
{
var createCommand = new BsonDocument
{
{ "create", collectionName },
{ "validator", validator },
{ "validationAction", "error" }
};
db.RunCommand<BsonDocument>(createCommand);
return;
}
var command = new BsonDocument
{
{ "collMod", collectionName },
{ "validator", validator },
{ "validationAction", "error" }
};
db.RunCommand<BsonDocument>(command);
}
public Task CreateAsync(Location location) => _col.InsertOneAsync(location);
public Task<List<Location>> GetAllAsync() =>
_col.Find(Builders<Location>.Filter.Empty).ToListAsync();
public async Task<bool> DeleteAsync(string id)
{
var filter = Builders<Location>.Filter.Eq(l => l.Id, id);
var result = await _col.DeleteOneAsync(filter);
return result.DeletedCount > 0;
}
};
var collections = db.ListCollectionNames().ToList();
if (!collections.Contains(collectionName))
{
var createCommand = new BsonDocument
{
{ "create", collectionName },
{ "validator", validator },
{ "validationAction", "error" }
};
db.RunCommand<BsonDocument>(createCommand);
return;
}
var command = new BsonDocument
{
{ "collMod", collectionName },
{ "validator", validator },
{ "validationAction", "error" }
};
db.RunCommand<BsonDocument>(command);
}
public Task CreateAsync(Location location) => _col.InsertOneAsync(location);
public Task<List<Location>> GetAllAsync() =>
_col.Find(Builders<Location>.Filter.Empty).ToListAsync();
public async Task<bool> DeleteAsync(string id)
{
var filter = Builders<Location>.Filter.Eq(l => l.Id, id);
var result = await _col.DeleteOneAsync(filter);
return result.DeletedCount > 0;
}
public async Task<bool> UpdateNameAsync(string id, string name)
{
var filter = Builders<Location>.Filter.Eq(l => l.Id, id);
@@ -419,10 +419,10 @@ public class LocationStore
{
_col.InsertOne(origin);
}
catch (MongoWriteException ex) when (ex.WriteError.Category == ServerErrorCategory.DuplicateKey)
{
// Another instance seeded it first.
}
catch (MongoWriteException ex) when (ex.WriteError.Category == ServerErrorCategory.DuplicateKey)
{
// Another instance seeded it first.
}
}
private static string NormalizeItemKey(string itemKey) => itemKey.Trim().ToLowerInvariant();
+1 -1
View File
@@ -11,4 +11,4 @@
- CharacterApi: `CharacterApi/README.md`
- InventoryApi: `InventoryApi/README.md`
- LocationsApi: `LocationsApi/README.md`
+18 -18
View File
@@ -1,9 +1,9 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.5.2.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AuthApi", "AuthApi\AuthApi.csproj", "{334F3B23-EFE8-6F1A-5E5F-9A2275D56E28}"
EndProject
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.5.2.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AuthApi", "AuthApi\AuthApi.csproj", "{334F3B23-EFE8-6F1A-5E5F-9A2275D56E28}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CharacterApi", "CharacterApi\CharacterApi.csproj", "{1572BA36-8EFC-4472-BE74-0676B593AED9}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LocationsApi", "LocationsApi\LocationsApi.csproj", "{C343AFFB-9AB0-4B70-834C-3D2A21E2B506}"
@@ -21,11 +21,11 @@ Global
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{334F3B23-EFE8-6F1A-5E5F-9A2275D56E28}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{334F3B23-EFE8-6F1A-5E5F-9A2275D56E28}.Debug|Any CPU.Build.0 = Debug|Any CPU
{334F3B23-EFE8-6F1A-5E5F-9A2275D56E28}.Release|Any CPU.ActiveCfg = Release|Any CPU
{334F3B23-EFE8-6F1A-5E5F-9A2275D56E28}.Release|Any CPU.Build.0 = Release|Any CPU
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{334F3B23-EFE8-6F1A-5E5F-9A2275D56E28}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{334F3B23-EFE8-6F1A-5E5F-9A2275D56E28}.Debug|Any CPU.Build.0 = Debug|Any CPU
{334F3B23-EFE8-6F1A-5E5F-9A2275D56E28}.Release|Any CPU.ActiveCfg = Release|Any CPU
{334F3B23-EFE8-6F1A-5E5F-9A2275D56E28}.Release|Any CPU.Build.0 = Release|Any CPU
{1572BA36-8EFC-4472-BE74-0676B593AED9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1572BA36-8EFC-4472-BE74-0676B593AED9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1572BA36-8EFC-4472-BE74-0676B593AED9}.Release|Any CPU.ActiveCfg = Release|Any CPU
@@ -51,10 +51,10 @@ Global
{C8F20B54-2A76-4BE0-8DA8-E146D1AF4D10}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C8F20B54-2A76-4BE0-8DA8-E146D1AF4D10}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {F82C87CC-7411-493D-A138-491A81FBCC32}
EndGlobalSection
EndGlobal
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {F82C87CC-7411-493D-A138-491A81FBCC32}
EndGlobalSection
EndGlobal