-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
322 lines (267 loc) · 8.12 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
package main
import (
"encoding/gob"
"errors"
"fmt"
"html/template"
"net/http"
"os"
"time"
"github.com/robfig/cron"
"github.com/wcalandro/osuapi-go"
"github.com/BurntSushi/toml"
"github.com/globalsign/mgo/bson"
"golang.org/x/text/language"
"github.com/go-bongo/bongo"
"github.com/mrjones/oauth"
ctxt "context"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/gorilla/context"
"github.com/gorilla/sessions"
"github.com/joho/godotenv"
"github.com/nicksnyder/go-i18n/v2/i18n"
"github.com/op/go-logging"
redistore "gopkg.in/boj/redistore.v1"
"net/http/pprof"
)
var log = logging.MustGetLogger("prosu")
/* Set up session store */
var sessionStore *redistore.RediStore
/* Set up templates */
var templates = template.Must(template.ParseGlob("templates/*"))
/* Twitter Consumer Key and Secret */
var consumerKey string
var consumerSecret string
var twitterConsumer *oauth.Consumer
// Domain
var domain string
type sessionTokenStorer struct {
Token *oauth.RequestToken
}
// Database variables
var mongoConnectionString string
var mongoDatabase string
var connection *bongo.Connection
// i18n bundle
var bundle *i18n.Bundle
// osu! api
var api osuRateLimiter
var postingAPI osuRateLimiter
// Is maintenance
var isMaintenance = false
type blankData struct {
}
func init() {
/* First, setting up logging */
loggingBackend := logging.NewLogBackend(os.Stdout, "", 0)
format := logging.MustStringFormatter(
`%{color}%{time:15:04:05.000} %{shortfunc} ▶ %{level:.4s} %{id:03x}%{color:reset} %{message}`,
)
loggingBackendFormatter := logging.NewBackendFormatter(loggingBackend, format)
logging.SetBackend(loggingBackendFormatter)
/* Second, as long as we aren't in the production environment, try to load a .env for configuration */
if os.Getenv("ENVIRONMENT") != "production" {
if err := godotenv.Load(); err != nil {
log.Warning("Couldn't load .env file")
fmt.Println(err)
} else {
log.Info("Successfully loaded .env file")
}
} else {
log.Debug("Production environment, not loading .env")
}
// Initialize sessionStore
sessionStore = setupSessionStore()
// Initialize consumer key and secret
consumerKey = os.Getenv("CONSUMER_KEY")
consumerSecret = os.Getenv("CONSUMER_SECRET")
// Initialize domain
domain = os.Getenv("DOMAIN")
// Initialize Twitter client
twitterConsumer = oauth.NewConsumer(
consumerKey,
consumerSecret,
oauth.ServiceProvider{
RequestTokenUrl: "https://api.twitter.com/oauth/request_token",
AuthorizeTokenUrl: "https://api.twitter.com/oauth/authenticate",
AccessTokenUrl: "https://api.twitter.com/oauth/access_token",
},
)
// Add sessionTokenStorer to gob
gob.Register(sessionTokenStorer{})
// Connect to MongoDB
mongoConnectionString = os.Getenv("MONGO_URL")
conn, err := bongo.Connect(&bongo.Config{
ConnectionString: mongoConnectionString,
})
if err != nil {
panic(err)
}
connection = conn
osuAPIKey := os.Getenv("OSU_API_KEY")
if len(osuAPIKey) == 0 {
panic(errors.New("OSU_API_KEY variable must not be empty"))
}
api = newOsuLimiter(osuapi.NewAPI(osuAPIKey), 250)
postingAPI = newOsuLimiter(osuapi.NewAPI(osuAPIKey), 250)
// Check if maintenance mode
if os.Getenv("MAINTENANCE") == "true" {
isMaintenance = true
log.Debug("Starting in maintenance mode")
}
}
func main() {
/* Set up chi router */
// Initialize the router
r := chi.NewRouter()
// Initialize the middleware
r.Use(middleware.RequestID)
r.Use(middleware.RealIP)
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
r.Use(middleware.Timeout(60 * time.Second))
if isMaintenance {
r.Use(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
templates.ExecuteTemplate(w, "503.html", blankData{})
})
})
}
r.Use(getLoggedInValue)
r.Get(relicHandle("/", homePage))
r.Get(relicHandle("/privacy", routePrivacy))
r.Get(relicHandle("/connect/twitter", redirectToTwitter))
r.Get(relicHandle("/connect/twitter/callback", obtainAccessToken))
r.Get(relicHandle("/logout", logoutUser))
r.Get(relicHandle("/settings", routeSettings))
r.Post(relicHandle("/settings/enable", enableTweetPosting))
r.Post(relicHandle("/settings/disable", disableTweetPosting))
r.Post(relicHandle("/settings/update", updateSettings))
//FileServer(r, "/assets", http.Dir("./static"))
r.Get("/favicon.ico", ServeFavicon)
// LoaderIO Configuration
loaderIoKey := os.Getenv("LOADERIO_KEY")
if loaderIoKey != "" {
r.Get("/"+loaderIoKey+".txt", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, loaderIoKey)
})
}
// pprof
pr := http.NewServeMux()
pr.HandleFunc("/debug/pprof/", pprof.Index)
pr.HandleFunc("/debug/pprof/cmdline/", pprof.Cmdline)
pr.HandleFunc("/debug/pprof/profile/", pprof.Profile)
pr.HandleFunc("/debug/pprof/symbol/", pprof.Symbol)
pr.HandleFunc("/debug/pprof/trace/", pprof.Trace)
r.NotFound(notFound)
// Set up translator
bundle = i18n.NewBundle(language.English)
bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal)
bundle.MustLoadMessageFile("./translations/active.en.toml")
// Cron job
c := cron.New()
c.AddFunc("0 0 * * * *", func() {
log.Info("Running posting function")
findAndGenerate()
})
c.Start()
/* Listen */
port := "5000"
if envPort := os.Getenv("PORT"); envPort != "" {
port = envPort
}
defer connection.Session.Close()
go (func() {
fmt.Println(http.ListenAndServe("localhost:5001", pr))
})()
fmt.Println(http.ListenAndServe(":"+port, context.ClearHandler(r)))
}
func getLoggedInValue(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
session, sessionError := sessionStore.Get(r, "prosu_session")
ctx := r.Context()
if sessionError != nil {
log.Error("Error getting session")
ctx = ctxt.WithValue(ctx, "session_error", sessionError.Error())
} else {
isAuthenticated := false
if session.Values["isAuthenticated"] == true {
isAuthenticated = true
}
ctx = ctxt.WithValue(ctx, "session_error", "")
ctx = ctxt.WithValue(ctx, "session", session)
ctx = ctxt.WithValue(ctx, "isAuthenticated", isAuthenticated)
if isAuthenticated {
user := &User{}
err := connection.Collection("usermodels").FindById(bson.ObjectIdHex(session.Values["user_id"].(string)), user)
if err != nil {
ctx = ctxt.WithValue(ctx, "user_error", err.Error())
} else {
ctx = ctxt.WithValue(ctx, "user_error", "")
ctx = ctxt.WithValue(ctx, "user", user)
}
}
if session.Values["language"] == nil {
session.Values["language"] = ""
}
session.Save(r, w)
}
next.ServeHTTP(w, r.WithContext(ctx))
}
return http.HandlerFunc(fn)
}
func logoutUser(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
sessionError := ctx.Value("session_error").(string)
if sessionError != "" {
log.Error("There was an error getting the user's session")
log.Error(sessionError)
reqID := middleware.GetReqID(ctx)
http.Error(w, "Error getting user session\nRequestID: "+reqID, 500)
return
}
session := ctx.Value("session").(*sessions.Session)
session.Options.MaxAge = -1
if err := session.Save(r, w); err != nil {
log.Error("There was an error saving the user's session")
log.Error(sessionError)
reqID := middleware.GetReqID(ctx)
http.Error(w, "Error saving user session\nRequestID: "+reqID, 500)
return
}
http.Redirect(w, r, "/", 302)
}
type navbarTranslations struct {
SignIn string
Logout string
HomePage string
SettingsPage string
}
func translateNavbar(localizer *i18n.Localizer, isAuthenticated bool, user User) navbarTranslations {
signIn := localizer.MustLocalize(&i18n.LocalizeConfig{
MessageID: "NavbarSignIn",
})
homePage := localizer.MustLocalize(&i18n.LocalizeConfig{
MessageID: "NavbarHomePage",
})
settingsPage := localizer.MustLocalize(&i18n.LocalizeConfig{
MessageID: "NavbarSettingsPage",
})
var username string
if isAuthenticated {
username = user.Twitter.Profile.Handle
}
logout := localizer.MustLocalize(&i18n.LocalizeConfig{
MessageID: "NavbarLogout",
TemplateData: map[string]string{
"Handle": username,
},
})
return navbarTranslations{
SignIn: signIn,
Logout: logout,
HomePage: homePage,
SettingsPage: settingsPage,
}
}