Initial STEP 3 study game and questions API

This commit is contained in:
hz
2026-07-09 20:50:33 -05:00
commit 277076a245
51 changed files with 2671 additions and 0 deletions
@@ -0,0 +1,138 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MongoDB.Driver;
using QuestionsApi.Models;
using QuestionsApi.Services;
namespace QuestionsApi.Controllers;
[ApiController]
[Route("api/[controller]")]
public class QuestionsController : ControllerBase
{
private readonly QuestionStore _questions;
public QuestionsController(QuestionStore questions)
{
_questions = questions;
}
[HttpGet("systems")]
[Authorize(Roles = "USER,SUPER")]
public async Task<IActionResult> Systems()
{
var systems = await _questions.GetSystemsAsync(User.IsInRole("SUPER"));
return Ok(systems);
}
[HttpPost("search")]
[Authorize(Roles = "USER,SUPER")]
public async Task<IActionResult> Search([FromBody] QuestionSearchRequest req)
{
var questions = await _questions.SearchAsync(req, User.IsInRole("SUPER"));
return Ok(questions.Select(QuestionResponse.FromModel).ToList());
}
[HttpGet("{id}")]
[Authorize(Roles = "USER,SUPER")]
public async Task<IActionResult> Get(string id)
{
var question = await _questions.GetByIdAsync(id);
if (question is null || (!question.IsPublished && !User.IsInRole("SUPER")))
return NotFound();
return Ok(QuestionResponse.FromModel(question));
}
[HttpPost]
[Authorize(Roles = "SUPER")]
public async Task<IActionResult> Create([FromBody] UpsertQuestionRequest req)
{
var validation = ValidateQuestion(req);
if (validation is not null)
return BadRequest(validation);
var created = await _questions.CreateAsync(req);
if (created is null)
return Conflict("Question externalId already exists");
return Ok(QuestionResponse.FromModel(created));
}
[HttpPost("bulk")]
[Authorize(Roles = "SUPER")]
public async Task<IActionResult> BulkUpsert([FromBody] BulkUpsertQuestionsRequest req)
{
if (req.Questions.Count == 0)
return BadRequest("questions required");
foreach (var question in req.Questions)
{
var validation = ValidateQuestion(question);
if (validation is not null)
return BadRequest($"{question.ExternalId}: {validation}");
}
var upserted = await _questions.UpsertManyByExternalIdAsync(req.Questions);
return Ok(new { upserted });
}
[HttpPut("{id}")]
[Authorize(Roles = "SUPER")]
public async Task<IActionResult> Update(string id, [FromBody] UpsertQuestionRequest req)
{
var validation = ValidateQuestion(req);
if (validation is not null)
return BadRequest(validation);
try
{
var updated = await _questions.UpdateAsync(id, req);
if (updated is null)
return NotFound();
return Ok(QuestionResponse.FromModel(updated));
}
catch (MongoWriteException ex) when (ex.WriteError.Category == ServerErrorCategory.DuplicateKey)
{
return Conflict("Question externalId already exists");
}
}
[HttpDelete("{id}")]
[Authorize(Roles = "SUPER")]
public async Task<IActionResult> Delete(string id)
{
var deleted = await _questions.DeleteAsync(id);
if (!deleted)
return NotFound();
return Ok("Deleted");
}
private static string? ValidateQuestion(UpsertQuestionRequest req)
{
if (string.IsNullOrWhiteSpace(req.ExternalId))
return "externalId required";
if (string.IsNullOrWhiteSpace(req.Stem))
return "stem required";
if (string.IsNullOrWhiteSpace(req.LeadIn))
return "leadIn required";
if (req.Choices.Count < 2)
return "at least two choices required";
if (string.IsNullOrWhiteSpace(req.CorrectChoiceId))
return "correctChoiceId required";
if (!req.Choices.Any(c => c.Id == req.CorrectChoiceId))
return "correctChoiceId must match a choice id";
if (string.IsNullOrWhiteSpace(req.Explanation))
return "explanation required";
if (string.IsNullOrWhiteSpace(req.System))
return "system required";
if (string.IsNullOrWhiteSpace(req.Discipline))
return "discipline required";
if (req.Difficulty is < 1 or > 5)
return "difficulty must be between 1 and 5";
return null;
}
}
+19
View File
@@ -0,0 +1,19 @@
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src
COPY ["QuestionsApi.csproj", "./"]
RUN dotnet restore "QuestionsApi.csproj"
COPY . .
RUN dotnet publish "QuestionsApi.csproj" -c Release -o /app/publish /p:UseAppHost=false
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS final
WORKDIR /app
COPY --from=build /app/publish .
ENV ASPNETCORE_URLS=http://+:8080 \
ASPNETCORE_ENVIRONMENT=Production
EXPOSE 8080
ENTRYPOINT ["dotnet", "QuestionsApi.dll"]
@@ -0,0 +1,6 @@
namespace QuestionsApi.Models;
public class BulkUpsertQuestionsRequest
{
public List<UpsertQuestionRequest> Questions { get; set; } = [];
}
+42
View File
@@ -0,0 +1,42 @@
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
namespace QuestionsApi.Models;
public class Question
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string? Id { get; set; }
public string ExternalId { get; set; } = "";
public string Stem { get; set; } = "";
public string LeadIn { get; set; } = "";
public List<QuestionChoice> Choices { get; set; } = [];
public string CorrectChoiceId { get; set; } = "";
public string Explanation { get; set; } = "";
public Dictionary<string, string> ChoiceExplanations { get; set; } = [];
public string Discipline { get; set; } = "";
public string System { get; set; } = "";
public int Difficulty { get; set; } = 1;
public List<QuestionLab> Labs { get; set; } = [];
public List<string> Media { get; set; } = [];
public List<string> Tags { get; set; } = [];
public bool IsPublished { get; set; } = true;
public DateTime CreatedUtc { get; set; } = DateTime.UtcNow;
public DateTime UpdatedUtc { get; set; } = DateTime.UtcNow;
}
public class QuestionChoice
{
public string Id { get; set; } = "";
public string Text { get; set; } = "";
}
public class QuestionLab
{
public string Name { get; set; } = "";
public string Value { get; set; } = "";
public string Unit { get; set; } = "";
public string Reference { get; set; } = "";
}
@@ -0,0 +1,29 @@
namespace QuestionsApi.Models;
public class QuestionSearchRequest
{
public string? System { get; set; }
public string? Discipline { get; set; }
public List<string> Tags { get; set; } = [];
public int? DifficultyMin { get; set; }
public int? DifficultyMax { get; set; }
public int Limit { get; set; } = 40;
}
public class UpsertQuestionRequest
{
public string ExternalId { get; set; } = "";
public string Stem { get; set; } = "";
public string LeadIn { get; set; } = "";
public List<QuestionChoice> Choices { get; set; } = [];
public string CorrectChoiceId { get; set; } = "";
public string Explanation { get; set; } = "";
public Dictionary<string, string> ChoiceExplanations { get; set; } = [];
public string Discipline { get; set; } = "";
public string System { get; set; } = "";
public int Difficulty { get; set; } = 1;
public List<QuestionLab> Labs { get; set; } = [];
public List<string> Media { get; set; } = [];
public List<string> Tags { get; set; } = [];
public bool IsPublished { get; set; } = true;
}
@@ -0,0 +1,37 @@
namespace QuestionsApi.Models;
public class QuestionResponse
{
public string Id { get; set; } = "";
public string ExternalId { get; set; } = "";
public string Stem { get; set; } = "";
public string LeadIn { get; set; } = "";
public List<QuestionChoice> Choices { get; set; } = [];
public string CorrectChoiceId { get; set; } = "";
public string Explanation { get; set; } = "";
public Dictionary<string, string> ChoiceExplanations { get; set; } = [];
public string Discipline { get; set; } = "";
public string System { get; set; } = "";
public int Difficulty { get; set; }
public List<QuestionLab> Labs { get; set; } = [];
public List<string> Media { get; set; } = [];
public List<string> Tags { get; set; } = [];
public static QuestionResponse FromModel(Question question) => new()
{
Id = question.Id ?? "",
ExternalId = question.ExternalId,
Stem = question.Stem,
LeadIn = question.LeadIn,
Choices = question.Choices,
CorrectChoiceId = question.CorrectChoiceId,
Explanation = question.Explanation,
ChoiceExplanations = question.ChoiceExplanations,
Discipline = question.Discipline,
System = question.System,
Difficulty = question.Difficulty,
Labs = question.Labs,
Media = question.Media,
Tags = question.Tags
};
}
+104
View File
@@ -0,0 +1,104 @@
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using QuestionsApi.Services;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddSingleton<QuestionStore>();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Questions 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", "Questions API v1");
o.RoutePrefix = "swagger";
});
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
+16
View File
@@ -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>
+16
View File
@@ -0,0 +1,16 @@
# QuestionsApi
STEP-style question bank service for study games and clients.
## Endpoints
- `GET /healthz` Health check.
- `GET /api/questions/systems` List available systems.
- `POST /api/questions/search` Search or build a block of questions.
- `GET /api/questions/{id}` Get one question.
- `POST /api/questions` Create question (SUPER only).
- `POST /api/questions/bulk` Upsert questions by `externalId` (SUPER only).
- `PUT /api/questions/{id}` Update question (SUPER only).
- `DELETE /api/questions/{id}` Delete question (SUPER only).
Player reads require `USER` or `SUPER` JWT auth. Authoring endpoints require `SUPER`.
+144
View File
@@ -0,0 +1,144 @@
using MongoDB.Driver;
using QuestionsApi.Models;
namespace QuestionsApi.Services;
public class QuestionStore
{
private readonly IMongoCollection<Question> _col;
public QuestionStore(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<Question>("Questions");
var externalIdIndex = Builders<Question>.IndexKeys.Ascending(q => q.ExternalId);
_col.Indexes.CreateOne(new CreateIndexModel<Question>(externalIdIndex, new CreateIndexOptions { Unique = true }));
var systemIndex = Builders<Question>.IndexKeys.Ascending(q => q.System).Ascending(q => q.IsPublished);
_col.Indexes.CreateOne(new CreateIndexModel<Question>(systemIndex));
var tagsIndex = Builders<Question>.IndexKeys.Ascending(q => q.Tags);
_col.Indexes.CreateOne(new CreateIndexModel<Question>(tagsIndex));
}
public async Task<List<Question>> SearchAsync(QuestionSearchRequest req, bool includeUnpublished)
{
var builder = Builders<Question>.Filter;
var filters = new List<FilterDefinition<Question>>();
if (!includeUnpublished)
filters.Add(builder.Eq(q => q.IsPublished, true));
if (!string.IsNullOrWhiteSpace(req.System) && req.System != "All Systems")
filters.Add(builder.Eq(q => q.System, req.System.Trim()));
if (!string.IsNullOrWhiteSpace(req.Discipline))
filters.Add(builder.Eq(q => q.Discipline, req.Discipline.Trim()));
if (req.Tags.Count > 0)
filters.Add(builder.All(q => q.Tags, req.Tags.Where(t => !string.IsNullOrWhiteSpace(t)).Select(t => t.Trim())));
if (req.DifficultyMin is not null)
filters.Add(builder.Gte(q => q.Difficulty, req.DifficultyMin.Value));
if (req.DifficultyMax is not null)
filters.Add(builder.Lte(q => q.Difficulty, req.DifficultyMax.Value));
var filter = filters.Count == 0 ? builder.Empty : builder.And(filters);
var limit = Math.Clamp(req.Limit, 1, 80);
var questions = await _col.Find(filter).Limit(limit).ToListAsync();
return questions.OrderBy(_ => Guid.NewGuid()).ToList();
}
public async Task<Question?> GetByIdAsync(string id) =>
await _col.Find(q => q.Id == id).FirstOrDefaultAsync();
public async Task<Question?> CreateAsync(UpsertQuestionRequest req)
{
var question = FromRequest(req);
question.CreatedUtc = DateTime.UtcNow;
question.UpdatedUtc = DateTime.UtcNow;
try
{
await _col.InsertOneAsync(question);
return question;
}
catch (MongoWriteException ex) when (ex.WriteError.Category == ServerErrorCategory.DuplicateKey)
{
return null;
}
}
public async Task<Question?> UpdateAsync(string id, UpsertQuestionRequest req)
{
var question = FromRequest(req);
question.Id = id;
question.UpdatedUtc = DateTime.UtcNow;
var existing = await GetByIdAsync(id);
if (existing is null)
return null;
question.CreatedUtc = existing.CreatedUtc;
var result = await _col.ReplaceOneAsync(q => q.Id == id, question);
return result.MatchedCount == 0 ? null : question;
}
public async Task<int> UpsertManyByExternalIdAsync(IEnumerable<UpsertQuestionRequest> requests)
{
var count = 0;
foreach (var req in requests)
{
var question = FromRequest(req);
question.UpdatedUtc = DateTime.UtcNow;
var filter = Builders<Question>.Filter.Eq(q => q.ExternalId, question.ExternalId);
var existing = await _col.Find(filter).FirstOrDefaultAsync();
if (existing is not null)
{
question.Id = existing.Id;
question.CreatedUtc = existing.CreatedUtc;
}
else
{
question.CreatedUtc = DateTime.UtcNow;
}
await _col.ReplaceOneAsync(filter, question, new ReplaceOptions { IsUpsert = true });
count++;
}
return count;
}
public async Task<bool> DeleteAsync(string id)
{
var result = await _col.DeleteOneAsync(q => q.Id == id);
return result.DeletedCount > 0;
}
public async Task<List<string>> GetSystemsAsync(bool includeUnpublished)
{
var filter = includeUnpublished
? Builders<Question>.Filter.Empty
: Builders<Question>.Filter.Eq(q => q.IsPublished, true);
var systems = await _col.Distinct(q => q.System, filter).ToListAsync();
return systems.Where(s => !string.IsNullOrWhiteSpace(s)).OrderBy(s => s).ToList();
}
private static Question FromRequest(UpsertQuestionRequest req) => new()
{
ExternalId = req.ExternalId.Trim(),
Stem = req.Stem.Trim(),
LeadIn = req.LeadIn.Trim(),
Choices = req.Choices,
CorrectChoiceId = req.CorrectChoiceId.Trim(),
Explanation = req.Explanation.Trim(),
ChoiceExplanations = req.ChoiceExplanations,
Discipline = req.Discipline.Trim(),
System = req.System.Trim(),
Difficulty = req.Difficulty,
Labs = req.Labs,
Media = req.Media,
Tags = req.Tags.Where(t => !string.IsNullOrWhiteSpace(t)).Select(t => t.Trim()).Distinct(StringComparer.OrdinalIgnoreCase).ToList(),
IsPublished = req.IsPublished
};
}
@@ -0,0 +1,6 @@
{
"Kestrel": { "Endpoints": { "Http": { "Url": "http://0.0.0.0:5008" } } },
"MongoDB": { "ConnectionString": "mongodb://127.0.0.1:27017", "DatabaseName": "step3" },
"Jwt": { "Key": "CHANGE_ME_USE_USER_SECRETS_OR_ENV", "Issuer": "promiscuity", "Audience": "promiscuity-auth-api" },
"Logging": { "LogLevel": { "Default": "Information" } }
}
+7
View File
@@ -0,0 +1,7 @@
{
"Kestrel": { "Endpoints": { "Http": { "Url": "http://0.0.0.0:5008" } } },
"MongoDB": { "ConnectionString": "mongodb://127.0.0.1:27017", "DatabaseName": "step3" },
"Jwt": { "Key": "CHANGE_ME_USE_ENV_Jwt__Key", "Issuer": "promiscuity", "Audience": "promiscuity-auth-api" },
"Logging": { "LogLevel": { "Default": "Information" } },
"AllowedHosts": "*"
}