/
gitlab.go
80 lines (66 loc) · 1.49 KB
/
gitlab.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package webhooks
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/go-git/go-git/v5/plumbing"
)
type Gitlab struct {
}
type glPush struct {
Ref string `json:"ref"`
}
func (g Gitlab) Handle(r *http.Request, hc *HookConf) (int, error) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return http.StatusBadRequest, err
}
err = g.handleToken(r, hc.Secret)
if err != nil {
return http.StatusBadRequest, err
}
event := r.Header.Get("X-Gitlab-Event")
if event == "" {
return http.StatusBadRequest, fmt.Errorf("header 'X-Gitlab-Event' missing")
}
switch event {
case "Push Hook":
err = g.handlePush(body, hc)
if err != nil {
return http.StatusBadRequest, err
}
default:
return http.StatusBadRequest, fmt.Errorf("cannot handle %q event", event)
}
return http.StatusOK, nil
}
func (g Gitlab) handleToken(r *http.Request, secret string) error {
token := r.Header.Get("X-Gitlab-Token")
if token != "" {
if secret == "" {
return fmt.Errorf("empty webhook secret")
} else {
if token != secret {
return fmt.Errorf("inavlid token")
}
}
}
return nil
}
func (g Gitlab) handlePush(body []byte, hc *HookConf) error {
var push glPush
err := json.Unmarshal(body, &push)
if err != nil {
return err
}
refName := plumbing.ReferenceName(push.Ref)
if refName.IsBranch() {
if refName != hc.RefName {
return fmt.Errorf("event: push to branch %s", refName)
}
} else {
return fmt.Errorf("refName is not a branch: %s", refName)
}
return nil
}