This repository has been archived by the owner on May 9, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
334 lines (294 loc) · 7.67 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
package main
import (
"context"
"net/http"
"os"
"os/signal"
"strings"
"sync"
"time"
"github.com/jinzhu/gorm"
"github.com/nicklaw5/helix"
"github.com/tensei/dggoauth"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/sirupsen/logrus"
)
// UnRustleLogs ...
type UnRustleLogs struct {
config *Config
db *gorm.DB
dggHTTPClient *http.Client
dggOauthClient *dggoauth.Client
dggStates map[string]*state
dggStateMutex sync.RWMutex
twitchHTTPClient *http.Client
twitchAPIClient *helix.Client
twitchStates map[string]struct{}
twitchStateMutex sync.RWMutex
}
type state struct {
service string
verifier string
time time.Time
}
const (
// TWITCHSERVICE ...
TWITCHSERVICE = "twitch"
// DESTINYGGSERVICE ...
DESTINYGGSERVICE = "destinygg"
)
// jwtCustomClaims are custom claims extending default ones.
type jwtClaims struct {
ID string `json:"id"`
jwt.StandardClaims
}
func main() {
gin.SetMode(gin.ReleaseMode)
rustle := NewUnRustleLogs()
rustle.LoadConfig("config.toml")
rustle.NewDatabase()
err := rustle.setupTwitchClient()
if err != nil {
logrus.Fatal(err)
}
err = rustle.setupDestinyggClient()
if err != nil {
logrus.Fatal(err)
}
router := gin.Default()
router.LoadHTMLGlob("templates/*")
router.GET("/", rustle.indexHandler)
router.GET("/verify", rustle.verifyHandler)
router.GET("/robots.txt", func(c *gin.Context) {
c.String(200, "User-agent: *\nDisallow: /")
})
twitch := router.Group("/twitch")
{
twitch.GET("/", rustle.TwitchIndexHandle)
twitch.GET("/login", rustle.TwitchLoginHandle)
twitch.GET("/logout", rustle.TwitchLogoutHandle)
twitch.GET("/callback", rustle.TwitchCallbackHandle)
}
dgg := router.Group("/dgg")
{
dgg.GET("/", rustle.DestinyggIndexHandle)
dgg.GET("/login", rustle.DestinyggLoginHandle)
dgg.GET("/logout", rustle.DestinyggLogoutHandle)
dgg.GET("/callback", rustle.DestinyggCallbackHandle)
}
router.Static("/assets", "./assets")
srv := &http.Server{
Handler: router,
Addr: rustle.config.Server.Address,
// Good practice: enforce timeouts for servers you create!
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
}
logrus.Infof("starting server adress: %q", rustle.config.Server.Address)
go func() {
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
logrus.Error(err)
}
}()
c := make(chan os.Signal, 1)
// We'll accept graceful shutdowns when quit via SIGINT (Ctrl+C)
// SIGKILL, SIGQUIT or SIGTERM (Ctrl+/) will not be caught.
signal.Notify(c, os.Interrupt)
// Block until we receive our signal.
<-c
// Create a deadline to wait for.
ctx, cancel := context.WithTimeout(context.Background(), time.Second*15)
defer cancel()
// Doesn't block if no connections, but will otherwise wait
// until the timeout deadline.
if err := srv.Shutdown(ctx); err != nil {
logrus.Fatal("Server Shutdown:", err)
}
logrus.Info("Server exiting")
}
// NewUnRustleLogs ...
func NewUnRustleLogs() *UnRustleLogs {
return &UnRustleLogs{
dggHTTPClient: &http.Client{},
dggStates: make(map[string]*state),
twitchHTTPClient: &http.Client{},
twitchStates: make(map[string]struct{}),
}
}
// Payload ...
type Payload struct {
Twitch struct {
ID string
Name string
Email string
LoggedIn bool
}
Destinygg struct {
ID string
Name string
LoggedIn bool
}
}
func (ur *UnRustleLogs) indexHandler(c *gin.Context) {
c.HTML(http.StatusOK, "index.tmpl", nil)
}
// TwitchIndexHandle ...
func (ur *UnRustleLogs) TwitchIndexHandle(c *gin.Context) {
payload := Payload{}
twitch, ok := ur.getUserFromJWT(c, ur.config.Twitch.Cookie)
if ok {
payload.Twitch.Name = twitch.DisplayName
payload.Twitch.Email = twitch.Email
payload.Twitch.LoggedIn = true
payload.Twitch.ID = twitch.ID
}
c.HTML(http.StatusOK, "twitch.tmpl", payload)
}
// DestinyggIndexHandle ...
func (ur *UnRustleLogs) DestinyggIndexHandle(c *gin.Context) {
payload := Payload{}
dgg, ok := ur.getUserFromJWT(c, ur.config.Destinygg.Cookie)
if ok {
payload.Destinygg.Name = dgg.DisplayName
payload.Destinygg.LoggedIn = true
payload.Destinygg.ID = dgg.ID
}
c.HTML(http.StatusOK, "destinygg.tmpl", payload)
}
// VerifyPayload ...
type VerifyPayload struct {
UserID string
Name string
Email string
Valid bool
JWT string
Service string
ID string
}
func (ur *UnRustleLogs) verifyHandler(c *gin.Context) {
payload := VerifyPayload{}
if id := c.Query("id"); id != "" {
id = strings.TrimSpace(id)
// make sure the uuid is valid
uid, err := uuid.Parse(id)
if err != nil {
c.HTML(http.StatusBadRequest, "verify.tmpl", payload)
return
}
user, ok := ur.GetUser(uid.String())
if !ok {
c.HTML(http.StatusBadRequest, "verify.tmpl", payload)
return
}
payload.UserID = user.UserID
payload.Name = user.Name
payload.Email = user.Email
payload.Valid = true
payload.Service = user.Service
payload.ID = uid.String()
}
c.HTML(http.StatusOK, "verify.tmpl", payload)
}
func (ur *UnRustleLogs) getUserFromJWT(c *gin.Context, cookiename string) (*User, bool) {
cookie, err := c.Cookie(cookiename)
if err != nil {
return nil, false
}
token, err := jwt.ParseWithClaims(cookie, &jwtClaims{}, func(token *jwt.Token) (interface{}, error) {
return []byte(ur.config.Server.JWTSecret), nil
})
if err != nil {
logrus.Error(err)
ur.deleteCookie(c, cookie)
return nil, false
}
if claims, ok := token.Claims.(*jwtClaims); ok && token.Valid {
// idk if i have to manually check if the jwt is expired or not
// might be that .Valid is only true if it's not expired also
now := time.Now()
expires := time.Unix(claims.ExpiresAt, 0)
if now.After(expires) {
ur.deleteCookie(c, cookie)
return nil, false
}
return ur.GetUser(claims.ID)
}
return nil, false
}
func (ur *UnRustleLogs) parseJWT(jwtString string) (*jwtClaims, bool) {
token, err := jwt.ParseWithClaims(jwtString, &jwtClaims{}, func(token *jwt.Token) (interface{}, error) {
return []byte(ur.config.Server.JWTSecret), nil
})
if err != nil {
logrus.Error(err)
return nil, false
}
if claims, ok := token.Claims.(*jwtClaims); ok && token.Valid {
return claims, true
}
return nil, false
}
func (ur *UnRustleLogs) addDggState(s, verifier string) {
ur.dggStateMutex.Lock()
defer ur.dggStateMutex.Unlock()
ur.dggStates[s] = &state{
verifier: verifier,
service: DESTINYGGSERVICE,
time: time.Now().UTC(),
}
// delete dgg state after 5 minutes
go func() {
time.Sleep(time.Minute * 5)
ur.deleteDggState(s)
}()
}
func (ur *UnRustleLogs) hasDggState(state string) (string, bool) {
if strings.TrimSpace(state) == "" {
return "", false
}
ur.dggStateMutex.RLock()
defer ur.dggStateMutex.RUnlock()
s, ok := ur.dggStates[state]
if !ok {
return "", false
}
return s.verifier, ok
}
func (ur *UnRustleLogs) deleteDggState(state string) {
ur.dggStateMutex.Lock()
defer ur.dggStateMutex.Unlock()
_, ok := ur.dggStates[state]
if ok {
logrus.Infof("deleting dgg state %s", state)
delete(ur.dggStates, state)
}
}
func (ur *UnRustleLogs) addTwitchState(s string) {
ur.twitchStateMutex.Lock()
defer ur.twitchStateMutex.Unlock()
ur.twitchStates[s] = struct{}{}
go func() {
time.Sleep(time.Minute * 5)
ur.deleteTwitchState(s)
}()
}
func (ur *UnRustleLogs) hasTwitchState(state string) bool {
if strings.TrimSpace(state) == "" {
return false
}
ur.twitchStateMutex.RLock()
defer ur.twitchStateMutex.RUnlock()
_, ok := ur.twitchStates[state]
return ok
}
func (ur *UnRustleLogs) deleteTwitchState(state string) {
ur.twitchStateMutex.Lock()
defer ur.twitchStateMutex.Unlock()
_, ok := ur.twitchStates[state]
if ok {
logrus.Infof("deleting twitch state %s", state)
delete(ur.twitchStates, state)
}
}