Files
DorkNet/DorkNet.Server/Controllers/API/Account/AccountApiController.cs
T
Alexa 6ee1d6f9b3 fix: presence, profile edits, outfit menu and RecNetResult writes for the 2023 client
Every change below was checked against the 2023-03-21 client disassembly;
file:line evidence is in the code comments and in
docs/recroom-2023-client-api-complete.md.

Presence
- matchmake/none means "online, in no room" (its only caller is
  TryGoToOfflineRoom, which ignores the reply). The server used to keep the
  old room or invent a dorm, so the next heartbeat looked out of sync and
  the client cancelled its load to chase that room.
- The join watchdog no longer clears presence 30 s into a long room load;
  it is a 3 minute backstop that drops the room only.
- One fan-out (PresenceBroadcastService) for every transition: deferred
  joins, matchmake/none, logout, failed joins, visibility changes, SignalR
  connect/disconnect. isOnline is sent on its own; pushes never go to the
  subject, because a self push moves the player.
- Online-status visibility (Public / Friends / Favorites / Appear offline)
  is stored and honoured by GET /player and by the live pushes.

Profile
- PUT account/me/{emoji,personalpronouns,identityflags,bannerimage} were
  404; added with the client's real form keys and persisted (new Players
  columns plus migration). Every account read now returns them, and edits
  push AccountUpdate to everyone.

Outfit menu
- Saved outfits kept OutfitSelectionsV2 and CustomAvatarItems, so loading a
  slot restores what was saved instead of a stale outfit.
- isCreationAllowedForAccount answers the {Success, Error} envelope the
  client parses; minPriceForPublicItem is a bare int; gifts/generate accepts
  form bodies; lockeditems returns the full owned-item shape; colourways no
  longer share their base item's AvatarItemId.

RecNetResult writes
- About 40 writes look status-only but parse the body as {Success, Error}.
  An empty 200 showed "Failed to ..." after the server applied the change,
  and a body without Success threw "Error message cannot be null". Clubs,
  announcements, keepsakes, comments/read, subscriptions, purchase offers
  and privacy settings now answer RecNetResult.
- Login token and device-code grants are real; remoteauth approves the
  device code; createlogintoken returns a bare string.
- New: incentivizedreferrals/referrals, account/bulk/{email,phone},
  GET strings, account/me/confirmphone, PlayMenuCarouselOrdering_1.
  Route inventory and coverage test extended to match.

README now describes the 2023 branch.
2026-10-15 14:08:11 +03:00

