Mail support
Deploy Promiscuity Auth API / deploy (push) Successful in 48s
Deploy Promiscuity Character API / deploy (push) Successful in 59s
Deploy Promiscuity Inventory API / deploy (push) Successful in 46s
Deploy Promiscuity Locations API / deploy (push) Successful in 1m0s
Deploy Promiscuity Mail API / deploy (push) Successful in 1m9s
k8s smoke test / test (push) Successful in 9s
Deploy Promiscuity Auth API / deploy (push) Successful in 48s
Deploy Promiscuity Character API / deploy (push) Successful in 59s
Deploy Promiscuity Inventory API / deploy (push) Successful in 46s
Deploy Promiscuity Locations API / deploy (push) Successful in 1m0s
Deploy Promiscuity Mail API / deploy (push) Successful in 1m9s
k8s smoke test / test (push) Successful in 9s
This commit is contained in:
@@ -0,0 +1,93 @@
|
||||
using MailApi.Models;
|
||||
using MailApi.Services;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace MailApi.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
public class MailController : ControllerBase
|
||||
{
|
||||
private readonly MailStore _mail;
|
||||
|
||||
public MailController(MailStore mail)
|
||||
{
|
||||
_mail = mail;
|
||||
}
|
||||
|
||||
[HttpGet("characters/{characterId}")]
|
||||
[Authorize(Roles = "USER,SUPER")]
|
||||
public async Task<IActionResult> GetMailbox(string characterId)
|
||||
{
|
||||
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
if (string.IsNullOrWhiteSpace(userId))
|
||||
return Unauthorized();
|
||||
|
||||
var access = await _mail.ResolveCharacterAsync(characterId, userId, User.IsInRole("SUPER"));
|
||||
if (!access.Exists)
|
||||
return NotFound();
|
||||
if (!access.IsAuthorized)
|
||||
return Forbid();
|
||||
|
||||
var inbox = await _mail.GetInboxAsync(characterId);
|
||||
var sent = await _mail.GetSentAsync(characterId);
|
||||
return Ok(new MailboxResponse
|
||||
{
|
||||
CharacterId = characterId,
|
||||
Inbox = inbox.Select(MailMessageResponse.FromModel).ToList(),
|
||||
Sent = sent.Select(MailMessageResponse.FromModel).ToList()
|
||||
});
|
||||
}
|
||||
|
||||
[HttpPost("characters/{characterId}/send")]
|
||||
[Authorize(Roles = "USER,SUPER")]
|
||||
public async Task<IActionResult> Send(string characterId, [FromBody] SendMailRequest req)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(req.RecipientCharacterName))
|
||||
return BadRequest("recipientCharacterName required");
|
||||
if (string.IsNullOrWhiteSpace(req.Subject))
|
||||
return BadRequest("subject required");
|
||||
if (string.IsNullOrWhiteSpace(req.Body))
|
||||
return BadRequest("body required");
|
||||
|
||||
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
if (string.IsNullOrWhiteSpace(userId))
|
||||
return Unauthorized();
|
||||
|
||||
var access = await _mail.ResolveCharacterAsync(characterId, userId, User.IsInRole("SUPER"));
|
||||
if (!access.Exists)
|
||||
return NotFound();
|
||||
if (!access.IsAuthorized)
|
||||
return Forbid();
|
||||
|
||||
var result = await _mail.SendAsync(characterId, req.RecipientCharacterName, req.Subject, req.Body);
|
||||
return result.Status switch
|
||||
{
|
||||
MailStore.SendMailStatus.SenderNotFound => NotFound("Sender character not found"),
|
||||
MailStore.SendMailStatus.RecipientNotFound => NotFound("Recipient character not found"),
|
||||
MailStore.SendMailStatus.RecipientAmbiguous => Conflict("Recipient character name is ambiguous"),
|
||||
MailStore.SendMailStatus.Invalid => BadRequest("Invalid recipient"),
|
||||
_ => Ok(MailMessageResponse.FromModel(result.Message!))
|
||||
};
|
||||
}
|
||||
|
||||
[HttpPost("characters/{characterId}/messages/{messageId}/read")]
|
||||
[Authorize(Roles = "USER,SUPER")]
|
||||
public async Task<IActionResult> MarkRead(string characterId, string messageId)
|
||||
{
|
||||
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
if (string.IsNullOrWhiteSpace(userId))
|
||||
return Unauthorized();
|
||||
|
||||
var access = await _mail.ResolveCharacterAsync(characterId, userId, User.IsInRole("SUPER"));
|
||||
if (!access.Exists)
|
||||
return NotFound();
|
||||
if (!access.IsAuthorized)
|
||||
return Forbid();
|
||||
|
||||
var message = await _mail.MarkReadAsync(characterId, messageId);
|
||||
return message is null ? NotFound() : Ok(MailMessageResponse.FromModel(message));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
# MailApi
|
||||
|
||||
- `GET /api/mail/characters/{characterId}` returns inbox and sent mail.
|
||||
- `POST /api/mail/characters/{characterId}/send` sends mail to another character by exact character name.
|
||||
- `POST /api/mail/characters/{characterId}/messages/{messageId}/read` marks an inbox message as read.
|
||||
@@ -0,0 +1,10 @@
|
||||
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
|
||||
WORKDIR /src
|
||||
COPY . .
|
||||
RUN dotnet publish -c Release -o /app/publish
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:8.0
|
||||
WORKDIR /app
|
||||
COPY --from=build /app/publish .
|
||||
EXPOSE 5004
|
||||
ENTRYPOINT ["dotnet", "MailApi.dll"]
|
||||
@@ -0,0 +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>
|
||||
@@ -0,0 +1,35 @@
|
||||
using MongoDB.Bson;
|
||||
using MongoDB.Bson.Serialization.Attributes;
|
||||
|
||||
namespace MailApi.Models;
|
||||
|
||||
public class MailMessage
|
||||
{
|
||||
[BsonId]
|
||||
[BsonRepresentation(BsonType.ObjectId)]
|
||||
public string? Id { get; set; }
|
||||
|
||||
[BsonElement("senderCharacterId")]
|
||||
public string SenderCharacterId { get; set; } = string.Empty;
|
||||
|
||||
[BsonElement("senderCharacterName")]
|
||||
public string SenderCharacterName { get; set; } = string.Empty;
|
||||
|
||||
[BsonElement("recipientCharacterId")]
|
||||
public string RecipientCharacterId { get; set; } = string.Empty;
|
||||
|
||||
[BsonElement("recipientCharacterName")]
|
||||
public string RecipientCharacterName { get; set; } = string.Empty;
|
||||
|
||||
[BsonElement("subject")]
|
||||
public string Subject { get; set; } = string.Empty;
|
||||
|
||||
[BsonElement("body")]
|
||||
public string Body { get; set; } = string.Empty;
|
||||
|
||||
[BsonElement("createdUtc")]
|
||||
public DateTime CreatedUtc { get; set; } = DateTime.UtcNow;
|
||||
|
||||
[BsonElement("readUtc")]
|
||||
public DateTime? ReadUtc { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
namespace MailApi.Models;
|
||||
|
||||
public class MailMessageResponse
|
||||
{
|
||||
public string Id { get; set; } = string.Empty;
|
||||
|
||||
public string SenderCharacterId { get; set; } = string.Empty;
|
||||
|
||||
public string SenderCharacterName { get; set; } = string.Empty;
|
||||
|
||||
public string RecipientCharacterId { get; set; } = string.Empty;
|
||||
|
||||
public string RecipientCharacterName { get; set; } = string.Empty;
|
||||
|
||||
public string Subject { get; set; } = string.Empty;
|
||||
|
||||
public string Body { get; set; } = string.Empty;
|
||||
|
||||
public DateTime CreatedUtc { get; set; }
|
||||
|
||||
public DateTime? ReadUtc { get; set; }
|
||||
|
||||
public static MailMessageResponse FromModel(MailMessage message) => new()
|
||||
{
|
||||
Id = message.Id ?? string.Empty,
|
||||
SenderCharacterId = message.SenderCharacterId,
|
||||
SenderCharacterName = message.SenderCharacterName,
|
||||
RecipientCharacterId = message.RecipientCharacterId,
|
||||
RecipientCharacterName = message.RecipientCharacterName,
|
||||
Subject = message.Subject,
|
||||
Body = message.Body,
|
||||
CreatedUtc = message.CreatedUtc,
|
||||
ReadUtc = message.ReadUtc
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace MailApi.Models;
|
||||
|
||||
public class MailboxResponse
|
||||
{
|
||||
public string CharacterId { get; set; } = string.Empty;
|
||||
|
||||
public List<MailMessageResponse> Inbox { get; set; } = [];
|
||||
|
||||
public List<MailMessageResponse> Sent { get; set; } = [];
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace MailApi.Models;
|
||||
|
||||
public class SendMailRequest
|
||||
{
|
||||
public string RecipientCharacterName { get; set; } = string.Empty;
|
||||
|
||||
public string Subject { get; set; } = string.Empty;
|
||||
|
||||
public string Body { get; set; } = string.Empty;
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
using MailApi.Services;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.AspNetCore.Diagnostics;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using Microsoft.OpenApi.Models;
|
||||
using System.Text;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
builder.Services.AddControllers();
|
||||
builder.Services.AddSingleton<MailStore>();
|
||||
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
builder.Services.AddSwaggerGen(c =>
|
||||
{
|
||||
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Mail 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>()
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
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 =>
|
||||
{
|
||||
errorApp.Run(async context =>
|
||||
{
|
||||
var feature = context.Features.Get<IExceptionHandlerFeature>();
|
||||
var exception = feature?.Error;
|
||||
var logger = context.RequestServices.GetRequiredService<ILoggerFactory>().CreateLogger("GlobalException");
|
||||
var traceId = context.TraceIdentifier;
|
||||
|
||||
if (exception is not null)
|
||||
{
|
||||
logger.LogError(
|
||||
exception,
|
||||
"Unhandled exception for {Method} {Path}. TraceId={TraceId}",
|
||||
context.Request.Method,
|
||||
context.Request.Path,
|
||||
traceId
|
||||
);
|
||||
}
|
||||
|
||||
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
|
||||
context.Response.ContentType = "application/problem+json";
|
||||
|
||||
await context.Response.WriteAsJsonAsync(new
|
||||
{
|
||||
type = "https://httpstatuses.com/500",
|
||||
title = "Internal Server Error",
|
||||
status = 500,
|
||||
detail = exception?.Message ?? "An unexpected server error occurred.",
|
||||
traceId
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
app.MapGet("/healthz", () => Results.Ok("ok"));
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI(o =>
|
||||
{
|
||||
o.SwaggerEndpoint("/swagger/v1/swagger.json", "Mail API v1");
|
||||
o.RoutePrefix = "swagger";
|
||||
});
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
app.MapControllers();
|
||||
app.Run();
|
||||
@@ -0,0 +1,3 @@
|
||||
# MailApi
|
||||
|
||||
Stores character-to-character mail and exposes mailbox read and send endpoints.
|
||||
@@ -0,0 +1,137 @@
|
||||
using MailApi.Models;
|
||||
using MongoDB.Bson;
|
||||
using MongoDB.Bson.Serialization.Attributes;
|
||||
using MongoDB.Driver;
|
||||
|
||||
namespace MailApi.Services;
|
||||
|
||||
public class MailStore
|
||||
{
|
||||
private readonly IMongoCollection<MailMessage> _messages;
|
||||
private readonly IMongoCollection<CharacterDocument> _characters;
|
||||
|
||||
public MailStore(IConfiguration cfg)
|
||||
{
|
||||
var cs = cfg["MongoDB:ConnectionString"] ?? "mongodb://127.0.0.1:27017";
|
||||
var dbName = cfg["MongoDB:DatabaseName"] ?? "promiscuity";
|
||||
var client = new MongoClient(cs);
|
||||
var db = client.GetDatabase(dbName);
|
||||
_messages = db.GetCollection<MailMessage>("MailMessages");
|
||||
_characters = db.GetCollection<CharacterDocument>("Characters");
|
||||
|
||||
_messages.Indexes.CreateOne(new CreateIndexModel<MailMessage>(
|
||||
Builders<MailMessage>.IndexKeys.Ascending(m => m.RecipientCharacterId).Descending(m => m.CreatedUtc)));
|
||||
_messages.Indexes.CreateOne(new CreateIndexModel<MailMessage>(
|
||||
Builders<MailMessage>.IndexKeys.Ascending(m => m.SenderCharacterId).Descending(m => m.CreatedUtc)));
|
||||
}
|
||||
|
||||
public async Task<CharacterAccessResult> ResolveCharacterAsync(string characterId, string userId, bool allowAnyOwner)
|
||||
{
|
||||
var character = await _characters.Find(c => c.Id == characterId).FirstOrDefaultAsync();
|
||||
if (character is null)
|
||||
return new CharacterAccessResult { Exists = false };
|
||||
|
||||
return new CharacterAccessResult
|
||||
{
|
||||
Exists = true,
|
||||
IsAuthorized = allowAnyOwner || character.OwnerUserId == userId,
|
||||
CharacterId = character.Id ?? string.Empty,
|
||||
CharacterName = character.Name,
|
||||
OwnerUserId = character.OwnerUserId
|
||||
};
|
||||
}
|
||||
|
||||
public async Task<List<MailMessage>> GetInboxAsync(string characterId) =>
|
||||
await _messages.Find(m => m.RecipientCharacterId == characterId)
|
||||
.SortByDescending(m => m.CreatedUtc)
|
||||
.ToListAsync();
|
||||
|
||||
public async Task<List<MailMessage>> GetSentAsync(string characterId) =>
|
||||
await _messages.Find(m => m.SenderCharacterId == characterId)
|
||||
.SortByDescending(m => m.CreatedUtc)
|
||||
.ToListAsync();
|
||||
|
||||
public async Task<SendMailResult> SendAsync(string senderCharacterId, string recipientCharacterName, string subject, string body)
|
||||
{
|
||||
var sender = await _characters.Find(c => c.Id == senderCharacterId).FirstOrDefaultAsync();
|
||||
if (sender is null)
|
||||
return new SendMailResult { Status = SendMailStatus.SenderNotFound };
|
||||
|
||||
var normalizedRecipientName = recipientCharacterName.Trim();
|
||||
var recipients = await _characters.Find(c => c.Name == normalizedRecipientName).ToListAsync();
|
||||
if (recipients.Count == 0)
|
||||
return new SendMailResult { Status = SendMailStatus.RecipientNotFound };
|
||||
if (recipients.Count > 1)
|
||||
return new SendMailResult { Status = SendMailStatus.RecipientAmbiguous };
|
||||
|
||||
var recipient = recipients[0];
|
||||
if (recipient.Id == sender.Id)
|
||||
return new SendMailResult { Status = SendMailStatus.Invalid };
|
||||
|
||||
var message = new MailMessage
|
||||
{
|
||||
SenderCharacterId = sender.Id ?? string.Empty,
|
||||
SenderCharacterName = sender.Name,
|
||||
RecipientCharacterId = recipient.Id ?? string.Empty,
|
||||
RecipientCharacterName = recipient.Name,
|
||||
Subject = subject.Trim(),
|
||||
Body = body.Trim(),
|
||||
CreatedUtc = DateTime.UtcNow
|
||||
};
|
||||
|
||||
await _messages.InsertOneAsync(message);
|
||||
return new SendMailResult { Status = SendMailStatus.Ok, Message = message };
|
||||
}
|
||||
|
||||
public async Task<MailMessage?> MarkReadAsync(string characterId, string messageId)
|
||||
{
|
||||
var filter = Builders<MailMessage>.Filter.And(
|
||||
Builders<MailMessage>.Filter.Eq(m => m.Id, messageId),
|
||||
Builders<MailMessage>.Filter.Eq(m => m.RecipientCharacterId, characterId)
|
||||
);
|
||||
var update = Builders<MailMessage>.Update.Set(m => m.ReadUtc, DateTime.UtcNow);
|
||||
var options = new FindOneAndUpdateOptions<MailMessage> { ReturnDocument = ReturnDocument.After };
|
||||
return await _messages.FindOneAndUpdateAsync(filter, update, options);
|
||||
}
|
||||
|
||||
public class CharacterAccessResult
|
||||
{
|
||||
public bool Exists { get; set; }
|
||||
|
||||
public bool IsAuthorized { get; set; }
|
||||
|
||||
public string CharacterId { get; set; } = string.Empty;
|
||||
|
||||
public string CharacterName { get; set; } = string.Empty;
|
||||
|
||||
public string OwnerUserId { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
public class SendMailResult
|
||||
{
|
||||
public SendMailStatus Status { get; set; }
|
||||
|
||||
public MailMessage? Message { get; set; }
|
||||
}
|
||||
|
||||
public enum SendMailStatus
|
||||
{
|
||||
Ok,
|
||||
SenderNotFound,
|
||||
RecipientNotFound,
|
||||
RecipientAmbiguous,
|
||||
Invalid
|
||||
}
|
||||
|
||||
[BsonIgnoreExtraElements]
|
||||
private class CharacterDocument
|
||||
{
|
||||
[BsonId]
|
||||
[BsonRepresentation(BsonType.ObjectId)]
|
||||
public string? Id { get; set; }
|
||||
|
||||
public string OwnerUserId { get; set; } = string.Empty;
|
||||
|
||||
public string Name { get; set; } = string.Empty;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"Kestrel": { "Endpoints": { "Http": { "Url": "http://0.0.0.0:5004" } } },
|
||||
"MongoDB": { "ConnectionString": "mongodb://127.0.0.1:27017", "DatabaseName": "promiscuity" },
|
||||
"Jwt": { "Key": "SuperUltraSecureJwtKeyWithAtLeast32Chars!!", "Issuer": "promiscuity", "Audience": "promiscuity-auth-api" },
|
||||
"Logging": { "LogLevel": { "Default": "Information" } },
|
||||
"AllowedHosts": "*"
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"Kestrel": { "Endpoints": { "Http": { "Url": "http://0.0.0.0:5004" } } },
|
||||
"MongoDB": { "ConnectionString": "mongodb://192.168.86.50:27017", "DatabaseName": "promiscuity" },
|
||||
"Jwt": { "Key": "SuperUltraSecureJwtKeyWithAtLeast32Chars!!", "Issuer": "promiscuity", "Audience": "promiscuity-auth-api" },
|
||||
"Logging": { "LogLevel": { "Default": "Information" } },
|
||||
"AllowedHosts": "*"
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: promiscuity-mail
|
||||
labels:
|
||||
app: promiscuity-mail
|
||||
spec:
|
||||
replicas: 2
|
||||
selector:
|
||||
matchLabels:
|
||||
app: promiscuity-mail
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: promiscuity-mail
|
||||
spec:
|
||||
containers:
|
||||
- name: promiscuity-mail
|
||||
image: promiscuity-mail:latest
|
||||
imagePullPolicy: IfNotPresent
|
||||
ports:
|
||||
- containerPort: 5004
|
||||
readinessProbe:
|
||||
httpGet:
|
||||
path: /healthz
|
||||
port: 5004
|
||||
initialDelaySeconds: 5
|
||||
periodSeconds: 10
|
||||
@@ -0,0 +1,15 @@
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: promiscuity-mail
|
||||
labels:
|
||||
app: promiscuity-mail
|
||||
spec:
|
||||
selector:
|
||||
app: promiscuity-mail
|
||||
type: NodePort
|
||||
ports:
|
||||
- name: http
|
||||
port: 80
|
||||
targetPort: 5004
|
||||
nodePort: 30084
|
||||
Reference in New Issue
Block a user