74 lines
2.5 KiB
C#
74 lines
2.5 KiB
C#
|
|
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
|
||
|
|
{
|
||
|
|
public sealed class PcAuthEndpointService(PcGlobalTokenService tokenService) : IPcAuthEndpointService
|
||
|
|
{
|
||
|
|
private static readonly JsonSerializerOptions JsonOptions = new()
|
||
|
|
{
|
||
|
|
PropertyNameCaseInsensitive = true,
|
||
|
|
};
|
||
|
|
|
||
|
|
public async Task<object?> AuthorizeAsync(ServiceEndpointContext ctx)
|
||
|
|
{
|
||
|
|
var request = Deserialize<PcAuthorizeRequest>(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<object?> RefreshAsync(ServiceEndpointContext ctx)
|
||
|
|
{
|
||
|
|
var request = Deserialize<PcRefreshRequest>(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<object?> LogoutAsync(ServiceEndpointContext ctx)
|
||
|
|
{
|
||
|
|
var request = Deserialize<PcLogoutRequest>(ctx.Body);
|
||
|
|
var token = request?.Token ?? ExtractBearerToken(ctx.GetHeader("Authorization"));
|
||
|
|
tokenService.Logout(token);
|
||
|
|
return Task.FromResult<object?>(ResponseHelper.Succeed("退出成功"));
|
||
|
|
}
|
||
|
|
|
||
|
|
private static T? Deserialize<T>(string? body)
|
||
|
|
{
|
||
|
|
return string.IsNullOrWhiteSpace(body)
|
||
|
|
? default
|
||
|
|
: JsonSerializer.Deserialize<T>(body, JsonOptions);
|
||
|
|
}
|
||
|
|
|
||
|
|
private static string? ExtractBearerToken(string? authorization)
|
||
|
|
{
|
||
|
|
if (string.IsNullOrWhiteSpace(authorization))
|
||
|
|
{
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
|
||
|
|
const string prefix = "Bearer ";
|
||
|
|
return authorization.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)
|
||
|
|
? authorization[prefix.Length..].Trim()
|
||
|
|
: authorization.Trim();
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|