using Authentication; using Avalonia_Common.Core; using Avalonia_Services.Core; using Avalonia_Services.Services.AuthService; using System; using System.Text.Json; using System.Threading.Tasks; namespace Avalonia_PC.Authentication { /// /// PC 端鉴权端点服务,实现 , /// 处理授权码登录、Token 刷新和登出操作。 /// public sealed class PcAuthEndpointService(PcGlobalTokenService tokenService) : IPcAuthEndpointService { private static readonly JsonSerializerOptions JsonOptions = new() { PropertyNameCaseInsensitive = true, }; /// public async Task AuthorizeAsync(ServiceEndpointContext ctx) { var request = Deserialize(ctx.Body); var token = await tokenService.AuthorizeAsync(request?.AuthorizationCode); if (token is null) { ctx.StatusCode = 401; return ResponseHelper.Failure(401, "授权失败"); } return ResponseHelper.Ok(token, "授权成功"); } /// public async Task RefreshAsync(ServiceEndpointContext ctx) { var request = Deserialize(ctx.Body); var token = request?.Token ?? ExtractBearerToken(ctx.GetHeader("Authorization")); var refreshed = await tokenService.RefreshAsync(token); if (refreshed is null) { ctx.StatusCode = 401; return ResponseHelper.Failure(401, "授权已失效"); } return ResponseHelper.Ok(refreshed, "刷新成功"); } /// public Task LogoutAsync(ServiceEndpointContext ctx) { var request = Deserialize(ctx.Body); var token = request?.Token ?? ExtractBearerToken(ctx.GetHeader("Authorization")); tokenService.Logout(token); return Task.FromResult(ResponseHelper.Succeed("退出成功")); } /// /// 将 JSON 请求体反序列化为指定类型。 /// /// 目标类型。 /// JSON 请求体字符串,可为空。 /// 反序列化后的对象;若 body 为空则返回默认值。 private static T? Deserialize(string? body) { return string.IsNullOrWhiteSpace(body) ? default : JsonSerializer.Deserialize(body, JsonOptions); } /// /// 从 Authorization 头中提取 Bearer Token。 /// /// Authorization 头的值。 /// 提取的 Token 字符串;若无法提取则返回 null。 private static string? ExtractBearerToken(string? authorization) { if (string.IsNullOrWhiteSpace(authorization)) { return null; } /// /// Bearer Token 的前缀常量。 /// const string prefix = "Bearer "; return authorization.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) ? authorization[prefix.Length..].Trim() : authorization.Trim(); } } }