forked from igk1972/netlify-cms-oauth-provider-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
224 lines (204 loc) · 6.39 KB
/
main.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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
package main
import (
// Refer to dotenv package first, to ensure it loads any .env settings before other init() functions try and use 'em.. isn't Golang great?
"crypto/hmac"
"crypto/sha1"
"encoding/hex"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"strings"
"github.com/gorilla/pat"
"github.com/joho/godotenv"
"github.com/markbates/goth"
"github.com/markbates/goth/gothic"
"github.com/markbates/goth/providers/bitbucket"
"github.com/markbates/goth/providers/github"
"github.com/markbates/goth/providers/gitlab"
)
var (
host = "localhost:3000"
base = host
)
const (
script = `<!DOCTYPE html><html><head><script>
if (!window.opener) {
window.opener = {
postMessage: function(action, origin) {
console.log(action, origin);
}
}
}
(function(status, provider, result) {
function receiveMessage(e) {
console.log("Receive message:", e);
// send message to main window with da app
window.opener.postMessage("authorization:" + provider + ":" + status + ":" + result, "*");
}
window.addEventListener("message", receiveMessage, false);
// Start handshake with parent
console.log("Sending message:", provider)
window.opener.postMessage(
"authorizing:" + provider,
"*"
);
})("%s", "%s", '%s')
</script></head><body></body></html>`
)
// GET /
func handleMain(res http.ResponseWriter, req *http.Request) {
log.Printf("handling root route '%v'\n", req)
res.Header().Set("Content-Type", "text/html; charset=utf-8")
res.WriteHeader(http.StatusOK)
res.Write([]byte(``))
}
// GET /auth Page redirecting after provider get param
func handleAuth(res http.ResponseWriter, req *http.Request) {
url := fmt.Sprintf("https://%s/auth/%s", base, req.FormValue("provider"))
fmt.Printf("redirect to %s\n", url)
http.Redirect(res, req, url, http.StatusTemporaryRedirect)
}
// GET /auth/provider Initial page redirecting by provider
func handleAuthProvider(res http.ResponseWriter, req *http.Request) {
log.Printf("handling /auth/provider\n")
gothic.BeginAuthHandler(res, req)
}
// GET /callback/{provider} Called by provider after authorization is granted
func handleCallbackProvider(res http.ResponseWriter, req *http.Request) {
var (
status string
result string
)
provider, errProvider := gothic.GetProviderName(req)
user, errAuth := gothic.CompleteUserAuth(res, req)
status = "error"
if errProvider != nil {
log.Printf("provider failed with '%s'\n", errProvider)
result = fmt.Sprintf("%s", errProvider)
} else if errAuth != nil {
log.Printf("auth failed with '%s'\n", errAuth)
result = fmt.Sprintf("%s", errAuth)
} else {
log.Printf("Logged in as %s user: %s (%s)\n", user.Provider, user.Email, user.AccessToken)
status = "success"
result = fmt.Sprintf(`{"token":"%s", "provider":"%s"}`, user.AccessToken, user.Provider)
}
res.Header().Set("Content-Type", "text/html; charset=utf-8")
res.WriteHeader(http.StatusOK)
res.Write([]byte(fmt.Sprintf(script, status, provider, result)))
}
// GET /refresh
func handleRefresh(res http.ResponseWriter, req *http.Request) {
log.Printf("refresh with '%v'\n", req)
res.Write([]byte(""))
}
// GET /success
func handleSuccess(res http.ResponseWriter, req *http.Request) {
log.Printf("success with '%v'\n", req)
res.Write([]byte(""))
}
// POST /callback/deploy
func handleDeploy(res http.ResponseWriter, req *http.Request) {
fmt.Printf("deploy from github..")
// Check signature in webhook
if hookSecret, ok := os.LookupEnv("GITHUB_HOOK_SECRET"); ok {
if isValidSignature(req, hookSecret) {
// Go ahead and run a deploy, ignoring the webhook content completely..
if hookExec, ok := os.LookupEnv("GITHUB_HOOK_EXEC"); ok {
cmd := exec.Command(hookExec)
err := cmd.Run()
if err != nil {
fmt.Printf("unable to run deploy command (%s): %v\n", hookExec, err)
} else {
fmt.Printf("ok\n")
}
} else {
fmt.Printf("missing GITHUB_HOOK_EXEC env\n")
}
} else {
fmt.Printf("invalid hook signature\n")
}
} else {
fmt.Printf("no secret, skipping\n")
}
res.Write([]byte(""))
}
// https://stackoverflow.com/questions/53242837/validating-github-webhook-hmac-signature-in-go
func isValidSignature(r *http.Request, key string) bool {
// Assuming a non-empty header
gotHash := strings.SplitN(r.Header.Get("X-Hub-Signature"), "=", 2)
if gotHash[0] != "sha1" {
return false
}
defer r.Body.Close()
b, err := ioutil.ReadAll(r.Body)
if err != nil {
fmt.Printf("Cannot read the request body: %s\n", err)
return false
}
hash := hmac.New(sha1.New, []byte(key))
if _, err := hash.Write(b); err != nil {
fmt.Printf("Cannot compute the HMAC for request: %s\n", err)
return false
}
expectedHash := hex.EncodeToString(hash.Sum(nil))
return gotHash[1] == expectedHash
}
func init() {
err := godotenv.Load()
if err != nil {
log.Println(".env file not present. Loading directly from environment")
}
if hostEnv, ok := os.LookupEnv("HOST"); ok {
host = hostEnv
}
if baseEnv, ok := os.LookupEnv("BASE"); ok {
base = baseEnv
}
var (
gitlabProvider goth.Provider
)
if gitlabServer, ok := os.LookupEnv("GITLAB_SERVER"); ok {
gitlabProvider = gitlab.NewCustomisedURL(
os.Getenv("GITLAB_KEY"), os.Getenv("GITLAB_SECRET"),
fmt.Sprintf("https://%s/callback/gitlab", base),
fmt.Sprintf("https://%s/oauth/authorize", gitlabServer),
fmt.Sprintf("https://%s/oauth/token", gitlabServer),
fmt.Sprintf("https://%s/api/v3/user", gitlabServer),
)
} else {
gitlabProvider = gitlab.New(
os.Getenv("GITLAB_KEY"), os.Getenv("GITLAB_SECRET"),
fmt.Sprintf("https://%s/callback/gitlab", base),
)
}
goth.UseProviders(
github.New(
os.Getenv("GITHUB_KEY"), os.Getenv("GITHUB_SECRET"),
fmt.Sprintf("https://%s/callback/github", base),
"repo",
),
bitbucket.New(
os.Getenv("BITBUCKET_KEY"), os.Getenv("BITBUCKET_SECRET"),
fmt.Sprintf("https://%s/callback/bitbucket", base),
"repo", // https://developer.github.com/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/
),
gitlabProvider,
)
}
func main() {
router := pat.New()
router.Post("/callback/deploy", handleDeploy)
router.Get("/callback/{provider}", handleCallbackProvider)
router.Get("/auth/{provider}", handleAuthProvider)
router.Get("/auth", handleAuth)
router.Get("/refresh", handleRefresh)
router.Get("/success", handleSuccess)
router.Get("/", handleMain)
http.Handle("/", router)
log.Printf("Started running on %s\n", host)
log.Println(http.ListenAndServe(host, nil))
}