优化导航菜单
This commit is contained in:
1 parent
4360280aee
commit
23fdbf422f
13 files changed
+10595
-19
No files matched your search
@@ -202,7 +202,7 @@ public sealed class AuthController(
|
||||
? AuthenticationClientType.App
|
||||
: AuthenticationClientType.Web,
|
||||
cancellationToken);
|
||||
return Ok(CreateLoginResponse(session));
|
||||
return Ok(await CreateLoginResponseAsync(db, session, cancellationToken));
|
||||
}
|
||||
|
||||
[AllowAnonymous]
|
||||
@@ -232,7 +232,7 @@ public sealed class AuthController(
|
||||
var session = await authSessionService.CreateAsync(user, roles,
|
||||
isNativeApp ? AuthenticationClientType.App : AuthenticationClientType.Web,
|
||||
cancellationToken);
|
||||
return CreateLoginResponse(session);
|
||||
return await CreateLoginResponseAsync(db, session, cancellationToken);
|
||||
}
|
||||
|
||||
[AllowAnonymous]
|
||||
@@ -255,7 +255,7 @@ public sealed class AuthController(
|
||||
});
|
||||
}
|
||||
|
||||
return CreateLoginResponse(session);
|
||||
return await CreateLoginResponseAsync(db, session, cancellationToken);
|
||||
}
|
||||
|
||||
[AllowAnonymous]
|
||||
@@ -280,13 +280,17 @@ public sealed class AuthController(
|
||||
}
|
||||
|
||||
var roles = await userManager.GetRolesAsync(user);
|
||||
var navigationPreference = await NavigationPreferencesController.ReadAsync(
|
||||
db,
|
||||
user.Id);
|
||||
return new CurrentUserResponse(
|
||||
user.Id,
|
||||
user.UserName!,
|
||||
user.DisplayName,
|
||||
roles,
|
||||
user.CollegeId,
|
||||
EffectiveDataScopeResolver.Resolve(roles).ToString());
|
||||
EffectiveDataScopeResolver.Resolve(roles).ToString(),
|
||||
navigationPreference);
|
||||
}
|
||||
|
||||
private ActionResult IdentityValidationProblem(IdentityResult result)
|
||||
@@ -316,8 +320,16 @@ public sealed class AuthController(
|
||||
Status = StatusCodes.Status401Unauthorized
|
||||
};
|
||||
|
||||
internal static LoginResponse CreateLoginResponse(AuthSessionResult session) =>
|
||||
new(
|
||||
internal static async Task<LoginResponse> CreateLoginResponseAsync(
|
||||
AppDbContext db,
|
||||
AuthSessionResult session,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var navigationPreference = await NavigationPreferencesController.ReadAsync(
|
||||
db,
|
||||
session.User.Id,
|
||||
cancellationToken);
|
||||
return new LoginResponse(
|
||||
session.AccessToken,
|
||||
session.AccessTokenExpiresAt,
|
||||
session.RefreshToken,
|
||||
@@ -328,7 +340,9 @@ public sealed class AuthController(
|
||||
session.User.DisplayName,
|
||||
session.Roles,
|
||||
session.User.CollegeId,
|
||||
EffectiveDataScopeResolver.Resolve(session.Roles).ToString()));
|
||||
EffectiveDataScopeResolver.Resolve(session.Roles).ToString(),
|
||||
navigationPreference));
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record LoginRequest(
|
||||
@@ -381,7 +395,8 @@ public sealed record CurrentUserResponse(
|
||||
string DisplayName,
|
||||
IEnumerable<string> Roles,
|
||||
Guid? CollegeId,
|
||||
string EffectiveDataScope);
|
||||
string EffectiveDataScope,
|
||||
NavigationPreferenceResponse NavigationPreference);
|
||||
|
||||
public sealed record ActivationOptionsResponse(
|
||||
IReadOnlyList<ActivationCollegeOption> Colleges,
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Security.Claims;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using Jiaowu.Api.Domain.Identity;
|
||||
using Jiaowu.Api.Infrastructure.Persistence;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Jiaowu.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
[Route("api/account/navigation-preference")]
|
||||
public sealed partial class NavigationPreferencesController(AppDbContext db) : ControllerBase
|
||||
{
|
||||
public const int MaximumFavorites = 12;
|
||||
public const int CurrentSchemaVersion = 1;
|
||||
|
||||
[HttpGet]
|
||||
public async Task<ActionResult<NavigationPreferenceResponse>> Get(
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var userId = CurrentUserId();
|
||||
if (userId is null) return Unauthorized();
|
||||
|
||||
return Ok(await ReadAsync(db, userId.Value, cancellationToken));
|
||||
}
|
||||
|
||||
[HttpPut]
|
||||
public async Task<ActionResult<NavigationPreferenceResponse>> Put(
|
||||
NavigationPreferenceUpdateRequest request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var userId = CurrentUserId();
|
||||
if (userId is null) return Unauthorized();
|
||||
|
||||
var favorites = request.FavoriteItemIds
|
||||
.Select(x => x.Trim())
|
||||
.Where(x => x.Length > 0)
|
||||
.Distinct(StringComparer.Ordinal)
|
||||
.ToArray();
|
||||
|
||||
if (favorites.Length > MaximumFavorites)
|
||||
{
|
||||
ModelState.AddModelError(
|
||||
nameof(request.FavoriteItemIds),
|
||||
$"常用功能最多只能保存 {MaximumFavorites} 项。");
|
||||
}
|
||||
|
||||
if (favorites.Any(x => !MenuItemIdRegex().IsMatch(x)))
|
||||
{
|
||||
ModelState.AddModelError(
|
||||
nameof(request.FavoriteItemIds),
|
||||
"菜单标识格式不正确。");
|
||||
}
|
||||
|
||||
if (!ModelState.IsValid) return ValidationProblem(ModelState);
|
||||
|
||||
var entity = await db.UserNavigationPreferences
|
||||
.SingleOrDefaultAsync(x => x.UserId == userId.Value, cancellationToken);
|
||||
var json = JsonSerializer.Serialize(new NavigationPreferenceConfiguration(favorites));
|
||||
if (entity is null)
|
||||
{
|
||||
entity = new UserNavigationPreference
|
||||
{
|
||||
UserId = userId.Value,
|
||||
SchemaVersion = CurrentSchemaVersion,
|
||||
ConfigurationJson = json
|
||||
};
|
||||
db.UserNavigationPreferences.Add(entity);
|
||||
}
|
||||
else
|
||||
{
|
||||
entity.SchemaVersion = CurrentSchemaVersion;
|
||||
entity.ConfigurationJson = json;
|
||||
entity.UpdatedAt = DateTime.UtcNow;
|
||||
}
|
||||
|
||||
await db.SaveChangesAsync(cancellationToken);
|
||||
return Ok(new NavigationPreferenceResponse(
|
||||
CurrentSchemaVersion,
|
||||
true,
|
||||
favorites));
|
||||
}
|
||||
|
||||
[HttpDelete]
|
||||
public async Task<ActionResult<NavigationPreferenceResponse>> Reset(
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var userId = CurrentUserId();
|
||||
if (userId is null) return Unauthorized();
|
||||
|
||||
var entity = await db.UserNavigationPreferences
|
||||
.SingleOrDefaultAsync(x => x.UserId == userId.Value, cancellationToken);
|
||||
if (entity is not null)
|
||||
{
|
||||
db.UserNavigationPreferences.Remove(entity);
|
||||
await db.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
|
||||
return Ok(NavigationPreferenceResponse.Default);
|
||||
}
|
||||
|
||||
internal static async Task<NavigationPreferenceResponse> ReadAsync(
|
||||
AppDbContext db,
|
||||
Guid userId,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var stored = await db.UserNavigationPreferences
|
||||
.AsNoTracking()
|
||||
.Where(x => x.UserId == userId)
|
||||
.Select(x => new { x.SchemaVersion, x.ConfigurationJson })
|
||||
.SingleOrDefaultAsync(cancellationToken);
|
||||
if (stored is null)
|
||||
{
|
||||
return NavigationPreferenceResponse.Default;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var configuration = JsonSerializer.Deserialize<NavigationPreferenceConfiguration>(
|
||||
stored.ConfigurationJson);
|
||||
var favorites = configuration?.FavoriteItemIds
|
||||
.Where(x => MenuItemIdRegex().IsMatch(x))
|
||||
.Distinct(StringComparer.Ordinal)
|
||||
.Take(MaximumFavorites)
|
||||
.ToArray() ?? [];
|
||||
return new NavigationPreferenceResponse(stored.SchemaVersion, true, favorites);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return new NavigationPreferenceResponse(stored.SchemaVersion, true, []);
|
||||
}
|
||||
}
|
||||
|
||||
private Guid? CurrentUserId()
|
||||
{
|
||||
var raw = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
return Guid.TryParse(raw, out var userId) ? userId : null;
|
||||
}
|
||||
|
||||
[GeneratedRegex("^[a-z0-9][a-z0-9.-]{0,79}$", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex MenuItemIdRegex();
|
||||
}
|
||||
|
||||
public sealed record NavigationPreferenceUpdateRequest(
|
||||
[Required] IReadOnlyList<string> FavoriteItemIds);
|
||||
|
||||
public sealed record NavigationPreferenceResponse(
|
||||
int SchemaVersion,
|
||||
bool IsCustomized,
|
||||
IReadOnlyList<string> FavoriteItemIds)
|
||||
{
|
||||
public static NavigationPreferenceResponse Default { get; } = new(1, false, []);
|
||||
}
|
||||
|
||||
internal sealed record NavigationPreferenceConfiguration(
|
||||
IReadOnlyList<string> FavoriteItemIds);
|
||||
@@ -4,6 +4,7 @@ using System.Security.Cryptography;
|
||||
using System.Text.Json;
|
||||
using Jiaowu.Api.Domain.Identity;
|
||||
using Jiaowu.Api.Infrastructure.Auth;
|
||||
using Jiaowu.Api.Infrastructure.Persistence;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
@@ -20,6 +21,7 @@ namespace Jiaowu.Api.Controllers;
|
||||
[ApiController]
|
||||
[Route("api/auth/sso")]
|
||||
public sealed class SsoController(
|
||||
AppDbContext db,
|
||||
UserManager<ApplicationUser> userManager,
|
||||
IAuthSessionService authSessionService,
|
||||
IDistributedCache cache,
|
||||
@@ -269,7 +271,7 @@ public sealed class SsoController(
|
||||
? AuthenticationClientType.App
|
||||
: AuthenticationClientType.Web,
|
||||
cancellationToken);
|
||||
return AuthController.CreateLoginResponse(session);
|
||||
return await AuthController.CreateLoginResponseAsync(db, session, cancellationToken);
|
||||
}
|
||||
|
||||
[AllowAnonymous]
|
||||
@@ -362,7 +364,7 @@ public sealed class SsoController(
|
||||
? AuthenticationClientType.App
|
||||
: AuthenticationClientType.Web,
|
||||
cancellationToken);
|
||||
return AuthController.CreateLoginResponse(session);
|
||||
return await AuthController.CreateLoginResponseAsync(db, session, cancellationToken);
|
||||
}
|
||||
|
||||
[Authorize]
|
||||
|
||||
Loaded 3 of 13 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user