67 lines
2.0 KiB
C#
67 lines
2.0 KiB
C#
using Microsoft.AspNetCore.Mvc.Filters;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.Extensions.Caching.Distributed;
|
|
using Microsoft.Extensions.Configuration;
|
|
using System.Globalization;
|
|
using StackExchange.Redis;
|
|
|
|
namespace UGQApiServer;
|
|
|
|
public class AllowWhenSingleLoginAttribute : TypeFilterAttribute
|
|
{
|
|
public AllowWhenSingleLoginAttribute() : base(typeof(AllowWhenSingleLoginFilter))
|
|
{
|
|
}
|
|
}
|
|
|
|
|
|
public class AllowWhenSingleLoginFilter : IAsyncAuthorizationFilter
|
|
{
|
|
readonly IConfiguration _configuration;
|
|
readonly IHttpContextAccessor _httpContextAccessor;
|
|
readonly IConnectionMultiplexer _redis;
|
|
|
|
bool EnableAllowWhenSingleLogin = true;
|
|
|
|
|
|
public AllowWhenSingleLoginFilter(IConfiguration configuration,
|
|
IHttpContextAccessor httpContextAccessor,
|
|
IConnectionMultiplexer redis)
|
|
{
|
|
_configuration = configuration;
|
|
_httpContextAccessor = httpContextAccessor;
|
|
_redis = redis;
|
|
|
|
|
|
EnableAllowWhenSingleLogin = _configuration.GetValue<bool>("EnableAllowWhenSingleLogin", true);
|
|
}
|
|
|
|
public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
|
|
{
|
|
if (EnableAllowWhenSingleLogin == false)
|
|
return;
|
|
|
|
var user_guid = context.HttpContext.User.Claims.FirstOrDefault(c => c.Type == "Id")?.Value;
|
|
if (user_guid == null)
|
|
{
|
|
context.Result = new UnauthorizedObjectResult(string.Empty);
|
|
return;
|
|
}
|
|
|
|
var game_login_cache = await _redis.GetDatabase().StringGetAsync($"login:{user_guid}");
|
|
if (game_login_cache.HasValue == true)
|
|
{
|
|
context.Result = new BadRequestObjectResult(ApiResponseFactory.error(ServerErrorCode.UgqMetaverseOnline));
|
|
return;
|
|
}
|
|
|
|
var ugq_login_cache = await _redis.GetDatabase().StringGetAsync($"ugq_login:{user_guid}");
|
|
if(ugq_login_cache.HasValue == false)
|
|
{
|
|
context.Result = new BadRequestObjectResult(ApiResponseFactory.error(ServerErrorCode.UgqAuthRemoved));
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
|