-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
387 lines (320 loc) · 10 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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
package main
import (
"bytes"
"context"
"crypto/tls"
"database/sql"
"fmt"
"html/template"
"io"
"net/http"
"os"
"shortlink/helpers"
"strings"
"time"
"github.com/ravener/discord-oauth2"
"golang.org/x/oauth2"
"golang.org/x/oauth2/github"
"golang.org/x/oauth2/google"
"github.com/go-co-op/gocron"
"github.com/gorilla/mux"
"github.com/gorilla/sessions"
)
var (
oauthConfig *oauth2.Config
store = sessions.NewCookieStore([]byte("secret"))
)
func initOauth(config helpers.Configuration) {
store = sessions.NewCookieStore([]byte(config.OAuth.Secret))
if config.OAuth.Type == "discord" {
oauthConfig = &oauth2.Config{
ClientID: config.OAuth.ClientID,
ClientSecret: config.OAuth.ClientSecret,
RedirectURL: config.OAuth.RedirectURL,
Scopes: []string{discord.ScopeIdentify},
Endpoint: discord.Endpoint,
}
} else if config.OAuth.Type == "google" {
oauthConfig = &oauth2.Config{
ClientID: config.OAuth.ClientID,
ClientSecret: config.OAuth.ClientSecret,
RedirectURL: config.OAuth.RedirectURL,
Scopes: []string{"profile", "email"},
Endpoint: google.Endpoint,
}
} else if config.OAuth.Type == "github" {
oauthConfig = &oauth2.Config{
ClientID: config.OAuth.ClientID,
ClientSecret: config.OAuth.ClientSecret,
RedirectURL: config.OAuth.RedirectURL,
Scopes: []string{"user:email", "read:user"},
Endpoint: github.Endpoint,
}
}
}
var rootServe string
var db *sql.DB
func addToCache(id string, data []byte) {
fileCache[id] = data
}
func getFromCache(id string) []byte {
if data, ok := fileCache[id]; ok {
return data
}
return nil
}
var templates *template.Template
func handleRequests(config helpers.Configuration) {
// we parse all templates in templates/
templates = template.Must(template.ParseGlob("templates/*.tmpl"))
router := mux.NewRouter().StrictSlash(true)
// link-shortening listeners
if config.Webserver.RootServe != "" {
rootServe = config.Webserver.RootServe
router.HandleFunc("/", homePage)
}
router.HandleFunc("/admin", authMiddleware(adminPage)).Methods("GET")
router.HandleFunc("/admin/remove/{term}", authMiddleware(adminPageRemove))
router.HandleFunc("/admin/add", authMiddleware(adminPageAdd))
router.HandleFunc("/admin/add/{short}/{long}", authMiddleware(adminPageAddShort))
router.HandleFunc("/admin/login", loginHandler).Methods("GET")
router.HandleFunc("/admin/logout", logoutHandler).Methods("GET")
router.HandleFunc("/admin/callback", callbackHandler).Methods("GET")
// we have to handle /admin/main.css
router.PathPrefix("/admin/main.css").Handler(http.StripPrefix("/admin/", http.FileServer(http.Dir("admin/"))))
router.HandleFunc("/{id}", shortenLink)
router.NotFoundHandler = http.HandlerFunc(notFoundHandler)
server := http.Server{
Addr: ":8081",
Handler: router,
TLSConfig: &tls.Config{
NextProtos: []string{"h2", "http/1.1"},
},
}
fmt.Printf("Server listening on %s\n", server.Addr)
if err := server.ListenAndServe(); err != nil {
fmt.Println(err)
}
}
var fileCache = make(map[string][]byte)
func authMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
session, _ := store.Get(r, "session-name")
_, ok := session.Values["authenticated"]
if !ok {
// http.Error(w, "Unauthorized", http.StatusUnauthorized)
// get current timestamp
t := time.Now()
data := helpers.PageData{
PageTitle: "Shorty - Unauthorized",
Footer: "© 2023 ptgms Industries - Page loaded in " + fmt.Sprintf("%d", time.Since(t).Milliseconds()) + "ms",
}
err := templates.ExecuteTemplate(w, "unauth", data)
helpers.HandleError(err, false)
return
}
next(w, r)
}
}
func notFoundHandler(w http.ResponseWriter, r *http.Request) {
// print url to writer
_, err := fmt.Fprintf(w, "404 - Not Found - %s", r.URL.Path)
helpers.HandleError(err, false)
}
func loginHandler(w http.ResponseWriter, r *http.Request) {
session, _ := store.Get(r, "session-name")
session.Values["state"] = "random-state"
err := session.Save(r, w)
helpers.HandleError(err, false)
url := oauthConfig.AuthCodeURL(session.Values["state"].(string))
http.Redirect(w, r, url, http.StatusTemporaryRedirect)
}
func logoutHandler(w http.ResponseWriter, r *http.Request) {
session, _ := store.Get(r, "session-name")
delete(session.Values, "authenticated")
err := session.Save(r, w)
helpers.HandleError(err, false)
t := time.Now()
data := helpers.PageData{
PageTitle: "Shorty - Logged out",
Footer: "© 2023 ptgms Industries - Page loaded in " + fmt.Sprintf("%d", time.Since(t).Milliseconds()) + "ms",
}
err = templates.ExecuteTemplate(w, "loggedout", data)
helpers.HandleError(err, false)
//http.Redirect(w, r, "/", http.StatusSeeOther)
}
func callbackHandler(w http.ResponseWriter, r *http.Request) {
session, _ := store.Get(r, "session-name")
queryState := r.URL.Query().Get("state")
if queryState != session.Values["state"].(string) {
http.Error(w, "Invalid callback state", http.StatusBadRequest)
return
}
code := r.URL.Query().Get("code")
token, err := oauthConfig.Exchange(context.Background(), code)
if err != nil {
http.Error(w, "Failed to exchange token", http.StatusInternalServerError)
return
}
// Check if token is valid
valid, authUser := helpers.IsTokenValid(token, config, oauthConfig)
if !valid {
http.Error(w, "Invalid token", http.StatusUnauthorized)
return
}
// check if config.PermittedUsers contains authUser.ID
if !helpers.IsIDPermitted(authUser.ID, config.PermittedUsers) {
http.Error(w, "User not permitted. Ask Owner to permit ID "+authUser.ID, http.StatusUnauthorized)
return
}
// Set username in session
session.Values["username"] = authUser.Username
// Set authenticated flag in session
session.Values["authenticated"] = true
err = session.Save(r, w)
helpers.HandleError(err, false)
// Set a cookie to remember login for 1 week
cookie := http.Cookie{
Name: "auth_token",
Value: token.AccessToken,
Expires: time.Now().Add(7 * 24 * time.Hour),
HttpOnly: true,
}
http.SetCookie(w, &cookie)
http.Redirect(w, r, "/admin", http.StatusSeeOther)
}
func homePage(w http.ResponseWriter, _ *http.Request) {
// check if we have the file in cache
if data := getFromCache("rootserve"); data != nil {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_, err := w.Write(data)
helpers.HandleError(err, false)
return
}
file, err := os.Open(rootServe)
helpers.HandleError(err, false)
defer func(file *os.File) {
err := file.Close()
if err != nil {
helpers.HandleError(err, false)
}
}(file)
var buf bytes.Buffer
_, err = io.Copy(&buf, file)
helpers.HandleError(err, false)
content := buf.Bytes()
addToCache("rootserve", content)
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_, err = w.Write(content)
helpers.HandleError(err, false)
}
func adminPageRemove(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
term := vars["term"]
termsSplit := strings.Split(term, ",")
for _, term := range termsSplit {
helpers.RemoveLink(db, term)
}
http.Redirect(w, r, "/admin", http.StatusTemporaryRedirect)
}
func adminPageAddShort(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
short := vars["short"]
long := strings.Replace(vars["long"], ".", "/", -1)
expires := r.URL.Query().Get("expires")
long = helpers.Base64Decode(long)
short = helpers.Base64Decode(short)
helpers.AddLink(db, long, short, expires)
http.Redirect(w, r, "/admin", http.StatusTemporaryRedirect)
}
func adminPage(w http.ResponseWriter, r *http.Request) {
// get current timestamp
t := time.Now()
// get user from session
session, _ := store.Get(r, "session-name")
username := session.Values["username"]
data := helpers.PageData{
PageTitle: "Shorty Admin",
LoginName: username.(string),
Links: helpers.GetLinks(db, config.Webserver.Domain),
Footer: "© 2023 ptgms Industries - Page loaded in " + fmt.Sprintf("%d", time.Since(t).Milliseconds()) + "ms",
}
err := templates.ExecuteTemplate(w, "admin", data)
helpers.HandleError(err, false)
}
func adminPageAdd(w http.ResponseWriter, r *http.Request) {
// get current timestamp
t := time.Now()
// get user from session
session, _ := store.Get(r, "session-name")
username := session.Values["username"]
data := helpers.PageData{
PageTitle: "Shorty Admin",
LoginName: username.(string),
Footer: "© - Page loaded in " + fmt.Sprintf("%d", time.Since(t).Milliseconds()) + "ms",
}
err := templates.ExecuteTemplate(w, "adminadd", data)
helpers.HandleError(err, false)
}
func shortenLink(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
key := vars["id"]
if key == "" || key == "admin" || key == "favicon.ico" {
return
}
// check if we have the url in cache
if data := getFromCache(key); data != nil {
// redirect to the link
http.Redirect(w, r, string(data), http.StatusMovedPermanently)
return
}
// get the link from the database
var link = helpers.GetLink(db, key)
// redirect to the link
http.Redirect(w, r, link, http.StatusMovedPermanently)
if link == "" {
return
}
// add the link to cache
addToCache(key, []byte(link))
// increase the counter
helpers.RegisterClick(db, key)
}
func task() {
fmt.Println("Task running")
// let's invalidate the cache
fileCache = make(map[string][]byte)
}
func prepareScheduler() {
s := gocron.NewScheduler(time.UTC)
_, err := s.Every(24).Hours().Do(task)
if err != nil {
return
}
if err != nil {
println(err.Error())
return
}
// Start the scheduler in a thread
s.StartAsync()
}
var config helpers.Configuration
func main() {
if helpers.DoesFileExist("config.json") {
config = helpers.LoadConfig()
if config.Webserver.RootServe != "" {
if !helpers.DoesFileExist(config.Webserver.RootServe) {
fmt.Println("RootServe file does not exist. Please check config.json / create the file.")
os.Exit(1)
}
}
} else {
helpers.SaveEmptyConfig()
fmt.Println("Please edit config.json and restart the server.")
os.Exit(1)
}
db = helpers.CreateConnection(config)
initOauth(config)
prepareScheduler()
handleRequests(config)
}