This repository has been archived by the owner on Jan 4, 2018. It is now read-only.
/
githubAuth.go
203 lines (172 loc) · 5.49 KB
/
githubAuth.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"github.com/Sirupsen/logrus"
"github.com/satori/go.uuid"
"gopkg.in/bufio.v1"
)
type githubHook struct {
Name string `json:"name"`
Active bool `json:"active"`
Events []string `json:"events"`
Config githubHookConfig `json:"config"`
}
type githubHookConfig struct {
URL string `json:"url"`
ContentType string `json:"content_type"`
}
func handleOauthGithubInit(res http.ResponseWriter, r *http.Request) {
sess, _ := sessionStore.Get(r, "GoBuilderSession")
scopes := strings.Join([]string{
"write:repo_hook", // We want to write the webhook to execute a gobuilder build
}, ",")
if code := r.URL.Query().Get("code"); code != "" {
state := sess.Values["gh_oauth_state"].(string)
if r.URL.Query().Get("state") != state {
sess.AddFlash("Something went wrong while authenticating you. Please try again.", "alert_error")
sess.Save(r, res)
http.Redirect(res, r, "/", http.StatusFound)
return
}
resp, err := http.PostForm("https://github.com/login/oauth/access_token", url.Values{
"client_id": {cfg.GitHub.ClientID},
"client_secret": {cfg.GitHub.ClientSecret},
"code": {code},
"state": {state},
})
if err != nil {
log.WithField("error", err).Error("Fetching OAuth2 AccessKey failed")
sess.AddFlash("Something went wrong while authenticating you. Please try again.", "alert_error")
sess.Save(r, res)
http.Redirect(res, r, "/", http.StatusFound)
return
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
accessInformation, _ := url.ParseQuery(string(body))
if accessInformation.Get("scope") != scopes {
sess.AddFlash("You denied some access rights. Unable to work that way.", "alert_error")
sess.Save(r, res)
http.Redirect(res, r, "/", http.StatusFound)
return
}
sess.Values["access_token"] = accessInformation.Get("access_token")
sess.Save(r, res)
http.Redirect(res, r, "/", http.StatusFound)
return
}
query := url.Values{}
redirURL, _ := url.Parse("https://github.com/login/oauth/authorize")
query.Set("client_id", cfg.GitHub.ClientID)
query.Set("scope", scopes)
u := uuid.NewV4().String()
sess.Values["gh_oauth_state"] = u
query.Set("state", u)
sess.Save(r, res)
redirURL.RawQuery = query.Encode()
http.Redirect(res, r, redirURL.String(), http.StatusFound)
}
func handleOauthGithubLogout(res http.ResponseWriter, r *http.Request) {
sess, _ := sessionStore.Get(r, "GoBuilderSession")
delete(sess.Values, "access_token")
sess.Save(r, res)
http.Redirect(res, r, "/", http.StatusFound)
}
func getGithubUsername(r *http.Request) string {
sess, _ := sessionStore.Get(r, "GoBuilderSession")
if _, ok := sess.Values["access_token"].(string); !ok {
return ""
}
resp, err := http.Get("https://api.github.com/user?access_token=" + sess.Values["access_token"].(string))
if err != nil {
log.WithField("error", err.Error()).Error("Unable to fetch GitHub username")
return ""
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
log.Errorf("GitHub Status %d", resp.StatusCode)
return ""
}
d := struct {
Login string `json:"login"`
}{}
json.NewDecoder(resp.Body).Decode(&d)
return d.Login
}
func addGithubWebhook(res http.ResponseWriter, r *http.Request, repo string) {
sess, _ := sessionStore.Get(r, "GoBuilderSession")
hookURL := strings.TrimRight(cfg.BaseURL, "/") + "/api/v1/webhook/github"
if token, ok := sess.Values["access_token"].(string); !ok || len(token) == 0 {
return
}
re := regexp.MustCompile("^github.com/([^/]+)/([^/]+)")
if !re.MatchString(repo) {
log.WithField("repo", repo).Error("Tried to add webhook to non-github-repo")
return
}
matches := re.FindStringSubmatch(repo)
owner := matches[1]
repomatch := matches[2]
resp, err := http.Get(fmt.Sprintf("https://api.github.com/repos/%s/%s/hooks?access_token=%s", owner, repomatch, sess.Values["access_token"].(string)))
if err != nil {
log.WithFields(logrus.Fields{
"error": err.Error(),
"repo": repo,
}).Error("Unable to fetch hooks for Repo")
sess.AddFlash("Could not access the hooks for your repository.", "alert_error")
sess.Save(r, res)
return
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
log.Errorf("GitHub Status %d", resp.StatusCode)
return
}
t := []githubHook{}
json.NewDecoder(resp.Body).Decode(&t)
for _, v := range t {
if v.Config.URL == hookURL {
// We found our hook, we're happy
return
}
}
hook := githubHook{
Name: "web",
Active: true,
Events: []string{"push"},
Config: githubHookConfig{
URL: hookURL,
ContentType: "json",
},
}
body, _ := json.Marshal(hook)
req, _ := http.NewRequest("POST", fmt.Sprintf("https://api.github.com/repos/%s/%s/hooks", owner, repomatch), bufio.NewBuffer(body))
req.Header.Set("Authorization", "token "+sess.Values["access_token"].(string))
setResp, err := http.DefaultClient.Do(req)
if err != nil {
log.WithFields(logrus.Fields{
"error": err.Error(),
"repo": repo,
}).Error("Unable to set hook for Repo")
sess.AddFlash("Could not set the hook for your repository.", "alert_error")
sess.Save(r, res)
return
}
defer setResp.Body.Close()
if setResp.StatusCode != 201 {
body, _ = ioutil.ReadAll(setResp.Body)
log.WithFields(logrus.Fields{
"repo": repo,
"status": strconv.FormatInt(int64(setResp.StatusCode), 10),
}).Error("Unable to set hook for Repo")
sess.AddFlash("Could not set the hook for your repository.", "alert_error")
sess.Save(r, res)
}
}