217 lines
9.1 KiB
C#

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using DorkNet.Models.Auth;
using DorkNet.Server.Data;
using DorkNet.Server.Data.Entities;
using DorkNet.Server.Services;
namespace DorkNet.Server.Controllers.API.Account;
/// <summary>
/// api.rec.net/api/account/* — same endpoints as accounts.rec.net but routed
/// through the API service. The Accounts class in dump.cs doesn't expose its
/// base URL constant so the game may use either host; we cover both.
/// </summary>
[ApiController]
public class AccountApiController(
PlayerService playerService,
AuthService authService,
DorkNetDbContext db,
NotificationService notifications,
ServerSettingsService settings,
SignupCodeService signupCodes,
ILogger<AccountApiController> logger) : ControllerBase
{
[HttpPost("api/account/v1/create")]
[HttpPost("api/account/v1")]
[HttpPost("api/account/v2/create")]
[HttpPost("api/createaccount")]
public async Task<IActionResult> CreateAccount(
[FromForm] int platform,
[FromForm] string? platformId,
[FromForm] string? deviceId,
[FromForm] string? Username,
[FromForm] string? DisplayName)
{
if (await settings.AreSignupsDisabledAsync())
{
logger.LogInformation(
"[api-account] api/account/v1/create refused — signups disabled (device={Device} platform={Platform})",
deviceId, platform);
await signupCodes.RecordPendingDeviceAsync(
deviceId, platform, platformId, SignupCodeService.ClientIp(HttpContext));
return Ok(new CreateAccountResponse
{
Success = false,
Error = "Account creation is currently disabled by the server admin.",
});
}
var player = await playerService.GetOrCreateByDeviceAsync(
deviceId: deviceId,
platform: platform,
platformId: platformId,
displayName: DisplayName ?? Username);
return Ok(new CreateAccountResponse
{
Success = true,
Error = string.Empty,
Account = AccountDtos.Public(player),
});
}
[HttpGet("api/account/v1/me")]
[HttpGet("api/account/v2/me")]
public async Task<IActionResult> GetMe()
{
var player = await GetCurrentPlayerAsync();
if (player is null) return Unauthorized();
return Ok(AccountDtos.Self(player));
}
/// <summary>
/// Resolves the player tied to the bearer token on the request. Returns
/// null when no/invalid bearer is supplied — caller decides whether
/// that's a 401 or a softer fallback. Anonymous-account creation was
/// previously the fallback path; deleted in Phase 1c because every
/// caller has gone through `/account/create` (deviceId-bound) before
/// reaching us.
/// </summary>
private async Task<PlayerEntity?> GetCurrentPlayerAsync()
{
var auth = Request.Headers.Authorization.ToString();
var token = auth.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)
? auth["Bearer ".Length..].Trim()
: Request.Cookies[AuthService.AccessCookieName];
if (string.IsNullOrWhiteSpace(token))
return null;
var id = authService.ValidateToken(token);
if (id is not long playerId) return null;
return await playerService.GetByIdAsync(playerId);
}
// Modification endpoints — POSTs land on api.* host with form body
// carrying the new value. AuthAccountController on auth.* handles
// the same shape with real persistence; we mirror that here so
// either host works.
[HttpPost("api/account/v1/displayname")]
public async Task<IActionResult> SetDisplayName([FromForm(Name = "displayName")] string? displayName,
[FromForm(Name = "value")] string? value)
{
var p = await GetCurrentPlayerAsync();
if (p is null) return Unauthorized();
var name = (displayName ?? value ?? string.Empty).Trim();
if (name.Length == 0) return BadRequest(new RecNetResult { Success = false, Error = "empty" });
await playerService.UpdateDisplayNameAsync(p.Id, name);
var updated = await playerService.GetByIdAsync(p.Id);
if (updated is not null) await notifications.AccountChanged(updated);
return Ok(new RecNetResult { Success = true, Error = string.Empty });
}
[HttpPost("api/account/v1/bio")]
public async Task<IActionResult> SetBio([FromForm(Name = "bio")] string? bio,
[FromForm(Name = "value")] string? value)
{
var p = await GetCurrentPlayerAsync();
if (p is null) return Unauthorized();
await playerService.UpdateBioAsync(p.Id, (bio ?? value ?? string.Empty));
return Ok(new RecNetResult { Success = true, Error = string.Empty });
}
[HttpPost("api/account/v1/username")]
public async Task<IActionResult> SetUsername([FromForm(Name = "username")] string? username,
[FromForm(Name = "value")] string? value)
{
var p = await GetCurrentPlayerAsync();
if (p is null) return Unauthorized();
var newName = (username ?? value ?? string.Empty).Trim();
if (newName.Length == 0) return BadRequest(new RecNetResult { Success = false, Error = "empty" });
var taken = await db.Players.AnyAsync(x => x.Username == newName && x.Id != p.Id);
if (taken) return Ok(new RecNetResult { Success = false, Error = "username_taken" });
p.Username = newName;
await db.SaveChangesAsync();
await notifications.AccountChanged(p);
return Ok(new RecNetResult { Success = true, Error = string.Empty });
}
[HttpPost("api/account/v1/birthday")]
public async Task<IActionResult> SetBirthday([FromForm(Name = "birthday")] string? birthday,
[FromForm(Name = "value")] string? value)
{
var p = await GetCurrentPlayerAsync();
if (p is null) return Unauthorized();
var raw = birthday ?? value ?? string.Empty;
if (DateTime.TryParse(raw, out var parsed))
{
p.Birthday = DateTime.SpecifyKind(parsed, DateTimeKind.Utc);
await db.SaveChangesAsync();
}
return Ok(new RecNetResult { Success = true, Error = string.Empty });
}
[HttpPost("api/account/v1/email")]
public async Task<IActionResult> SetEmail([FromForm(Name = "email")] string? email,
[FromForm(Name = "value")] string? value)
{
var p = await GetCurrentPlayerAsync();
if (p is null) return Unauthorized();
var addr = (email ?? value ?? string.Empty).Trim();
if (addr.Length > 0) p.Email = addr;
await db.SaveChangesAsync();
return Ok(new RecNetResult { Success = true, Error = string.Empty });
}
[HttpPost("api/account/v1/phone")]
[HttpPost("api/account/v1/confirmphone")]
public async Task<IActionResult> SetPhone([FromForm(Name = "phone")] string? phone,
[FromForm(Name = "value")] string? value)
{
var p = await GetCurrentPlayerAsync();
if (p is null) return Unauthorized();
var num = (phone ?? value ?? string.Empty).Trim();
if (num.Length > 0) p.Phone = num;
await db.SaveChangesAsync();
return Ok(new RecNetResult { Success = true, Error = string.Empty });
}
[HttpPost("api/account/v1/profileimage")]
[HttpPost("api/account/me/profileimage")]
[HttpPost("account/me/profileimage", Order = 10)]
[HttpPost("profileimage", Order = 10)]
[HttpPut("api/account/v1/profileimage")]
[HttpPut("api/account/me/profileimage")]
[HttpPut("account/me/profileimage", Order = 10)]
[HttpPut("profileimage", Order = 10)]
[Consumes("application/x-www-form-urlencoded", "multipart/form-data", "application/json")]
public async Task<IActionResult> SetProfileImage(
[FromForm(Name = "imageName")] string? imageName,
[FromForm(Name = "fileName")] string? fileName,
[FromForm(Name = "image")] string? imageAlt)
{
var player = await GetCurrentPlayerAsync();
if (player is null) return Unauthorized();
var name = imageName ?? fileName ?? imageAlt
?? Request.Query["imageName"].ToString()
?? Request.Query["fileName"].ToString();
player.ProfileImageName = string.IsNullOrWhiteSpace(name) ? null : name.Trim();
await db.SaveChangesAsync();
logger.LogInformation(
"[api-account] profile image set: player={PlayerId} -> {Name}",
player.Id,
player.ProfileImageName ?? "<cleared>");
await notifications.AccountChanged(player);
return Ok(new RecNetResult { Success = true, Error = string.Empty });
}
[HttpGet("api/account/v1/namegen")]
[HttpGet("api/account/v1/namegeneration")]
public IActionResult NameGen() => Ok(new
{
Nouns = new[] { "Player", "Hero", "Star", "Fox", "Wolf" },
Adjectives = new[] { "Brave", "Swift", "Clever", "Bold", "Bright" },
});
}