-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
339 lines (274 loc) · 8.05 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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
package main
import (
"encoding/base64"
"encoding/json"
"flag"
"fmt"
"log"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"text/template"
"time"
"github.com/gin-gonic/gin"
"github.com/tmtk75/go-oauth2/oauth2"
"github.com/tmtk75/go-oauth2/oauth2/github"
)
type templateHandler struct {
once sync.Once
filename string
templ *template.Template
}
func (t *templateHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
log.Println("/login or /")
t.once.Do(func() {
t.templ = template.Must(template.ParseFiles(filepath.Join("client", t.filename)))
})
data := map[string]interface{}{
"Host": r.Host,
}
if authCookie, err := r.Cookie("auth"); err == nil {
var v map[string]interface{}
log.Println("authCookie: ", authCookie)
b, _ := base64.StdEncoding.DecodeString(authCookie.Value)
err := json.Unmarshal([]byte(b), &v)
if err != nil {
log.Fatalf("Failed to Unmarshal: %v\n", err)
}
data["UserData"] = v
}
data["Providers"] = oauth2.Providers()
t.templ.Execute(w, data)
}
type authHandler struct {
next http.Handler
}
func (h *authHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
log.Println("/-1")
if _, err := r.Cookie("auth"); err == http.ErrNoCookie {
w.Header().Set("location", "/login")
w.WriteHeader(http.StatusTemporaryRedirect)
} else if err != nil {
panic(err.Error())
} else {
h.next.ServeHTTP(w, r)
}
}
func mustAuth(handler http.Handler) http.Handler {
return &authHandler{next: handler}
}
func loginHandler(w http.ResponseWriter, r *http.Request) {
log.Println("/auth*")
segs := strings.Split(r.URL.Path, "/")
action := segs[2]
providerName := segs[3]
switch action {
case "login":
loginURL := oauth2.ProviderByName(providerName).Config().AuthCodeURL("state")
w.Header().Set("Location", loginURL)
w.WriteHeader(http.StatusTemporaryRedirect)
case "callback":
code := r.FormValue("code")
provider := oauth2.ProviderByName(providerName)
profile, err := oauth2.ProfileByCode(provider, code)
if err != nil {
log.Println("Failed to Profile !!!! ", providerName, "-", err)
// c.JSON(401, gin.H{"status": "unauthorized"})
// Write([]byte) (int, error)
// w.WriteHeader(http.StatusUnauthorized)
// return
} else {
account := profile.Nickname()
if account != "" && profile.Token() != nil && profile.Token().AccessToken != "" {
fmt.Print("github access token:", profile.Token().AccessToken)
SetUserOrJustUpdateToken(account, profile.Token().AccessToken)
saveSession(w, profile)
} else {
log.Println("Got Profile but info something worng !!!! ")
// w.WriteHeader(http.StatusUnauthorized)
// return
}
}
// saveSession(w, profile)
w.Header()["Location"] = []string{"/"}
w.WriteHeader(http.StatusTemporaryRedirect)
default:
w.WriteHeader(http.StatusNotFound)
fmt.Fprintf(w, "Unsupported action: %s", action)
}
}
func saveSession(w http.ResponseWriter, u oauth2.Profile) {
msg, _ := json.Marshal(map[string]interface{}{
"name": u.Nickname(),
"authToken": u.Token().AccessToken,
})
http.SetCookie(w, &http.Cookie{
Name: "auth",
Value: base64.StdEncoding.EncodeToString([]byte(msg)),
Path: "/",
Expires: time.Now().AddDate(1, 0, 0), //Add(24 * time.Hour),
})
}
var userMap map[string]*GitHubUser
var mux sync.Mutex
func init() {
log.Println("main init !!!!!!")
callbackURL := os.Getenv("CallbackURL")
oauth2.WithProviders(
github.New(oauth2.NewConfig(oauth2.GITHUB, callbackURL+oauth2.GITHUB)),
)
// prepare userMap
userMap = make(map[string]*GitHubUser)
_ = userMap
}
func getReposActionHandler(c *gin.Context) {
log.Println("get-reindex in getReposActionHandler")
r := c.Request
if authCookie, err := r.Cookie("auth"); err == nil {
var v map[string]interface{}
b, _ := base64.StdEncoding.DecodeString(authCookie.Value)
err := json.Unmarshal([]byte(b), &v)
if err != nil {
log.Fatalf("Failed to Unmarshal: %v\n", err)
} else if account2, ok2 := v["name"]; ok2 == true {
account := account2.(string)
if user, _ := GetUser(account); user != nil {
log.Println("found out account, and reset to notstart index:", user.Account)
user.Status = NOTSTART
SetUser(user.Account, *user)
}
}
}
cleanCookieAndToLoginPage(c)
// c.JSON(http.StatusUnauthorized, gin.H{
// "message": "",
// })
}
func getReposHandler(c *gin.Context) {
log.Println("/repos")
r := c.Request
ok := false
message := "no valid auth"
// if userMap == nil {
// log.Println("usermap is nil")
// }
if authCookie, err := r.Cookie("auth"); err == nil {
var v map[string]interface{}
b, _ := base64.StdEncoding.DecodeString(authCookie.Value)
err := json.Unmarshal([]byte(b), &v)
if err != nil {
log.Fatalf("Failed to Unmarshal: %v\n", err)
} else if account2, ok2 := v["name"]; ok2 == true {
account := account2.(string)
if user, _ := GetUser(account); user != nil {
log.Println("found out account:", user.Account)
// log.Println("cookie:", v)
tokenInCookie := v["authToken"].(string)
// log.Println("found out after token")
// log.Println("tokenIncookie:", tokenInCookie)
// log.Println("user.Tokens in DB:", user)
// try to compare tokens
for _, token := range user.Tokens {
if token == tokenInCookie {
log.Println("found out the same token")
ok = true
break
}
}
if ok {
// log.Println("found out the same token in DB")
// 之後再做todo 1.
// 1. 如果再run當中的就不要再new/run了,
// p.s. . 假設前一個token還可以用,
// 那此時第二個同一user的token好像會已經先傳回去? 好像同時兩個token也還好,
if user.Status == NOTSTART {
// TODO: if two clients use the same account simutaneously, still have race condition problems
go user.IndexStarredInfo(tokenInCookie)
}
c.JSON(200, gin.H{
"status": user.Status,
"numOfStarred": user.NumOfStarred,
"githubAccount": account,
})
} else {
log.Println("can not found out the same token in DB")
}
} else {
log.Println("does not have the same key, force logout")
http.SetCookie(c.Writer, &http.Cookie{
Name: "auth",
Value: "",
Path: "/",
MaxAge: -1,
})
}
}
} else {
message = "does not have cookie"
}
if ok == false {
c.JSON(http.StatusUnauthorized, gin.H{
"message": message,
})
}
}
func cleanCookieAndToLoginPage(c *gin.Context) {
http.SetCookie(c.Writer, &http.Cookie{
Name: "auth",
Value: "",
Path: "/",
MaxAge: -1,
})
w := c.Writer
// w.Header()["Location"] = []string{"/login"}
w.Header().Set("location", "/login")
w.WriteHeader(http.StatusTemporaryRedirect)
}
func sendTwilioAlert(repo string) {
fmt.Println("send twilio alert")
// accountSid := ""
// authToken := ""
// twilio := gotwilio.NewTwilioClient(accountSid, authToken)
//
// from := ""
// to := ""
// message := "Over 10k limit for Algolia api:" + repo
// twilio.SendSMS(from, to, message, "", "")
}
func main() {
// os.Setenv("HTTP_PROXY", os.Getenv("FIXIE_URL"))
// os.Setenv("HTTPS_PROXY", os.Getenv("FIXIE_URL"))
fmt.Println("start main")
port := os.Getenv("PORT")
if port == "" {
port = "5000"
}
port2 := fmt.Sprintf(":%s", port)
var addr = flag.String("addr", port2, "application address")
flag.Parse()
//
r := gin.Default()
r.Use(gin.Logger())
r.Use(gin.Recovery())
r.Static("/build-client", "build-client")
r.Static("/styles", "client/styles")
r.GET("/", gin.WrapH(mustAuth(&templateHandler{filename: "index.html"})))
r.GET("/login", gin.WrapH(&templateHandler{filename: "templates/login.html"}))
r.GET("/logout", cleanCookieAndToLoginPage)
r.GET("/auth/*action", gin.WrapF(loginHandler))
// r.GET("/clock", gin.WrapH(websocket.Handler(func(ws *websocket.Conn) {
// for {
// fmt.Fprint(ws, "{When:'"+time.Now().Format(time.RFC3339)+"'}")
// time.Sleep(1 * time.Second)
// }
// })))
r.GET("/repos/*action", getReposActionHandler)
r.GET("/repos", getReposHandler)
log.Println("Start web server. Port: ", *addr)
if err := r.Run(*addr); err != nil {
log.Fatal("Run:", err)
}
log.Println("end of main")
}