Skip to content

Commit

Permalink
add more event for GitHub
Browse files Browse the repository at this point in the history
  • Loading branch information
azhe403 committed Jun 10, 2024
1 parent 3f58885 commit 66424b1
Show file tree
Hide file tree
Showing 5 changed files with 33 additions and 21 deletions.
2 changes: 2 additions & 0 deletions backend/ZiziBot.Application/Core/ApiRequestBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,6 @@ public class ApiRequestBase<T> : IRequest<ApiResponseBase<T>>
[BindNever]
[SwaggerIgnore]
public string? BearerToken => Authorization?.Replace("Bearer ", string.Empty);

public async Task<string> RequestBody() => await HttpContextAccessor?.HttpContext?.GetBodyAsync();
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,6 @@ namespace ZiziBot.Application.Handlers.RestApis.Webhook;

public class PostWebhookPayloadRequest : ApiRequestBase<PostWebhookPayloadResponseDto>
{
[FromBody]
public object? Content { get; set; }

[FromRoute(Name = "targetId")]
public string targetId { get; set; }

Expand Down Expand Up @@ -50,12 +47,12 @@ CancellationToken cancellationToken
var stopwatch = Stopwatch.StartNew();
var webhookSource = request.UserAgent.GetWebHookSource();
var webhookHeader = WebhookHeader.Parse(request.Headers);
var content = $"{request.Content}";
var content = await request.RequestBody();
var response = new ApiResponseBase<PostWebhookPayloadResponseDto>() {
TransactionId = request.HttpContextAccessor?.HttpContext?.TraceIdentifier ?? string.Empty
};

if (request.Content == null)
if (content == null)
{
return response.BadRequest("Webhook payload is empty");
}
Expand Down
14 changes: 14 additions & 0 deletions backend/ZiziBot.Application/Services/WebhookService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,20 @@ public async Task<WebhookResponseBase<bool>> ParseGitHub(WebhookHeader header, s
.Bold("Status: ").TextBr(deploymentEvent.Deployment.Task);
break;

case WebhookEventType.WorkflowRun:
var workflowRunEvent = payload.Deserialize<WorkflowRunEvent>();
htmlMessage.Bold("Name: ").TextBr(workflowRunEvent.WorkflowRun.Name)
.Bold("Status: ").TextBr(workflowRunEvent.WorkflowRun.Status.StringValue)
.Bold("Actor: ").TextBr(workflowRunEvent.WorkflowRun.Actor.Login);
break;

case WebhookEventType.CheckSuite:
var checkSuiteEvent = payload.Deserialize<CheckSuiteEvent>();
htmlMessage.Bold("Name: ").TextBr(checkSuiteEvent.CheckSuite.App.Name)
.Bold("Status: ").TextBr(checkSuiteEvent.CheckSuite.Status.StringValue)
.Bold("Conclusion: ").TextBr(checkSuiteEvent.CheckSuite.Conclusion.StringValue);
break;

default:
break;
}
Expand Down
8 changes: 8 additions & 0 deletions backend/ZiziBot.Parsers/SerializationUtil.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,12 @@ public static string ToHeaderRawKv(this IHeaderDictionary headerDictionary)
{
return headerDictionary.Select(kv => $"{kv.Key}: {kv.Value}").StrJoin("\n");
}

public static async Task<string> GetBodyAsync(this HttpContext? context)
{
if (context == null) return string.Empty;

using var reader = new StreamReader(context.Request.Body);
return await reader.ReadToEndAsync();
}
}
23 changes: 7 additions & 16 deletions backend/ZiziBot.WebApi/RestApiExtension.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,29 +34,25 @@ public static IServiceCollection ConfigureApi(this IServiceCollection services)
options.Conventions.Add(new RouteTokenTransformerConvention(new SlugifyParameterTransformer()));
}
)
.AddNewtonsoftJson()
.ConfigureApiBehaviorOptions(options => {
options.InvalidModelStateResponseFactory = context => {
var transactionId = context.HttpContext.Request.Headers[HeaderKey.TransactionId].FirstOrDefault();
var errorDetails = context.ModelState
.Where(entry => entry.Value?.ValidationState == ModelValidationState.Invalid)
.Select(key => new
{
.Select(key => new {
Id = key.Key,
Field = key.Key.Split('.').Last(),
Message = key.Value?.Errors.Select(e => e.ErrorMessage)
}).ToList();
var errors = errorDetails.SelectMany(x => x.Message).ToList();
return new BadRequestObjectResult(new ApiResponseBase<object>()
{
return new BadRequestObjectResult(new ApiResponseBase<object>() {
StatusCode = HttpStatusCode.BadRequest,
TransactionId = transactionId,
Message = "Please ensure your request",
Result = new
{
Result = new {
Error = errors.Aggregate((a, b) => $"{a}\n{b}"),
Errors = errors,
ErrorDetails = errorDetails,
Expand All @@ -71,8 +67,7 @@ public static IServiceCollection ConfigureApi(this IServiceCollection services)
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(o => {
o.TokenValidationParameters = new TokenValidationParameters
{
o.TokenValidationParameters = new TokenValidationParameters {
ValidIssuer = jwtConfig.Issuer,
ValidAudience = jwtConfig.Audience,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfig.Key)),
Expand All @@ -82,16 +77,14 @@ public static IServiceCollection ConfigureApi(this IServiceCollection services)
ValidateIssuerSigningKey = true
};
o.Events = new JwtBearerEvents
{
o.Events = new JwtBearerEvents {
OnChallenge = async context => {
context.HandleResponse();
context.Response.StatusCode = 401;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(
new ApiResponseBase<bool>()
{
new ApiResponseBase<bool>() {
StatusCode = HttpStatusCode.Unauthorized,
Message = "Please ensure you have a valid token"
}
Expand Down Expand Up @@ -154,9 +147,7 @@ public static WebApplication ConfigureApi(this WebApplication app)
app.ConfigureRateLimiter();

app.UseSwagger();
app.UseSwaggerUI(options => {
options.DefaultModelsExpandDepth(-1);
});
app.UseSwaggerUI(options => { options.DefaultModelsExpandDepth(-1); });

return app;
}
Expand Down

0 comments on commit 66424b1

Please sign in to comment.