/
main.go
337 lines (289 loc) · 10.2 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
package main
import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
. "github.com/arran4/gobookmarks"
"github.com/arran4/gorillamuxlogic"
"github.com/google/go-github/v55/github"
"github.com/gorilla/mux"
"github.com/gorilla/sessions"
"golang.org/x/oauth2"
"golang.org/x/oauth2/endpoints"
"log"
"math/big"
"net/http"
"net/url"
"os"
"os/signal"
"reflect"
"sync"
"time"
)
var (
clientID = os.Getenv("OAUTH2_CLIENT_ID")
clientSecret = os.Getenv("OAUTH2_SECRET")
externalUrl = os.Getenv("EXTERNAL_URL")
redirectUrl = fmt.Sprintf("%s/oauth2Callback", externalUrl)
version = "dev"
commit = "none"
date = "unknown"
)
func init() {
log.SetFlags(log.Flags() | log.Lshortfile)
SessionName = "gobookmarks"
SessionStore = sessions.NewCookieStore([]byte("random-key")) // TODO random key
Oauth2Config = &oauth2.Config{
ClientID: clientID,
ClientSecret: clientSecret,
RedirectURL: redirectUrl,
Scopes: []string{"repo", "read:user", "user:email"},
Endpoint: endpoints.GitHub,
}
}
func main() {
r := mux.NewRouter()
r.Use(UserAdderMiddleware)
r.Use(CoreAdderMiddleware)
r.HandleFunc("/main.css", func(writer http.ResponseWriter, request *http.Request) {
_, _ = writer.Write(GetMainCSSData())
}).Methods("GET")
r.HandleFunc("/favicon.ico", func(writer http.ResponseWriter, request *http.Request) {
_, _ = writer.Write(GetFavicon())
}).Methods("GET")
// News
r.Handle("/", http.HandlerFunc(runTemplate("indexPage.gohtml"))).Methods("GET")
r.HandleFunc("/", runHandlerChain(TaskDoneAutoRefreshPage)).Methods("POST")
r.HandleFunc("/edit", runTemplate("loginPage.gohtml")).Methods("GET").MatcherFunc(gorillamuxlogic.Not(RequiresAnAccount()))
r.HandleFunc("/edit", runTemplate("edit.gohtml")).Methods("GET").MatcherFunc(RequiresAnAccount())
r.HandleFunc("/edit", runTemplate("edit.gohtml")).Methods("POST").MatcherFunc(RequiresAnAccount()).MatcherFunc(HasError())
r.HandleFunc("/edit", runHandlerChain(BookmarksEditSaveAction, redirectToHandlerBranchToRef("/"))).Methods("POST").MatcherFunc(RequiresAnAccount()).MatcherFunc(TaskMatcher("Save"))
r.HandleFunc("/edit", runHandlerChain(BookmarksEditCreateAction, redirectToHandlerBranchToRef("/"))).Methods("POST").MatcherFunc(RequiresAnAccount()).MatcherFunc(TaskMatcher("Create"))
r.HandleFunc("/edit", runHandlerChain(TaskDoneAutoRefreshPage)).Methods("POST")
r.HandleFunc("/history", runTemplate("loginPage.gohtml")).Methods("GET").MatcherFunc(gorillamuxlogic.Not(RequiresAnAccount()))
r.HandleFunc("/history", runTemplate("history.gohtml")).Methods("GET").MatcherFunc(RequiresAnAccount())
r.HandleFunc("/history/commits", runTemplate("loginPage.gohtml")).Methods("GET").MatcherFunc(gorillamuxlogic.Not(RequiresAnAccount()))
r.HandleFunc("/history/commits", runTemplate("historyCommits.gohtml")).Methods("GET").MatcherFunc(RequiresAnAccount())
r.HandleFunc("/logout", runHandlerChain(UserLogoutAction, runTemplate("logoutPage.gohtml"))).Methods("GET")
r.HandleFunc("/oauth2Callback", runHandlerChain(Oauth2CallbackPage, redirectToHandler("/"))).Methods("GET")
r.HandleFunc("/proxy/favicon", FaviconProxyHandler).Methods("GET")
http.Handle("/", r)
if !fileExists("cert.pem") || !fileExists("key.pem") {
CreatePEMFiles()
}
log.Printf("gobookmarks: %s, commit %s, built at %s", version, commit, date)
SetVersion(version, commit, date)
log.Printf("Redirect URL configured to: %s", redirectUrl)
log.Println("Server started on http://localhost:8080")
log.Println("Server started on https://localhost:8443")
// Create a context with a cancel function
_, cancel := context.WithCancel(context.Background())
defer cancel() // Ensure cancellation when main exits
// Create an HTTP server with a handler
httpServer := &http.Server{
Addr: ":8080",
}
// Create an HTTPS server with a handler
httpsServer := &http.Server{
Addr: ":8443",
}
var sigCh chan os.Signal
// Handle ^C signal (SIGINT) to gracefully shut down the servers
go func() {
sigCh = make(chan os.Signal, 1)
signal.Notify(sigCh, os.Interrupt)
<-sigCh
fmt.Println("Shutting down gracefully...")
// Cancel the context to signal shutdown to both servers
cancel()
// Give some time for active connections to finish
timeout := 5 * time.Second
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
if err := httpServer.Shutdown(ctx); err != nil {
log.Printf("HTTP server error during shutdown: %v", err)
}
if err := httpsServer.Shutdown(ctx); err != nil {
log.Printf("HTTPS server error during shutdown: %v", err)
}
fmt.Println("Servers gracefully shut down.")
}()
wg := sync.WaitGroup{}
wg.Add(2)
// Start the HTTP server
go func() {
defer wg.Done()
fmt.Println("HTTP server listening on :8080...")
if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("HTTP server error: %v", err)
}
}()
// Start the HTTPS server (TLS/SSL)
go func() {
defer wg.Done()
fmt.Println("HTTPS server listening on :8443...")
if err := httpsServer.ListenAndServeTLS("cert.pem", "key.pem"); err != nil && err != http.ErrServerClosed {
log.Fatalf("HTTPS server error: %v", err)
}
}()
wg.Wait()
}
func CreatePEMFiles() {
notBefore := time.Now()
notAfter := notBefore.Add(365 * 24 * time.Hour) // Valid for 1 year
serialNumber, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
if err != nil {
log.Fatalf("Failed to generate serial number: %v", err)
}
template := x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
Organization: []string{"Your Organization"},
},
NotBefore: notBefore,
NotAfter: notAfter,
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
}
priv, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
if err != nil {
log.Fatalf("Failed to generate private key: %v", err)
}
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
if err != nil {
log.Fatalf("Failed to create certificate: %v", err)
}
certFile, err := os.Create("cert.pem")
if err != nil {
log.Fatalf("Failed to create cert.pem file: %v", err)
}
defer certFile.Close()
if err := pem.Encode(certFile, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}); err != nil {
log.Fatalf("Failed to write data to cert.pem: %v", err)
}
keyFile, err := os.Create("key.pem")
if err != nil {
log.Fatalf("Failed to create key.pem file: %v", err)
}
defer keyFile.Close()
privBytes, err := x509.MarshalECPrivateKey(priv)
if err != nil {
log.Fatalf("Failed to marshal private key: %v", err)
}
if err := pem.Encode(keyFile, &pem.Block{Type: "EC PRIVATE KEY", Bytes: privBytes}); err != nil {
log.Fatalf("Failed to write data to key.pem: %v", err)
}
}
func runHandlerChain(chain ...any) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
for _, each := range chain {
switch each := each.(type) {
case http.Handler:
each.ServeHTTP(w, r)
case http.HandlerFunc:
each(w, r)
case func(http.ResponseWriter, *http.Request):
each(w, r)
case func(http.ResponseWriter, *http.Request) error:
if err := each(w, r); err != nil {
type ErrorData struct {
*CoreData
Error string
}
if err := GetCompiledTemplates(NewFuncs(r)).ExecuteTemplate(w, "error.gohtml", ErrorData{
CoreData: r.Context().Value(ContextValues("coreData")).(*CoreData),
Error: err.Error(),
}); err != nil {
log.Printf("Error Template Error: %s", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
return
}
default:
log.Panicf("unknown input: %s", reflect.TypeOf(each))
}
}
}
}
func runTemplate(template string) func(http.ResponseWriter, *http.Request) {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
type Data struct {
*CoreData
Error string
}
data := Data{
CoreData: r.Context().Value(ContextValues("coreData")).(*CoreData),
Error: r.URL.Query().Get("error"),
}
if err := GetCompiledTemplates(NewFuncs(r)).ExecuteTemplate(w, template, data); err != nil {
log.Printf("Template Error: %s", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
})
}
func redirectToHandler(toUrl string) func(http.ResponseWriter, *http.Request) {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, toUrl, http.StatusTemporaryRedirect)
})
}
func redirectToHandlerBranchToRef(toUrl string) func(http.ResponseWriter, *http.Request) {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
u, _ := url.Parse(toUrl)
qs := u.Query()
qs.Set("ref", "refs/heads/"+r.PostFormValue("branch"))
u.RawQuery = qs.Encode()
http.Redirect(w, r, u.String(), http.StatusTemporaryRedirect)
})
}
func RequiresAnAccount() mux.MatcherFunc {
return func(request *http.Request, match *mux.RouteMatch) bool {
var session *sessions.Session
sessioni := request.Context().Value(ContextValues("session"))
if sessioni == nil {
var err error
session, err = SessionStore.Get(request, SessionName)
if err != nil {
return false
}
} else {
var ok bool
session, ok = sessioni.(*sessions.Session)
if !ok {
return false
}
}
githubUser, ok := session.Values["GithubUser"].(*github.User)
return ok && githubUser != nil
}
}
func TaskMatcher(taskName string) mux.MatcherFunc {
return func(request *http.Request, match *mux.RouteMatch) bool {
return request.PostFormValue("task") == taskName
}
}
func ModeMatcher(modeName string) mux.MatcherFunc {
return func(request *http.Request, match *mux.RouteMatch) bool {
return request.URL.Query().Get("mode") == modeName
}
}
func HasError() mux.MatcherFunc {
return func(request *http.Request, match *mux.RouteMatch) bool {
return request.URL.Query().Has("error")
}
}
func NoTask() mux.MatcherFunc {
return func(request *http.Request, match *mux.RouteMatch) bool {
return request.PostFormValue("task") == ""
}
}
func fileExists(filename string) bool {
_, err := os.Stat(filename)
return !os.IsNotExist(err)
}