chore: clean up admin panel

This commit is contained in:
Lapis
2026-06-19 16:59:00 -04:00
parent 3794e6e0ab
commit 21b5ac84e9
15 changed files with 442 additions and 329 deletions
+4
View File
@@ -11,4 +11,8 @@
<ProjectReference Include="..\CannedNet.Shared\CannedNet.Shared.csproj" />
</ItemGroup>
<ItemGroup>
<Content Update="admin_config.json" CopyToPublishDirectory="PreserveNewest" />
</ItemGroup>
</Project>
+5
View File
@@ -21,6 +21,11 @@
<ReconnectModal />
</CascadingAuthenticationState>
<script src="@Assets["_framework/blazor.web.js"]"></script>
<script>
window.getElementValue = function (element) {
return element.value;
};
</script>
</body>
</html>
@@ -9,7 +9,7 @@ main {
}
.sidebar {
background-image: linear-gradient(180deg, rgb(5, 39, 103) 0%, #3a0647 70%);
background: white;
}
.top-row {
@@ -21,27 +21,30 @@ main {
align-items: center;
}
.top-row ::deep a, .top-row ::deep .btn-link {
white-space: nowrap;
margin-left: 1.5rem;
text-decoration: none;
}
.top-row ::deep a,
.top-row ::deep .btn-link {
white-space: nowrap;
margin-left: 1.5rem;
text-decoration: none;
}
.top-row ::deep a:hover, .top-row ::deep .btn-link:hover {
text-decoration: underline;
}
.top-row ::deep a:hover,
.top-row ::deep .btn-link:hover {
text-decoration: underline;
}
.top-row ::deep a:first-child {
overflow: hidden;
text-overflow: ellipsis;
}
.top-row ::deep a:first-child {
overflow: hidden;
text-overflow: ellipsis;
}
@media (max-width: 640.98px) {
.top-row {
justify-content: space-between;
}
.top-row ::deep a, .top-row ::deep .btn-link {
.top-row ::deep a,
.top-row ::deep .btn-link {
margin-left: 0;
}
}
@@ -70,7 +73,8 @@ main {
width: 0;
}
.top-row, article {
.top-row,
article {
padding-left: 2rem !important;
padding-right: 1.5rem !important;
}
@@ -90,9 +94,9 @@ main {
z-index: 1000;
}
#blazor-error-ui .dismiss {
cursor: pointer;
position: absolute;
right: 0.75rem;
top: 0.5rem;
}
#blazor-error-ui .dismiss {
cursor: pointer;
position: absolute;
right: 0.75rem;
top: 0.5rem;
}
@@ -1,53 +1,36 @@
<div class="top-row ps-3 navbar navbar-dark">
<div class="container-fluid">
<a class="navbar-brand" href="">CannedNet.Admin</a>
</div>
</div>
<input type="checkbox" title="Navigation menu" class="navbar-toggler" />
<div class="nav-scrollable" onclick="document.querySelector('.navbar-toggler').click()">
<div class="nav-scrollable" onclick="document.querySelector('.navbar-toggler').click()">
<nav class="nav flex-column">
<AuthorizeView>
<Authorized>
<div class="nav-item px-3">
<NavLink class="nav-link" href="" Match="NavLinkMatch.All">
<span class="bi bi-house-door-fill-nav-menu" aria-hidden="true"></span> Dashboard
</NavLink>
</div>
<div class="nav-section-label px-3 mt-3 mb-1 text-muted small text-uppercase">Users</div>
<div class="nav-item px-3">
<NavLink class="nav-link" href="users/search">
<span class="bi bi-search-nav-menu" aria-hidden="true"></span> Search Users
</NavLink>
</div>
<div class="nav-section-label px-3 mt-3 mb-1 text-muted small text-uppercase">Rooms</div>
<div class="nav-item px-3">
<NavLink class="nav-link" href="rooms/search">
<span class="bi bi-building-nav-menu" aria-hidden="true"></span> Search Rooms
</NavLink>
</div>
<div class="nav-section-label px-3 mt-3 mb-1 text-muted small text-uppercase">Config</div>
<div class="nav-item px-3">
<NavLink class="nav-link" href="config/gameconfig">
<span class="bi bi-sliders-nav-menu" aria-hidden="true"></span> Game Config
</NavLink>
</div>
<div class="nav-item px-3">
<NavLink class="nav-link" href="config/communityboard">
<span class="bi bi-megaphone-fill-nav-menu" aria-hidden="true"></span> Community Board
</NavLink>
</div>
<div class="nav-section-label px-3 mt-3 mb-1 text-muted small text-uppercase">Storefronts</div>
<div class="nav-item px-3">
<NavLink class="nav-link" href="storefronts">
<span class="bi bi-cart-fill-nav-menu" aria-hidden="true"></span> Storefronts
</NavLink>
</div>
<div class="nav-item px-3">
<NavLink class="nav-link" href="settings">
<span class="bi bi-gear-fill-nav-menu" aria-hidden="true"></span> Settings
</NavLink>
</div>
</Authorized>
</AuthorizeView>
</nav>
@@ -1,29 +1,3 @@
.navbar-toggler {
appearance: none;
cursor: pointer;
width: 3.5rem;
height: 2.5rem;
color: white;
position: absolute;
top: 0.5rem;
right: 1rem;
border: 1px solid rgba(255, 255, 255, 0.1);
background: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 30 30'%3e%3cpath stroke='rgba%28255, 255, 255, 0.55%29' stroke-linecap='round' stroke-miterlimit='10' stroke-width='2' d='M4 7h22M4 15h22M4 23h22'/%3e%3c/svg%3e") no-repeat center/1.75rem rgba(255, 255, 255, 0.1);
}
.navbar-toggler:checked {
background-color: rgba(255, 255, 255, 0.5);
}
.top-row {
height: 3.5rem;
background-color: rgba(0,0,0,0.4);
}
.navbar-brand {
font-size: 1.1rem;
}
.bi {
display: inline-block;
position: relative;
@@ -39,55 +13,42 @@
padding-bottom: 0.5rem;
}
.nav-item:first-of-type {
padding-top: 1rem;
}
.nav-item:first-of-type {
padding-top: 0.75rem;
}
.nav-item:last-of-type {
padding-bottom: 1rem;
}
.nav-item:last-of-type {
padding-bottom: 0;
}
.nav-item ::deep a {
color: #d7d7d7;
border-radius: 4px;
height: 2.5rem;
display: flex;
align-items: center;
line-height: 2.5rem;
}
.nav-item ::deep a {
color: #000;
border-radius: 0.5px;
height: 2.5rem;
display: flex;
align-items: center;
line-height: 2.5rem;
justify-content: flex-start;
}
.nav-item ::deep a.active {
background-color: rgba(255,255,255,0.37);
color: white;
}
.nav-item ::deep a.active {
background-color: rgba(0, 0, 0, 0.08);
color: #000;
}
.nav-item ::deep a:hover {
background-color: rgba(255,255,255,0.1);
color: white;
}
.nav-item ::deep a:hover {
background-color: rgba(0, 0, 0, 0.05);
color: #000;
}
.nav-scrollable {
display: none;
}
.navbar-toggler:checked ~ .nav-scrollable {
display: block;
}
.nav-section-label {
font-size: 0.7rem;
letter-spacing: 0.05em;
opacity: 0.7;
}
@media (min-width: 641px) {
.navbar-toggler {
display: none;
}
.nav-scrollable {
display: block;
height: calc(100vh - 3.5rem);
height: 100vh;
overflow-y: auto;
}
}
@@ -7,19 +7,25 @@
display: none;
}
#components-reconnect-modal.components-reconnect-show .components-reconnect-first-attempt-visible,
#components-reconnect-modal.components-reconnect-show .components-rejoining-animation,
#components-reconnect-modal.components-reconnect-paused .components-pause-visible,
#components-reconnect-modal.components-reconnect-resume-failed .components-resume-failed-visible,
#components-reconnect-modal.components-reconnect-show
.components-reconnect-first-attempt-visible,
#components-reconnect-modal.components-reconnect-show
.components-rejoining-animation,
#components-reconnect-modal.components-reconnect-paused
.components-pause-visible,
#components-reconnect-modal.components-reconnect-resume-failed
.components-resume-failed-visible,
#components-reconnect-modal.components-reconnect-retrying,
#components-reconnect-modal.components-reconnect-retrying .components-reconnect-repeated-attempt-visible,
#components-reconnect-modal.components-reconnect-retrying .components-rejoining-animation,
#components-reconnect-modal.components-reconnect-retrying
.components-reconnect-repeated-attempt-visible,
#components-reconnect-modal.components-reconnect-retrying
.components-rejoining-animation,
#components-reconnect-modal.components-reconnect-failed,
#components-reconnect-modal.components-reconnect-failed .components-reconnect-failed-visible {
#components-reconnect-modal.components-reconnect-failed
.components-reconnect-failed-visible {
display: block;
}
#components-reconnect-modal {
background-color: white;
width: 20rem;
@@ -29,15 +35,17 @@
border-radius: 0.5rem;
box-shadow: 0 3px 6px 2px rgba(0, 0, 0, 0.3);
opacity: 0;
transition: display 0.5s allow-discrete, overlay 0.5s allow-discrete;
transition:
display 0.5s allow-discrete,
overlay 0.5s allow-discrete;
animation: components-reconnect-modal-fadeOutOpacity 0.5s both;
&[open]
{
animation: components-reconnect-modal-slideUp 1.5s cubic-bezier(.05, .89, .25, 1.02) 0.3s, components-reconnect-modal-fadeInOpacity 0.5s ease-in-out 0.3s;
animation-fill-mode: both;
}
&[open] {
animation:
components-reconnect-modal-slideUp 1.5s
cubic-bezier(0.05, 0.89, 0.25, 1.02) 0.3s,
components-reconnect-modal-fadeInOpacity 0.5s ease-in-out 0.3s;
animation-fill-mode: both;
}
}
#components-reconnect-modal::backdrop {
@@ -96,13 +104,13 @@
border-radius: 4px;
}
#components-reconnect-modal button:hover {
background-color: #3b6ea2;
}
#components-reconnect-modal button:hover {
background-color: #3b6ea2;
}
#components-reconnect-modal button:active {
background-color: #6b9ed2;
}
#components-reconnect-modal button:active {
background-color: #6b9ed2;
}
.components-rejoining-animation {
position: relative;
@@ -110,17 +118,18 @@
height: 80px;
}
.components-rejoining-animation div {
position: absolute;
border: 3px solid #0087ff;
opacity: 1;
border-radius: 50%;
animation: components-rejoining-animation 1.5s cubic-bezier(0, 0.2, 0.8, 1) infinite;
}
.components-rejoining-animation div {
position: absolute;
border: 3px solid #0087ff;
opacity: 1;
border-radius: 50%;
animation: components-rejoining-animation 1.5s cubic-bezier(0, 0.2, 0.8, 1)
infinite;
}
.components-rejoining-animation div:nth-child(2) {
animation-delay: -0.5s;
}
.components-rejoining-animation div:nth-child(2) {
animation-delay: -0.5s;
}
@keyframes components-rejoining-animation {
0% {
@@ -1,6 +1,9 @@
// Set up event handlers
const reconnectModal = document.getElementById("components-reconnect-modal");
reconnectModal.addEventListener("components-reconnect-state-changed", handleReconnectStateChanged);
reconnectModal.addEventListener(
"components-reconnect-state-changed",
handleReconnectStateChanged,
);
const retryButton = document.getElementById("components-reconnect-button");
retryButton.addEventListener("click", retry);
@@ -9,55 +12,67 @@ const resumeButton = document.getElementById("components-resume-button");
resumeButton.addEventListener("click", resume);
function handleReconnectStateChanged(event) {
if (event.detail.state === "show") {
reconnectModal.showModal();
} else if (event.detail.state === "hide") {
reconnectModal.close();
} else if (event.detail.state === "failed") {
document.addEventListener("visibilitychange", retryWhenDocumentBecomesVisible);
} else if (event.detail.state === "rejected") {
location.reload();
}
if (event.detail.state === "show") {
reconnectModal.showModal();
} else if (event.detail.state === "hide") {
reconnectModal.close();
} else if (event.detail.state === "failed") {
document.addEventListener(
"visibilitychange",
retryWhenDocumentBecomesVisible,
);
} else if (event.detail.state === "rejected") {
location.reload();
}
}
async function retry() {
document.removeEventListener("visibilitychange", retryWhenDocumentBecomesVisible);
document.removeEventListener(
"visibilitychange",
retryWhenDocumentBecomesVisible,
);
try {
// Reconnect will asynchronously return:
// - true to mean success
// - false to mean we reached the server, but it rejected the connection (e.g., unknown circuit ID)
// - exception to mean we didn't reach the server (this can be sync or async)
const successful = await Blazor.reconnect();
if (!successful) {
// We have been able to reach the server, but the circuit is no longer available.
// We'll reload the page so the user can continue using the app as quickly as possible.
const resumeSuccessful = await Blazor.resumeCircuit();
if (!resumeSuccessful) {
location.reload();
} else {
reconnectModal.close();
}
}
} catch (err) {
// We got an exception, server is currently unavailable
document.addEventListener("visibilitychange", retryWhenDocumentBecomesVisible);
try {
// Reconnect will asynchronously return:
// - true to mean success
// - false to mean we reached the server, but it rejected the connection (e.g., unknown circuit ID)
// - exception to mean we didn't reach the server (this can be sync or async)
const successful = await Blazor.reconnect();
if (!successful) {
// We have been able to reach the server, but the circuit is no longer available.
// We'll reload the page so the user can continue using the app as quickly as possible.
const resumeSuccessful = await Blazor.resumeCircuit();
if (!resumeSuccessful) {
location.reload();
} else {
reconnectModal.close();
}
}
} catch (err) {
// We got an exception, server is currently unavailable
document.addEventListener(
"visibilitychange",
retryWhenDocumentBecomesVisible,
);
}
}
async function resume() {
try {
const successful = await Blazor.resumeCircuit();
if (!successful) {
location.reload();
}
} catch {
reconnectModal.classList.replace("components-reconnect-paused", "components-reconnect-resume-failed");
try {
const successful = await Blazor.resumeCircuit();
if (!successful) {
location.reload();
}
} catch {
reconnectModal.classList.replace(
"components-reconnect-paused",
"components-reconnect-resume-failed",
);
}
}
async function retryWhenDocumentBecomesVisible() {
if (document.visibilityState === "visible") {
await retry();
}
if (document.visibilityState === "visible") {
await retry();
}
}
@@ -1,133 +0,0 @@
@page "/config/gameconfig"
@rendermode InteractiveServer
<PageTitle>Game Config</PageTitle>
<h3>Game Config</h3>
<p class="text-muted">Edit the gameconfigs.json file that controls various game settings.</p>
@if (loading)
{
<div class="spinner-border" role="status"></div>
}
else if (!string.IsNullOrEmpty(error))
{
<div class="alert alert-danger">@error</div>
}
else
{
<ul class="nav nav-tabs mb-3">
<li class="nav-item">
<a class="nav-link @GetActiveClass("edit")" href="#" @onclick='() => SetTab("edit")' @onclick:preventDefault="true">Raw Editor</a>
</li>
<li class="nav-item">
<a class="nav-link @GetActiveClass("browse")" href="#" @onclick='() => SetTab("browse")' @onclick:preventDefault="true">Browse</a>
</li>
</ul>
@if (activeTab == "edit")
{
<form>
<div class="mb-3">
<button type="submit" class="btn btn-success" @onclick="Save" disabled="@saving">
@(saving ? "Saving..." : "Save Changes")
</button>
@if (!string.IsNullOrEmpty(saveMessage))
{
<span class="ms-2 @(saveMessage.Contains("Error") ? "text-danger" : "text-success")">@saveMessage</span>
}
</div>
<textarea class="form-control font-monospace" rows="30" @bind="jsonContent"></textarea>
</form>
}
else if (activeTab == "browse")
{
<div class="mb-3">
<input type="text" class="form-control" placeholder="Filter keys..." @bind="filterText" @bind:event="oninput" />
</div>
<div class="table-responsive">
<table class="table table-sm table-striped">
<thead>
<tr><th>Key</th><th>Value</th></tr>
</thead>
<tbody>
@foreach (var entry in configEntries.Where(e => string.IsNullOrEmpty(filterText) || e.Key.Contains(filterText, StringComparison.OrdinalIgnoreCase)))
{
<tr>
<td class="font-monospace small">@entry.Key</td>
<td class="small" style="max-width: 400px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;" title="@entry.Value">@entry.Value</td>
</tr>
}
</tbody>
</table>
</div>
<div class="text-muted small">@configEntries.Count(e => string.IsNullOrEmpty(filterText) || e.Key.Contains(filterText, StringComparison.OrdinalIgnoreCase)) entries</div>
}
}
@code {
[Inject] private HttpClient Http { get; set; } = default!;
private bool loading = true;
private bool saving;
private string? error;
private string? saveMessage;
private string jsonContent = "";
private string activeTab = "browse";
private string filterText = "";
private List<ConfigEntry> configEntries = new();
protected override async Task OnInitializedAsync()
{
try
{
jsonContent = await Http.GetStringAsync("/admin/api/config/gameconfigs");
configEntries = JsonSerializer.Deserialize<List<ConfigEntry>>(jsonContent) ?? new();
}
catch (Exception ex)
{
error = $"Failed to load: {ex.Message}";
}
finally
{
loading = false;
}
}
private string GetActiveClass(string tab) => activeTab == tab ? "active" : "";
private void SetTab(string tab)
{
activeTab = tab;
}
private async Task Save()
{
saving = true;
saveMessage = null;
try
{
var content = new StringContent(jsonContent, System.Text.Encoding.UTF8, "application/json");
var response = await Http.PutAsync("/admin/api/config/gameconfigs", content);
response.EnsureSuccessStatusCode();
saveMessage = "Saved successfully!";
configEntries = JsonSerializer.Deserialize<List<ConfigEntry>>(jsonContent) ?? new();
}
catch (Exception ex)
{
saveMessage = $"Error: {ex.Message}";
}
finally
{
saving = false;
}
}
private class ConfigEntry
{
public string Key { get; set; } = "";
public string Value { get; set; } = "";
public string? EndTime { get; set; }
public string? StartTime { get; set; }
}
}
+2 -2
View File
@@ -30,8 +30,8 @@
<div class="card">
<div class="card-body">
<h5 class="card-title">Config</h5>
<p class="card-text">Modify server configuration files: NS config, game configs, community board.</p>
<a href="config/nameserver" class="btn btn-primary">Manage Config</a>
<p class="card-text">Modify server configuration files</p>
<a href="config/communityboard" class="btn btn-primary">Manage Config</a>
</div>
</div>
</div>
@@ -0,0 +1,91 @@
@page "/settings"
@attribute [Authorize]
@rendermode InteractiveServer
@inject AdminConfigService AdminConfig
@inject NavigationManager Navigation
<PageTitle>Admin Settings</PageTitle>
<h3>Admin Settings</h3>
@if (saved)
{
<div class="alert alert-success alert-dismissible fade show" role="alert">
Settings saved. New sessions will use the updated URLs.
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
}
@if (error)
{
<div class="alert alert-danger alert-dismissible fade show" role="alert">
@errorMessage
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
}
<div class="card mb-4">
<div class="card-body">
<p class="text-muted">
These settings control where the admin panel connects to the CannedNet server API.
If you accidentally change this to the wrong server, please manually change the URL in <code>admin_config.json</code>.
</p>
<div class="mb-3">
<label for="serverUrl" class="form-label">Server Base URL</label>
<input type="url" class="form-control" id="serverUrl" @bind="edit.ServerBaseUrl" />
</div>
<button class="btn btn-primary" @onclick="Save" disabled="@saving">
@(saving ? "Saving..." : "Save Settings")
</button>
</div>
</div>
@code {
private AdminConfigService.AdminConfigData edit = new();
private bool saving;
private bool saved;
private bool error;
private string errorMessage = "";
protected override void OnInitialized()
{
edit = new AdminConfigService.AdminConfigData
{
ServerBaseUrl = AdminConfig.ServerBaseUrl
};
}
private async Task Save()
{
saving = true;
saved = false;
error = false;
errorMessage = "";
try
{
if (string.IsNullOrWhiteSpace(edit.ServerBaseUrl))
{
error = true;
errorMessage = "Server Base URL cannot be empty.";
return;
}
if (!Uri.TryCreate(edit.ServerBaseUrl, UriKind.Absolute, out _))
{
error = true;
errorMessage = "Server Base URL is not a valid absolute URL.";
return;
}
AdminConfig.Save(edit);
saved = true;
}
finally
{
saving = false;
}
}
}
@@ -0,0 +1,96 @@
@page "/setup"
@rendermode InteractiveServer
@inject AdminConfigService AdminConfig
@inject NavigationManager Navigation
<PageTitle>First-Time Setup</PageTitle>
@if (!AdminConfig.IsConfigured)
{
<div class="row justify-content-center mt-5">
<div class="col-md-6">
<div class="card">
<div class="card-header"><h4 class="mb-0">First-Time Setup</h4></div>
<div class="card-body">
<p class="text-muted">
Welcome to the CannedNet Admin Panel. Before you can log in, please configure the
connection to your CannedNet server.
</p>
@if (saved)
{
<div class="alert alert-success">Settings saved! Redirecting to login...</div>
}
@if (error)
{
<div class="alert alert-danger">@errorMessage</div>
}
<div class="mb-3">
<label for="serverUrl" class="form-label">Server Base URL</label>
<input type="url" class="form-control" id="serverUrl" @bind="edit.ServerBaseUrl" placeholder="http://localhost:5000" />
</div>
<button class="btn btn-primary" @onclick="Save" disabled="@saving">
@(saving ? "Saving..." : "Save & Continue")
</button>
</div>
</div>
</div>
</div>
}
else
{
<div class="row justify-content-center mt-5">
<div class="col-md-4">
<div class="card">
<div class="card-body text-center">
<p>Already configured. <a href="/login">Go to login</a>.</p>
</div>
</div>
</div>
</div>
}
@code {
private AdminConfigService.AdminConfigData edit = new();
private bool saving;
private bool saved;
private bool error;
private string errorMessage = "";
private async Task Save()
{
saving = true;
saved = false;
error = false;
errorMessage = "";
try
{
if (string.IsNullOrWhiteSpace(edit.ServerBaseUrl))
{
error = true;
errorMessage = "Server Base URL is required.";
return;
}
if (!Uri.TryCreate(edit.ServerBaseUrl, UriKind.Absolute, out _))
{
error = true;
errorMessage = "Server Base URL is not a valid absolute URL.";
return;
}
AdminConfig.Save(edit);
saved = true;
await Task.Delay(1000);
Navigation.NavigateTo("/login", forceLoad: true);
}
finally
{
saving = false;
}
}
}
+26 -10
View File
@@ -26,23 +26,27 @@ builder.Services.AddAuthentication("AdminCookie")
builder.Services.AddAuthorization();
var imagesBaseUrl = builder.Configuration.GetValue<string>("ImagesBaseUrl") ?? "http://localhost:5000/img";
builder.Services.AddSingleton(new ImageUrlService(imagesBaseUrl));
builder.Services.AddSingleton<AdminConfigService>();
builder.Services.AddHttpContextAccessor();
var serverUrl = builder.Configuration.GetValue<string>("ServerBaseUrl") ?? "http://localhost:5000";
builder.Services.AddScoped(sp =>
{
var config = sp.GetRequiredService<AdminConfigService>();
return new ImageUrlService(config.ImagesBaseUrl);
});
builder.Services.AddTransient<JwtBearerHandler>();
builder.Services.AddScoped(sp =>
{
var config = sp.GetRequiredService<AdminConfigService>();
var handler = sp.GetRequiredService<JwtBearerHandler>();
handler.InnerHandler = new SocketsHttpHandler();
return new HttpClient(handler) { BaseAddress = new Uri(serverUrl) };
return new HttpClient(handler) { BaseAddress = new Uri(config.ServerBaseUrl) };
});
var app = builder.Build();
// --- Admin Auth Endpoints ---
app.MapPost("/admin/login", async (HttpContext context) =>
{
var form = await context.Request.ReadFormAsync();
@@ -55,8 +59,8 @@ app.MapPost("/admin/login", async (HttpContext context) =>
return;
}
var serverUrl = app.Services.GetRequiredService<IConfiguration>().GetValue<string>("ServerBaseUrl") ?? "http://localhost:5000";
using var httpClient = new HttpClient { BaseAddress = new Uri(serverUrl) };
var adminConfig = app.Services.GetRequiredService<AdminConfigService>();
using var httpClient = new HttpClient { BaseAddress = new Uri(adminConfig.ServerBaseUrl) };
var tokenResponse = await httpClient.PostAsync("/auth/connect/token", new FormUrlEncodedContent(new Dictionary<string, string>
{
["grant_type"] = "password",
@@ -100,7 +104,6 @@ app.MapPost("/admin/login", async (HttpContext context) =>
new("access_token", accessToken)
};
// Map JWT roles for admin app authorization
if (role.Split(',', StringSplitOptions.RemoveEmptyEntries).Any(rr => rr == "developer" || rr == "admin"))
claims.Add(new Claim(ClaimTypes.Role, "Admin"));
@@ -122,7 +125,20 @@ app.MapGet("/admin/logout", async (HttpContext context) =>
context.Response.Redirect("/login");
});
// --- Standard middleware ---
app.Use(async (context, next) =>
{
var config = context.RequestServices.GetRequiredService<AdminConfigService>();
if (!config.IsConfigured && !context.Request.Path.StartsWithSegments("/setup"))
{
var accept = context.Request.Headers.Accept.FirstOrDefault() ?? "";
if (accept.Contains("text/html"))
{
context.Response.Redirect("/setup");
return;
}
}
await next();
});
if (!app.Environment.IsDevelopment())
{
@@ -0,0 +1,46 @@
using System.Text.Json;
namespace CannedNet.Admin.Services;
public class AdminConfigService
{
private const string ConfigFile = "admin_config.json";
private static readonly JsonSerializerOptions Indented = new() { WriteIndented = true };
public AdminConfigData Config { get; private set; }
public string ServerBaseUrl => Config.ServerBaseUrl;
public string ImagesBaseUrl => Config.ServerBaseUrl.TrimEnd('/') + "/img";
public AdminConfigService()
{
Config = Load();
}
public bool IsConfigured =>
!string.IsNullOrWhiteSpace(Config.ServerBaseUrl);
private static AdminConfigData Load()
{
if (!File.Exists(ConfigFile))
{
var empty = new AdminConfigData();
File.WriteAllText(ConfigFile, JsonSerializer.Serialize(empty, Indented));
return empty;
}
var json = File.ReadAllText(ConfigFile);
return JsonSerializer.Deserialize<AdminConfigData>(json) ?? new AdminConfigData();
}
public void Save(AdminConfigData updated)
{
Config = updated;
File.WriteAllText(ConfigFile, JsonSerializer.Serialize(Config, Indented));
}
public class AdminConfigData
{
public string ServerBaseUrl { get; set; } = "";
}
}
+3
View File
@@ -0,0 +1,3 @@
{
"ServerBaseUrl": "https://cannednet.lapis.codes"
}
@@ -209,10 +209,23 @@ public class AdminController : ControllerBase
[HttpPut("config/gameconfigs")]
public async Task<IResult> SaveGameConfigs()
{
using var reader = new StreamReader(Request.Body);
var body = await reader.ReadToEndAsync();
await System.IO.File.WriteAllTextAsync(Path.Combine(JsonDir, "gameconfigs.json"), body);
return Results.Ok(new { success = true });
try
{
using var reader = new StreamReader(Request.Body);
var body = await reader.ReadToEndAsync();
Console.WriteLine(body);
var path = Path.Combine(JsonDir, "gameconfigs.json");
await System.IO.File.WriteAllTextAsync(path, body);
return Results.Ok(new { success = true });
}
catch (Exception ex)
{
return Results.Problem(ex.ToString());
}
}
[HttpGet("config/communityboard")]