-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPreferencesController.cs
More file actions
50 lines (43 loc) · 1.6 KB
/
PreferencesController.cs
File metadata and controls
50 lines (43 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Backend.Controllers;
[ApiController]
[Route("api/preferences")]
[Authorize]
public class PreferencesController : ControllerBase
{
private static readonly HashSet<string> AllowedThemes = ["light", "dark"];
/// <summary>
/// Stores the user's theme preference in a browser-accessible (non-HttpOnly) cookie
/// so React can read it on load without an API call.
///
/// IS 414 additional feature: "Browser-accessible cookie (NOT httponly) that saves a
/// user setting used by React."
/// </summary>
[HttpPost("theme")]
public IActionResult SetTheme([FromBody] ThemeRequest request)
{
if (!AllowedThemes.Contains(request.Theme))
return BadRequest(new { message = "Theme must be 'light' or 'dark'." });
Response.Cookies.Append("user-theme", request.Theme, new CookieOptions
{
HttpOnly = false, // Must be JS-readable for React to use it
Secure = true,
SameSite = SameSiteMode.Lax,
Expires = DateTimeOffset.UtcNow.AddDays(365)
});
return Ok(new { theme = request.Theme });
}
/// <summary>
/// Returns the current theme preference from the cookie.
/// React can read this directly from document.cookie, but this endpoint
/// is available as a fallback.
/// </summary>
[HttpGet("theme")]
public IActionResult GetTheme()
{
var theme = Request.Cookies["user-theme"] ?? "light";
return Ok(new { theme });
}
}
public record ThemeRequest(string Theme);