Skip to content

Commit

Permalink
chore: format code
Browse files Browse the repository at this point in the history
  • Loading branch information
GZTimeWalker committed Oct 9, 2023
1 parent 3cd9244 commit 4460522
Show file tree
Hide file tree
Showing 85 changed files with 671 additions and 438 deletions.
30 changes: 20 additions & 10 deletions src/GZCTF/Controllers/AccountController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@ public async Task<IActionResult> Register([FromBody] RegisterModel model, Cancel
var mailDomain = model.Email.Split('@')[1];
if (!string.IsNullOrWhiteSpace(accountPolicy.Value.EmailDomainList) &&
accountPolicy.Value.EmailDomainList.Split(',').All(d => d != mailDomain))
return BadRequest(new RequestResponse(localizer[nameof(Resources.Program.Account_AvailableEmailDomain), accountPolicy.Value.EmailDomainList]));
return BadRequest(new RequestResponse(localizer[nameof(Resources.Program.Account_AvailableEmailDomain),
accountPolicy.Value.EmailDomainList]));

var user = new UserInfo { UserName = model.UserName, Email = model.Email, Role = Role.User };

Expand All @@ -69,7 +70,8 @@ public async Task<IActionResult> Register([FromBody] RegisterModel model, Cancel
UserInfo? current = await userManager.FindByEmailAsync(model.Email);

if (current is null)
return BadRequest(new RequestResponse(result.Errors.FirstOrDefault()?.Description ?? localizer[nameof(Resources.Program.Identity_UnknownError)]));
return BadRequest(new RequestResponse(result.Errors.FirstOrDefault()?.Description ??
localizer[nameof(Resources.Program.Identity_UnknownError)]));

if (await userManager.IsEmailConfirmedAsync(current))
return BadRequest(new RequestResponse(localizer[nameof(Resources.Program.Account_UserExisting)]));
Expand All @@ -84,7 +86,8 @@ public async Task<IActionResult> Register([FromBody] RegisterModel model, Cancel
await signInManager.SignInAsync(user, true);

logger.Log(Program.StaticLocalizer[nameof(Resources.Program.Account_UserRegisteredLog)], user, TaskStatus.Success);
return Ok(new RequestResponse<RegisterStatus>(localizer[nameof(Resources.Program.Account_UserRegistered)], RegisterStatus.LoggedIn, StatusCodes.Status200OK));
return Ok(new RequestResponse<RegisterStatus>(localizer[nameof(Resources.Program.Account_UserRegistered)], RegisterStatus.LoggedIn,
StatusCodes.Status200OK));
}

if (!accountPolicy.Value.EmailConfirmationRequired)
Expand Down Expand Up @@ -187,7 +190,8 @@ public async Task<IActionResult> PasswordReset([FromBody] PasswordResetModel mod
await userManager.ResetPasswordAsync(user, Codec.Base64.Decode(model.RToken), model.Password);

if (!result.Succeeded)
return BadRequest(new RequestResponse(result.Errors.FirstOrDefault()?.Description ?? localizer[nameof(Resources.Program.Identity_UnknownError)]));
return BadRequest(new RequestResponse(result.Errors.FirstOrDefault()?.Description ??
localizer[nameof(Resources.Program.Identity_UnknownError)]));

logger.Log(Program.StaticLocalizer[nameof(Resources.Program.Account_PasswordReset)], user, TaskStatus.Success);

Expand Down Expand Up @@ -218,7 +222,8 @@ public async Task<IActionResult> Verify([FromBody] AccountVerifyModel model)
IdentityResult result = await userManager.ConfirmEmailAsync(user, Codec.Base64.Decode(model.Token));

if (!result.Succeeded)
return Unauthorized(new RequestResponse(localizer[nameof(Resources.Program.Account_EmailVerificationFailed)], StatusCodes.Status401Unauthorized));
return Unauthorized(new RequestResponse(localizer[nameof(Resources.Program.Account_EmailVerificationFailed)],
StatusCodes.Status401Unauthorized));

logger.Log(Program.StaticLocalizer[nameof(Resources.Program.Account_EmailVerified)], user, TaskStatus.Success);
await signInManager.SignInAsync(user, true);
Expand All @@ -230,7 +235,8 @@ public async Task<IActionResult> Verify([FromBody] AccountVerifyModel model)
result = await userManager.UpdateAsync(user);

if (!result.Succeeded)
return BadRequest(new RequestResponse(result.Errors.FirstOrDefault()?.Description ?? localizer[nameof(Resources.Program.Identity_UnknownError)]));
return BadRequest(new RequestResponse(result.Errors.FirstOrDefault()?.Description ??
localizer[nameof(Resources.Program.Identity_UnknownError)]));

return Ok();
}
Expand Down Expand Up @@ -259,7 +265,8 @@ public async Task<IActionResult> LogIn([FromBody] LoginModel model, Cancellation
user ??= await userManager.FindByEmailAsync(model.UserName);

if (user is null)
return Unauthorized(new RequestResponse(localizer[nameof(Resources.Program.Account_IncorrectUserNameOrPassword)], StatusCodes.Status401Unauthorized));
return Unauthorized(new RequestResponse(localizer[nameof(Resources.Program.Account_IncorrectUserNameOrPassword)],
StatusCodes.Status401Unauthorized));

if (user.Role == Role.Banned)
return Unauthorized(new RequestResponse(localizer[nameof(Resources.Program.Account_UserDisabled)], StatusCodes.Status401Unauthorized));
Expand All @@ -272,7 +279,8 @@ public async Task<IActionResult> LogIn([FromBody] LoginModel model, Cancellation
SignInResult result = await signInManager.PasswordSignInAsync(user, model.Password, true, false);

if (!result.Succeeded)
return Unauthorized(new RequestResponse(localizer[nameof(Resources.Program.Account_IncorrectUserNameOrPassword)], StatusCodes.Status401Unauthorized));
return Unauthorized(new RequestResponse(localizer[nameof(Resources.Program.Account_IncorrectUserNameOrPassword)],
StatusCodes.Status401Unauthorized));

logger.Log(Program.StaticLocalizer[nameof(Resources.Program.Account_UserLogined)], user, TaskStatus.Success);

Expand Down Expand Up @@ -320,7 +328,8 @@ public async Task<IActionResult> Update([FromBody] ProfileUpdateModel model)
IdentityResult result = await userManager.UpdateAsync(user);

if (!result.Succeeded)
return BadRequest(new RequestResponse(result.Errors.FirstOrDefault()?.Description ?? localizer[nameof(Resources.Program.Identity_UnknownError)]));
return BadRequest(new RequestResponse(result.Errors.FirstOrDefault()?.Description ??
localizer[nameof(Resources.Program.Identity_UnknownError)]));

if (oldName != user.UserName)
logger.Log(Program.StaticLocalizer[nameof(Resources.Program.Account_UserUpdated), oldName!, user.UserName!], user, TaskStatus.Success);
Expand Down Expand Up @@ -348,7 +357,8 @@ public async Task<IActionResult> ChangePassword([FromBody] PasswordChangeModel m
IdentityResult result = await userManager.ChangePasswordAsync(user!, model.Old, model.New);

if (!result.Succeeded)
return BadRequest(new RequestResponse(result.Errors.FirstOrDefault()?.Description ?? localizer[nameof(Resources.Program.Identity_UnknownError)]));
return BadRequest(new RequestResponse(result.Errors.FirstOrDefault()?.Description ??
localizer[nameof(Resources.Program.Identity_UnknownError)]));

logger.Log(Program.StaticLocalizer[nameof(Resources.Program.Account_PasswordChanged)], user, TaskStatus.Success);

Expand Down
8 changes: 5 additions & 3 deletions src/GZCTF/Controllers/AdminController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,8 @@ public async Task<IActionResult> AddUsers([FromBody] UserCreateModel[] model, Ca
default:
await trans.RollbackAsync(token);
return BadRequest(
new RequestResponse(result.Errors.FirstOrDefault()?.Description ?? localizer[nameof(Resources.Program.Identity_UnknownError)]));
new RequestResponse(result.Errors.FirstOrDefault()?.Description ??
localizer[nameof(Resources.Program.Identity_UnknownError)]));
}

if (userInfo is not null)
Expand All @@ -158,7 +159,8 @@ public async Task<IActionResult> AddUsers([FromBody] UserCreateModel[] model, Ca
if (!result.Succeeded || userInfo is null)
{
await trans.RollbackAsync(token);
return BadRequest(new RequestResponse(result.Errors.FirstOrDefault()?.Description ?? localizer[nameof(Resources.Program.Identity_UnknownError)]));
return BadRequest(new RequestResponse(result.Errors.FirstOrDefault()?.Description ??
localizer[nameof(Resources.Program.Identity_UnknownError)]));
}
}

Expand Down Expand Up @@ -563,4 +565,4 @@ public async Task<IActionResult> DestroyInstance(Guid id, CancellationToken toke
public async Task<IActionResult> Files([FromQuery] int count = 50, [FromQuery] int skip = 0,
CancellationToken token = default) =>
Ok(new ArrayResponse<LocalFile>(await fileService.GetFiles(count, skip, token)));
}
}
8 changes: 6 additions & 2 deletions src/GZCTF/Controllers/AssetsController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ public IActionResult GetFile([RegularExpression("[0-9a-f]{64}")] string hash, st
if (!System.IO.File.Exists(path))
{
var ip = HttpContext.Connection.RemoteIpAddress?.ToString() ?? "0.0.0.0";
logger.Log(Program.StaticLocalizer[nameof(Resources.Program.Assets_FileNotFound), hash[..8], filename], ip, TaskStatus.NotFound, LogLevel.Warning);
logger.Log(Program.StaticLocalizer[nameof(Resources.Program.Assets_FileNotFound), hash[..8], filename], ip, TaskStatus.NotFound,
LogLevel.Warning);
return NotFound(new RequestResponse(localizer[nameof(Resources.Program.File_NotFound)], StatusCodes.Status404NotFound));
}

Expand Down Expand Up @@ -75,13 +76,16 @@ public async Task<IActionResult> Upload(List<IFormFile> files, [FromQuery] strin
{
List<LocalFile> results = new();
foreach (IFormFile file in files)
{
if (file.Length > 0)
{
LocalFile res = await fileService.CreateOrUpdateFile(file, filename, token);
logger.SystemLog(Program.StaticLocalizer[nameof(Resources.Program.Assets_UpdateFile), res.Hash[..8], filename ?? file.FileName, file.Length],
logger.SystemLog(
Program.StaticLocalizer[nameof(Resources.Program.Assets_UpdateFile), res.Hash[..8], filename ?? file.FileName, file.Length],
TaskStatus.Success, LogLevel.Debug);
results.Add(res);
}
}

return Ok(results);
}
Expand Down
16 changes: 11 additions & 5 deletions src/GZCTF/Controllers/EditController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -541,7 +541,10 @@ public async Task<IActionResult> UpdateGameChallenge([FromRoute] int id, [FromRo

if (game.IsActive)
await gameNoticeRepository.AddNotice(
new() { Game = game, Type = NoticeType.NewChallenge, Content = localizer[nameof(Resources.Program.Challenge_Created), res.Title] }, token);
new()
{
Game = game, Type = NoticeType.NewChallenge, Content = localizer[nameof(Resources.Program.Challenge_Created), res.Title]
}, token);
}
else
{
Expand All @@ -550,7 +553,8 @@ await gameNoticeRepository.AddNotice(

if (game.IsActive && res.IsEnabled && hintUpdated)
await gameNoticeRepository.AddNotice(
new() { Game = game, Type = NoticeType.NewHint, Content = localizer[nameof(Resources.Program.Challenge_HintUpdated), res.Title] }, token);
new() { Game = game, Type = NoticeType.NewHint, Content = localizer[nameof(Resources.Program.Challenge_HintUpdated), res.Title] },
token);

// always flush scoreboard
await cacheHelper.FlushScoreboardCache(game.Id, token);
Expand Down Expand Up @@ -602,7 +606,8 @@ public async Task<IActionResult> CreateTestContainer([FromRoute] int id, [FromRo
CPUCount = challenge.CPUCount ?? 1,
MemoryLimit = challenge.MemoryLimit ?? 64,
StorageLimit = challenge.StorageLimit ?? 256,
ExposedPort = challenge.ContainerExposePort ?? throw new ArgumentException(localizer[nameof(Resources.Program.Container_InvalidPort)])
ExposedPort = challenge.ContainerExposePort ??
throw new ArgumentException(localizer[nameof(Resources.Program.Container_InvalidPort)])
}, token);

if (container is null)
Expand All @@ -611,7 +616,8 @@ public async Task<IActionResult> CreateTestContainer([FromRoute] int id, [FromRo
challenge.TestContainer = container;
await challengeRepository.SaveAsync(token);

logger.Log(Program.StaticLocalizer[nameof(Resources.Program.Container_TestContainerCreated), container.ContainerId], user, TaskStatus.Success);
logger.Log(Program.StaticLocalizer[nameof(Resources.Program.Container_TestContainerCreated), container.ContainerId], user,
TaskStatus.Success);

return Ok(ContainerInfoModel.FromContainer(container));
}
Expand Down Expand Up @@ -780,4 +786,4 @@ public async Task<IActionResult> RemoveFlag([FromRoute] int id, [FromRoute] int

return Ok(await challengeRepository.RemoveFlag(challenge, fId, token));
}
}
}
3 changes: 1 addition & 2 deletions src/GZCTF/Controllers/ExerciseController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,4 @@ public class ExerciseController(ILogger<ExerciseController> logger,
IExerciseInstanceRepository exerciseInstanceRepository,
IStringLocalizer<Program> localizer) : ControllerBase
{

}
}
39 changes: 20 additions & 19 deletions src/GZCTF/Controllers/GameController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -840,7 +840,8 @@ public async Task<IActionResult> SubmitWriteup([FromRoute] int id, IFormFile fil

await participationRepository.SaveAsync(token);

logger.Log(Program.StaticLocalizer[nameof(Resources.Program.Game_WriteupSubmitted), team.Name, game.Title], context.User!, TaskStatus.Success);
logger.Log(Program.StaticLocalizer[nameof(Resources.Program.Game_WriteupSubmitted), team.Name, game.Title], context.User!,
TaskStatus.Success);

return Ok();
}
Expand Down Expand Up @@ -881,10 +882,8 @@ public async Task<IActionResult> CreateContainer([FromRoute] int id, [FromRoute]
return BadRequest(new RequestResponse(localizer[nameof(Resources.Program.Game_ContainerCreationNotAllowed)]));

if (DateTimeOffset.UtcNow - instance.LastContainerOperation < TimeSpan.FromSeconds(10))
return new JsonResult(new RequestResponse(localizer[nameof(Resources.Program.Game_OperationTooFrequent)], StatusCodes.Status429TooManyRequests))
{
StatusCode = StatusCodes.Status429TooManyRequests
};
return new JsonResult(new RequestResponse(localizer[nameof(Resources.Program.Game_OperationTooFrequent)],
StatusCodes.Status429TooManyRequests)) { StatusCode = StatusCodes.Status429TooManyRequests };

if (instance.Container is not null)
{
Expand All @@ -896,13 +895,14 @@ public async Task<IActionResult> CreateContainer([FromRoute] int id, [FromRoute]

return await gameInstanceRepository.CreateContainer(instance, context.Participation!.Team, context.User!,
context.Game!.ContainerCountLimit, token) switch
{
null or (TaskStatus.Failed, null) => BadRequest(new RequestResponse(localizer[nameof(Resources.Program.Game_ContainerCreationFailed)])),
(TaskStatus.Denied, null) => BadRequest(
new RequestResponse(localizer[nameof(Resources.Program.Game_ContainerNumberLimitExceeded), context.Game.ContainerCountLimit])),
(TaskStatus.Success, var x) => Ok(ContainerInfoModel.FromContainer(x!)),
_ => throw new NotImplementedException()
};
{
null or (TaskStatus.Failed, null) => BadRequest(
new RequestResponse(localizer[nameof(Resources.Program.Game_ContainerCreationFailed)])),
(TaskStatus.Denied, null) => BadRequest(
new RequestResponse(localizer[nameof(Resources.Program.Game_ContainerNumberLimitExceeded), context.Game.ContainerCountLimit])),
(TaskStatus.Success, var x) => Ok(ContainerInfoModel.FromContainer(x!)),
_ => throw new NotImplementedException()
};
}

/// <summary>
Expand Down Expand Up @@ -989,10 +989,8 @@ public async Task<IActionResult> DeleteContainer([FromRoute] int id, [FromRoute]
return BadRequest(new RequestResponse(localizer[nameof(Resources.Program.Game_ContainerNotCreated)]));

if (DateTimeOffset.UtcNow - instance.LastContainerOperation < TimeSpan.FromSeconds(10))
return new JsonResult(new RequestResponse(localizer[nameof(Resources.Program.Game_OperationTooFrequent)], StatusCodes.Status429TooManyRequests))
{
StatusCode = StatusCodes.Status429TooManyRequests
};
return new JsonResult(new RequestResponse(localizer[nameof(Resources.Program.Game_OperationTooFrequent)],
StatusCodes.Status429TooManyRequests)) { StatusCode = StatusCodes.Status429TooManyRequests };

var destroyId = instance.Container.ContainerId;

Expand All @@ -1011,7 +1009,9 @@ await gameEventRepository.AddEvent(
Content = localizer[nameof(Resources.Program.Game_ContainerDeletedEvent), instance.Challenge.Title, instance.Challenge.Id]
}, token);

logger.Log(Program.StaticLocalizer[nameof(Resources.Program.Game_ContainerDeleted), context.Participation!.Team.Name, instance.Challenge.Title, destroyId],
logger.Log(
Program.StaticLocalizer[nameof(Resources.Program.Game_ContainerDeleted), context.Participation!.Team.Name, instance.Challenge.Title,
destroyId],
context.User, TaskStatus.Success);

return Ok();
Expand Down Expand Up @@ -1046,7 +1046,8 @@ async Task<ContextInfo> GetContextInfo(int id, int challengeId = 0, bool withFla
GameChallenge? challenge = await challengeRepository.GetChallenge(id, challengeId, withFlag, token);

if (challenge is null)
return res.WithResult(NotFound(new RequestResponse(localizer[nameof(Resources.Program.Challenge_NotFound)], StatusCodes.Status404NotFound)));
return res.WithResult(NotFound(new RequestResponse(localizer[nameof(Resources.Program.Challenge_NotFound)],
StatusCodes.Status404NotFound)));

res.Challenge = challenge;
}
Expand Down Expand Up @@ -1080,4 +1081,4 @@ public ContextInfo WithResult(IActionResult res)
return this;
}
}
}
}
12 changes: 6 additions & 6 deletions src/GZCTF/Controllers/ProxyController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ public async Task<IActionResult> ProxyForInstance(Guid id, CancellationToken tok

var enable = _enableTrafficCapture && container.EnableTrafficCapture;

byte[]? metadata = enable ? container.GenerateMetadata(_jsonOptions) : null;
var metadata = enable ? container.GenerateMetadata(_jsonOptions) : null;

IPEndPoint client = new(clientIp, clientPort);
IPEndPoint target = new(ipAddress, container.Port);
Expand Down Expand Up @@ -148,12 +148,12 @@ async Task<IActionResult> DoContainerProxy(Guid id, IPEndPoint client, IPEndPoin
}
catch (SocketException e)
{
logger.SystemLog(Program.StaticLocalizer[nameof(Resources.Program.Proxy_ContainerConnectionFailedLog), e.SocketErrorCode, $"{target.Address}:{target.Port}"],
logger.SystemLog(
Program.StaticLocalizer[nameof(Resources.Program.Proxy_ContainerConnectionFailedLog), e.SocketErrorCode,
$"{target.Address}:{target.Port}"],
TaskStatus.Failed, LogLevel.Debug);
return new JsonResult(new RequestResponse(localizer[nameof(Resources.Program.Proxy_ContainerConnectionFailed), e.SocketErrorCode], StatusCodes.Status418ImATeapot))
{
StatusCode = StatusCodes.Status418ImATeapot
};
return new JsonResult(new RequestResponse(localizer[nameof(Resources.Program.Proxy_ContainerConnectionFailed), e.SocketErrorCode],
StatusCodes.Status418ImATeapot)) { StatusCode = StatusCodes.Status418ImATeapot };
}

using WebSocket ws = await HttpContext.WebSockets.AcceptWebSocketAsync();
Expand Down
Loading

0 comments on commit 4460522

Please sign in to comment.