AvaloniaStack/Avalonia-PC/Authentication/PcAuthEndpointService.cs

73 lines
2.6 KiB
C#
Raw Normal View History

using Authentication;
using Avalonia_Common.Core;
using Avalonia_Services.Core;
using Avalonia_Services.Services.AuthService;
using System;
using System.Threading.Tasks;
namespace Avalonia_PC.Authentication
{
/// <summary>
/// PC 端鉴权端点服务,实现 <see cref="IPcAuthEndpointService"/>
/// 处理授权码登录、Token 刷新和登出操作。
/// </summary>
public sealed class PcAuthEndpointService(PcGlobalTokenService tokenService) : IPcAuthEndpointService
{
/// <inheritdoc />
public async Task<IApiResponse> AuthorizeAsync(PcAuthorizeRequest request, ServiceEndpointContext ctx)
{
var token = await tokenService.AuthorizeAsync(request.AuthorizationCode);
if (token is null)
{
ctx.StatusCode = 401;
return ResponseHelper.Failure(401, "授权失败");
}
return ResponseHelper.Ok(token, "授权成功");
}
/// <inheritdoc />
public async Task<IApiResponse> RefreshAsync(PcRefreshRequest request, ServiceEndpointContext ctx)
{
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, "刷新成功");
}
/// <inheritdoc />
public Task<IApiResponse> LogoutAsync(PcLogoutRequest request, ServiceEndpointContext ctx)
{
var token = request.Token ?? ExtractBearerToken(ctx.GetHeader("Authorization"));
tokenService.Logout(token);
return Task.FromResult<IApiResponse>(ResponseHelper.Succeed("退出成功"));
}
/// <summary>
/// 从 Authorization 头中提取 Bearer Token。
/// </summary>
/// <param name="authorization">Authorization 头的值。</param>
/// <returns>提取的 Token 字符串;若无法提取则返回 null。</returns>
private static string? ExtractBearerToken(string? authorization)
{
if (string.IsNullOrWhiteSpace(authorization))
{
return null;
}
/// <summary>
/// Bearer Token 的前缀常量。
/// </summary>
const string prefix = "Bearer ";
return authorization.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)
? authorization[prefix.Length..].Trim()
: authorization.Trim();
}
}
}