Skip to content

Commit

Permalink
style(code): use primary constructors
Browse files Browse the repository at this point in the history
  • Loading branch information
GZTimeWalker committed Aug 23, 2023
1 parent dde3700 commit dfd0a47
Show file tree
Hide file tree
Showing 35 changed files with 682 additions and 1,029 deletions.
2 changes: 1 addition & 1 deletion src/GZCTF.Test/GZCTF.Test.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="7.0.10" />
<PackageReference Include="Microsoft.AspNetCore.TestHost" Version="7.0.10" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.7.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.7.1" />
<PackageReference Include="xunit" Version="2.5.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
Expand Down
171 changes: 75 additions & 96 deletions src/GZCTF/Controllers/AccountController.cs

Large diffs are not rendered by default.

142 changes: 57 additions & 85 deletions src/GZCTF/Controllers/AdminController.cs

Large diffs are not rendered by default.

22 changes: 7 additions & 15 deletions src/GZCTF/Controllers/AssetsController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,10 @@ namespace GZCTF.Controllers;
[ApiController]
[ProducesResponseType(typeof(RequestResponse), StatusCodes.Status401Unauthorized)]
[ProducesResponseType(typeof(RequestResponse), StatusCodes.Status403Forbidden)]
public class AssetsController : ControllerBase
public class AssetsController(IFileRepository fileService, ILogger<AssetsController> logger) : ControllerBase
{
private readonly ILogger<AssetsController> _logger;
private readonly IFileRepository _fileRepository;
private readonly FileExtensionContentTypeProvider _extProvider = new();

public AssetsController(IFileRepository fileService, ILogger<AssetsController> logger)
{
_fileRepository = fileService;
_logger = logger;
}

/// <summary>
/// 获取文件接口
/// </summary>
Expand All @@ -46,7 +38,7 @@ public IActionResult GetFile([RegularExpression("[0-9a-f]{64}")] string hash, st

if (!System.IO.File.Exists(path))
{
_logger.Log($"尝试获取不存在的文件 [{hash[..8]}] {filename}", HttpContext.Connection?.RemoteIpAddress?.ToString() ?? "0.0.0.0", TaskStatus.NotFound, LogLevel.Warning);
logger.Log($"尝试获取不存在的文件 [{hash[..8]}] {filename}", HttpContext.Connection?.RemoteIpAddress?.ToString() ?? "0.0.0.0", TaskStatus.NotFound, LogLevel.Warning);
return NotFound(new RequestResponse("文件不存在", 404));
}

Expand Down Expand Up @@ -85,16 +77,16 @@ public async Task<IActionResult> Upload(List<IFormFile> files, [FromQuery] strin
{
if (file.Length > 0)
{
var res = await _fileRepository.CreateOrUpdateFile(file, filename, token);
_logger.SystemLog($"更新文件 [{res.Hash[..8]}] {filename ?? file.FileName} @ {file.Length} bytes", TaskStatus.Success, LogLevel.Debug);
var res = await fileService.CreateOrUpdateFile(file, filename, token);
logger.SystemLog($"更新文件 [{res.Hash[..8]}] {filename ?? file.FileName} @ {file.Length} bytes", TaskStatus.Success, LogLevel.Debug);
results.Add(res);
}
}
return Ok(results);
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
logger.LogError(ex, ex.Message);
return BadRequest(new RequestResponse("遇到IO错误"));
}
}
Expand All @@ -118,9 +110,9 @@ public async Task<IActionResult> Upload(List<IFormFile> files, [FromQuery] strin
[ProducesResponseType(typeof(RequestResponse), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Delete(string hash, CancellationToken token)
{
var result = await _fileRepository.DeleteFileByHash(hash, token);
var result = await fileService.DeleteFileByHash(hash, token);

_logger.SystemLog($"删除文件 [{hash[..8]}]...", result, LogLevel.Information);
logger.SystemLog($"删除文件 [{hash[..8]}]...", result, LogLevel.Information);

return result switch
{
Expand Down
183 changes: 79 additions & 104 deletions src/GZCTF/Controllers/EditController.cs

Large diffs are not rendered by default.

190 changes: 75 additions & 115 deletions src/GZCTF/Controllers/GameController.cs

Large diffs are not rendered by default.

30 changes: 9 additions & 21 deletions src/GZCTF/Controllers/InfoController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,23 +13,11 @@ namespace GZCTF.Controllers;
/// </summary>
[Route("api")]
[ApiController]
public class InfoController : ControllerBase
public class InfoController(IPostRepository postRepository,
IRecaptchaExtension recaptchaExtension,
IOptionsSnapshot<GlobalConfig> globalConfig,
IOptionsSnapshot<AccountPolicy> accountPolicy) : ControllerBase
{
private readonly IOptionsSnapshot<AccountPolicy> _accountPolicy;
private readonly IOptionsSnapshot<GlobalConfig> _globalConfig;
private readonly IPostRepository _postRepository;
private readonly IRecaptchaExtension _recaptchaExtension;

public InfoController(IPostRepository postRepository,
IRecaptchaExtension recaptchaExtension,
IOptionsSnapshot<GlobalConfig> globalConfig,
IOptionsSnapshot<AccountPolicy> accountPolicy)
{
_globalConfig = globalConfig;
_accountPolicy = accountPolicy;
_postRepository = postRepository;
_recaptchaExtension = recaptchaExtension;
}

/// <summary>
/// 获取最新文章
Expand All @@ -42,7 +30,7 @@ public InfoController(IPostRepository postRepository,
[HttpGet("Posts/Latest")]
[ProducesResponseType(typeof(PostInfoModel[]), StatusCodes.Status200OK)]
public async Task<IActionResult> GetLatestPosts(CancellationToken token)
=> Ok((await _postRepository.GetPosts(token)).Take(20).Select(PostInfoModel.FromPost));
=> Ok((await postRepository.GetPosts(token)).Take(20).Select(PostInfoModel.FromPost));

/// <summary>
/// 获取全部文章
Expand All @@ -55,7 +43,7 @@ public async Task<IActionResult> GetLatestPosts(CancellationToken token)
[HttpGet("Posts")]
[ProducesResponseType(typeof(PostInfoModel[]), StatusCodes.Status200OK)]
public async Task<IActionResult> GetPosts(CancellationToken token)
=> Ok((await _postRepository.GetPosts(token)).Select(PostInfoModel.FromPost));
=> Ok((await postRepository.GetPosts(token)).Select(PostInfoModel.FromPost));

/// <summary>
/// 获取文章详情
Expand All @@ -71,7 +59,7 @@ public async Task<IActionResult> GetPosts(CancellationToken token)
[ProducesResponseType(typeof(RequestResponse), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetPost(string id, CancellationToken token)
{
var post = await _postRepository.GetPostByIdFromCache(id, token);
var post = await postRepository.GetPostByIdFromCache(id, token);

if (post is null)
return NotFound(new RequestResponse("文章未找到", 404));
Expand All @@ -88,7 +76,7 @@ public async Task<IActionResult> GetPost(string id, CancellationToken token)
/// <response code="200">成功获取配置信息</response>
[HttpGet("Config")]
[ProducesResponseType(typeof(GlobalConfig), StatusCodes.Status200OK)]
public IActionResult GetGlobalConfig() => Ok(_globalConfig.Value);
public IActionResult GetGlobalConfig() => Ok(globalConfig.Value);

/// <summary>
/// 获取 Recaptcha SiteKey
Expand All @@ -100,5 +88,5 @@ public async Task<IActionResult> GetPost(string id, CancellationToken token)
[HttpGet("SiteKey")]
[ProducesResponseType(typeof(string), StatusCodes.Status200OK)]
public IActionResult GetRecaptchaSiteKey()
=> Ok(_accountPolicy.Value.UseGoogleRecaptcha ? _recaptchaExtension.SiteKey() : "NOTOKEN");
=> Ok(accountPolicy.Value.UseGoogleRecaptcha ? recaptchaExtension.SiteKey() : "NOTOKEN");
}
47 changes: 17 additions & 30 deletions src/GZCTF/Controllers/ProxyController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,11 @@ namespace GZCTF.Controllers;
/// </summary>
[ApiController]
[Route("api/[controller]")]
public class ProxyController : ControllerBase
public class ProxyController(ILogger<ProxyController> logger, IDistributedCache cache,
IOptions<ContainerProvider> provider, IContainerRepository containerRepository) : ControllerBase
{
private readonly ILogger<ProxyController> _logger;
private readonly IDistributedCache _cache;
private readonly IContainerRepository _containerRepository;

private readonly bool _enablePlatformProxy = false;
private readonly bool _enableTrafficCapture = false;
private readonly bool _enablePlatformProxy = provider.Value.PortMappingType == ContainerPortMappingType.PlatformProxy;
private readonly bool _enableTrafficCapture = provider.Value.EnableTrafficCapture;
private const int BUFFER_SIZE = 1024 * 4;
private const uint CONNECTION_LIMIT = 64;
private readonly JsonSerializerOptions _JsonOptions = new()
Expand All @@ -32,16 +29,6 @@ public class ProxyController : ControllerBase
WriteIndented = true,
};

public ProxyController(ILogger<ProxyController> logger, IDistributedCache cache,
IOptions<ContainerProvider> provider, IContainerRepository containerRepository)
{
_cache = cache;
_logger = logger;
_enablePlatformProxy = provider.Value.PortMappingType == ContainerPortMappingType.PlatformProxy;
_enableTrafficCapture = provider.Value.EnableTrafficCapture;
_containerRepository = containerRepository;
}

/// <summary>
/// 采用 websocket 代理 TCP 流量
/// </summary>
Expand All @@ -67,7 +54,7 @@ public async Task<IActionResult> ProxyForInstance(string id, CancellationToken t
if (!await IncrementConnectionCount(id))
return BadRequest(new RequestResponse("容器连接数已达上限"));

var container = await _containerRepository.GetContainerWithInstanceById(id, token);
var container = await containerRepository.GetContainerWithInstanceById(id, token);

if (container is null || container.Instance is null || !container.IsProxy)
return NotFound(new RequestResponse("不存在的容器"));
Expand Down Expand Up @@ -135,7 +122,7 @@ public async Task<IActionResult> ProxyForNoInstance(string id, CancellationToken
if (!HttpContext.WebSockets.IsWebSocketRequest)
return NoContent();

var container = await _containerRepository.GetContainerById(id, token);
var container = await containerRepository.GetContainerById(id, token);

if (container is null || container.InstanceId != 0 || !container.IsProxy)
return NotFound(new RequestResponse("不存在的容器"));
Expand Down Expand Up @@ -174,7 +161,7 @@ internal async Task<IActionResult> DoContainerProxy(string id, IPEndPoint client
}
catch (SocketException e)
{
_logger.SystemLog($"容器连接失败({e.SocketErrorCode}),可能正在启动中或请检查网络配置 -> {target.Address}:{target.Port}", TaskStatus.Failed, LogLevel.Warning);
logger.SystemLog($"容器连接失败({e.SocketErrorCode}),可能正在启动中或请检查网络配置 -> {target.Address}:{target.Port}", TaskStatus.Failed, LogLevel.Warning);
return new JsonResult(new RequestResponse($"容器连接失败({e.SocketErrorCode}", 418)) { StatusCode = 418 };
}

Expand All @@ -183,11 +170,11 @@ internal async Task<IActionResult> DoContainerProxy(string id, IPEndPoint client
try
{
var (tx, rx) = await RunProxy(stream, ws, token);
_logger.SystemLog($"[{id}] {client.Address} -> {target.Address}:{target.Port}, tx {tx}, rx {rx}", TaskStatus.Success, LogLevel.Debug);
logger.SystemLog($"[{id}] {client.Address} -> {target.Address}:{target.Port}, tx {tx}, rx {rx}", TaskStatus.Success, LogLevel.Debug);
}
catch (Exception e)
{
_logger.LogError(e, "代理过程发生错误");
logger.LogError(e, "代理过程发生错误");
}
finally
{
Expand Down Expand Up @@ -281,15 +268,15 @@ internal async Task<IActionResult> DoContainerProxy(string id, IPEndPoint client
internal async Task<bool> ValidateContainer(string id, CancellationToken token = default)
{
var key = CacheKey.ConnectionCount(id);
var bytes = await _cache.GetAsync(key, token);
var bytes = await cache.GetAsync(key, token);

// avoid DoS attack with cache -1
if (bytes is not null)
return BitConverter.ToInt32(bytes) >= 0;

var valid = await _containerRepository.ValidateContainer(id, token);
var valid = await containerRepository.ValidateContainer(id, token);

await _cache.SetAsync(key, BitConverter.GetBytes(valid ? 0 : -1), _validOption, token);
await cache.SetAsync(key, BitConverter.GetBytes(valid ? 0 : -1), _validOption, token);

return valid;
}
Expand All @@ -302,7 +289,7 @@ internal async Task<bool> ValidateContainer(string id, CancellationToken token =
internal async Task<bool> IncrementConnectionCount(string id)
{
var key = CacheKey.ConnectionCount(id);
var bytes = await _cache.GetAsync(key);
var bytes = await cache.GetAsync(key);

if (bytes is null)
return false;
Expand All @@ -312,7 +299,7 @@ internal async Task<bool> IncrementConnectionCount(string id)
if (count > CONNECTION_LIMIT)
return false;

await _cache.SetAsync(key, BitConverter.GetBytes(count + 1), _storeOption);
await cache.SetAsync(key, BitConverter.GetBytes(count + 1), _storeOption);

return true;
}
Expand All @@ -325,7 +312,7 @@ internal async Task<bool> IncrementConnectionCount(string id)
internal async Task DecrementConnectionCount(string id)
{
var key = CacheKey.ConnectionCount(id);
var bytes = await _cache.GetAsync(key);
var bytes = await cache.GetAsync(key);

if (bytes is null)
return;
Expand All @@ -334,11 +321,11 @@ internal async Task DecrementConnectionCount(string id)

if (count > 1)
{
await _cache.SetAsync(key, BitConverter.GetBytes(count - 1), _storeOption);
await cache.SetAsync(key, BitConverter.GetBytes(count - 1), _storeOption);
}
else
{
await _cache.SetAsync(key, BitConverter.GetBytes(0), _validOption);
await cache.SetAsync(key, BitConverter.GetBytes(0), _validOption);
}
}
}
Loading

0 comments on commit dfd0a47

Please sign in to comment.