gitea-github-proxy/api/routes_webhooks.go

73 lines
1.8 KiB
Go
Raw Normal View History

package api
import (
"code.gitea.io/gitea/modules/structs"
"code.gitea.io/sdk/gitea"
"encoding/json"
"git.lumeweb.com/LumeWeb/gitea-github-proxy/config"
"go.uber.org/zap"
"gorm.io/gorm"
"net/http"
)
type webhookApi struct {
config *config.Config
logger *zap.Logger
db *gorm.DB
whm *WebhookManager
}
func newWebhookApi(cfg *config.Config, db *gorm.DB, logger *zap.Logger, whm *WebhookManager) *webhookApi {
return &webhookApi{config: cfg, db: db, logger: logger, whm: whm}
}
func (a *webhookApi) handlePullRequest(w http.ResponseWriter, r *http.Request) {
webhook := a.getWebhookData(w, r)
payload := &structs.PullRequestPayload{}
err := json.Unmarshal(webhook, payload)
if a.unmarshallError(w, err) {
return
}
}
func setupWebhookRoutes(params RouteParams) {
cfg := params.Config
db := params.Db
logger := params.Logger
r := params.R
whm := params.WebhookManager
webhookApi := newWebhookApi(cfg, db, logger, whm)
webhookRouter := r.PathPrefix("/api").Subrouter()
webhookRouter.Use(gitea.VerifyWebhookSignatureMiddleware(cfg.GiteaWebHookSecret))
webhookRouter.Use(storeWebhookDataMiddleware(logger))
webhookRouter.HandleFunc("/webhooks/pull_request", webhookApi.handlePullRequest).Methods("POST")
}
func (a *webhookApi) getWebhookData(w http.ResponseWriter, r *http.Request) []byte {
return getWebhookData(r, a.logger)
}
func (a *webhookApi) unmarshallError(w http.ResponseWriter, err error) bool {
if err != nil {
a.logger.Error("Failed to unmarshal webhook data", zap.Error(err))
http.Error(w, "Failed to unmarshal webhook data", http.StatusInternalServerError)
}
return err != nil
}
func getWebhookData(r *http.Request, logger *zap.Logger) []byte {
webhook := r.Context().Value(WEBHOOK_CONTEXT_KEY)
webhookData, ok := webhook.([]byte)
if !ok {
logger.Fatal("Failed to get webhook data from context")
}
return webhookData
}