-
Notifications
You must be signed in to change notification settings - Fork 0
/
goth.go
711 lines (555 loc) · 17.8 KB
/
goth.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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
// 🚀 Fiber is an Express inspired web framework written in Go with 💖
// 📌 API Documentation: https://fiber.wiki
// 📝 Github Repository: https://github.com/gofiber/fiber
package goth
import (
"crypto/rand"
"encoding/base64"
"fmt"
"math/big"
"net/http"
"strings"
"time"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/log"
"github.com/gofiber/fiber/v2/utils"
"github.com/valyala/fasthttp"
"github.com/zeiss/fiber-goth/adapters"
"github.com/zeiss/fiber-goth/providers"
)
var _ GothHandler = (*BeginAuthHandler)(nil)
const charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-"
// Params maps the parameters of the Fiber context to the gothic context.
type Params struct {
ctx *fiber.Ctx
}
// Get returns the value of a query paramater.
func (p *Params) Get(key string) string {
return p.ctx.Query(key)
}
// The contextKey type is unexported to prevent collisions with context keys defined in
// other packages.
type contextKey int
// The keys for the values in context
const (
providerKey contextKey = iota
sessionKey
tokenKey
userIDKey
)
// Error is the default error type for the goth middleware.
type Error struct {
Code int
Message string
}
// Error makes it compatible with the `error` interface.
func (e *Error) Error() string {
return e.Message
}
// NewError creates a new Error instance with an optional message
func NewError(code int, message ...string) *Error {
err := &Error{
Code: code,
Message: utils.StatusMessage(code),
}
if len(message) > 0 {
err.Message = message[0]
}
return err
}
var (
// ErrMissingProviderName is thrown if the provider cannot be determined.
ErrMissingProviderName = NewError(http.StatusBadRequest, "missing provider name in request")
// ErrMissingSession is thrown if there is no active session.
ErrMissingSession = NewError(http.StatusBadRequest, "could not find a matching session for this request")
// ErrBadSession is thrown if the session is invalid.
ErrBadSession = NewError(http.StatusBadRequest, "session is invalid")
// ErrMissingUser is thrown if the user is missing.
ErrMissingUser = NewError(http.StatusBadRequest, "missing user")
// ErrMissingCookie is thrown if the cookie is missing.
ErrMissingCookie = NewError(http.StatusBadRequest, "missing session cookie")
// ErrBadRequest is thrown if the request is invalid.
ErrBadRequest = NewError(http.StatusBadRequest, "bad request")
)
const (
state = "state"
provider = "provider"
)
// ProviderFromContext returns the provider from the request context.
func ProviderFromContext(c *fiber.Ctx) string {
return c.Get(fmt.Sprint(providerKey))
}
// SessionHandler is the default handler for the session.
type SessionHandler struct{}
// New creates a new handler to manage the session.
func (SessionHandler) New(cfg Config) fiber.Handler {
return func(c *fiber.Ctx) error {
if cfg.Next != nil && cfg.Next(c) {
return c.Next()
}
cookie := c.Cookies(cfg.CookieName)
if cookie == "" {
return cfg.ErrorHandler(c, ErrMissingCookie)
}
session, err := cfg.Adapter.GetSession(c.Context(), cookie)
if err != nil {
return cfg.ErrorHandler(c, err)
}
if !session.IsValid() {
cfg.ErrorHandler(c, err)
}
duration, err := time.ParseDuration(cfg.Expiry)
if err != nil {
return cfg.ErrorHandler(c, err)
}
expires := time.Now().Add(duration)
session.ExpiresAt = expires
session, err = cfg.Adapter.RefreshSession(c.Context(), session)
if err != nil {
return cfg.ErrorHandler(c, err)
}
cookieValue := fasthttp.Cookie{}
cookieValue.SetKey(cfg.CookieName)
cookieValue.SetValueBytes([]byte(session.SessionToken))
cookieValue.SetHTTPOnly(true)
cookieValue.SetSameSite(cfg.CookieSameSite)
cookieValue.SetExpire(expires)
cookieValue.SetPath(cfg.CookiePath)
c.Response().Header.SetCookie(&cookieValue)
return c.Next()
}
}
// NewSessionHandler returns a new default session handler.
func NewSessionHandler(config ...Config) fiber.Handler {
cfg := configDefault(config...)
return cfg.SessionHandler.New(cfg)
}
// BeginAuthHandler is the default handler to begin the authentication process.
type BeginAuthHandler struct{}
// New creates a new handler to begin authentication.
func (BeginAuthHandler) New(cfg Config) fiber.Handler {
return func(c *fiber.Ctx) error {
if cfg.Next != nil && cfg.Next(c) {
return c.Next()
}
p := c.Params(provider)
if p == "" {
return ErrMissingProviderName
}
provider, err := providers.GetProvider(p)
if err != nil {
return err
}
state, err := stateFromContext(c)
if err != nil {
return err
}
intent, err := provider.BeginAuth(c.Context(), cfg.Adapter, state, &Params{ctx: c})
if err != nil {
return err
}
url, err := intent.GetAuthURL()
if err != nil {
return err
}
return c.Redirect(url, fiber.StatusTemporaryRedirect)
}
}
// GothHandler is the interface for defining handlers for the middleware.
type GothHandler interface {
New(cfg Config) fiber.Handler
}
// NewBeginAuthHandler creates a new middleware handler to start authentication.
func NewBeginAuthHandler(config ...Config) fiber.Handler {
cfg := configDefault(config...)
return cfg.BeginAuthHandler.New(cfg)
}
// CompleteAuthComplete is the default handler to complete the authentication process.
type CompleteAuthCompleteHandler struct{}
// New creates a new handler to complete authentication.
//
//nolint:gocyclo
func (CompleteAuthCompleteHandler) New(cfg Config) fiber.Handler {
return func(c *fiber.Ctx) error {
if cfg.Next != nil && cfg.Next(c) {
return c.Next()
}
p := c.Params(provider)
if p == "" {
return cfg.ErrorHandler(c, ErrMissingProviderName)
}
provider, err := providers.GetProvider(p)
if err != nil {
return cfg.ErrorHandler(c, ErrMissingProviderName)
}
log.Infow("", "provider", provider.Name())
user, err := provider.CompleteAuth(c.Context(), cfg.Adapter, &Params{ctx: c})
if err != nil {
log.Error(err)
return cfg.ErrorHandler(c, ErrMissingUser)
}
log.Infow("", "user", user.Email)
duration, err := time.ParseDuration(cfg.Expiry)
if err != nil {
log.Error(err)
return cfg.ErrorHandler(c, ErrMissingSession)
}
expires := time.Now().Add(duration)
session, err := cfg.Adapter.CreateSession(c.Context(), user.ID, expires)
if err != nil {
log.Error(err)
return cfg.ErrorHandler(c, ErrMissingSession)
}
log.Infow("", "session", session.SessionToken)
cookieValue := fasthttp.Cookie{}
cookieValue.SetKeyBytes([]byte(cfg.CookieName))
cookieValue.SetValueBytes([]byte(session.SessionToken))
cookieValue.SetHTTPOnly(true)
cookieValue.SetSameSite(fasthttp.CookieSameSiteLaxMode)
cookieValue.SetExpire(expires)
cookieValue.SetPath("/")
c.Vary(fiber.HeaderCookie)
c.Response().Header.SetCookie(&cookieValue)
return cfg.CompletionFilter(c)
}
}
// NewCompleteAuthHandler creates a new middleware handler to complete authentication.
func NewCompleteAuthHandler(config ...Config) fiber.Handler {
cfg := configDefault(config...)
return cfg.CompleteAuthHandler.New(cfg)
}
// LogoutHandler is the default handler for the logout process.
type LogoutHandler struct{}
// NewLogoutHandler returns a new default logout handler.
func NewLogoutHandler(config ...Config) fiber.Handler {
cfg := configDefault(config...)
return cfg.LogoutHandler.New(cfg)
}
// New creates a new handler to logout.
func (LogoutHandler) New(cfg Config) fiber.Handler {
return func(c *fiber.Ctx) error {
if cfg.Next != nil && cfg.Next(c) {
return c.Next()
}
token, err := cfg.Extractor(c)
if err != nil {
return cfg.ErrorHandler(c, err)
}
err = cfg.Adapter.DeleteSession(c.Context(), token)
if err != nil {
return cfg.ErrorHandler(c, err)
}
c.ClearCookie(cfg.CookieName)
return cfg.CompletionFilter(c)
}
}
// ProtectMiddleware is the default handler for the protection process.
type ProtectMiddleware struct{}
// NewProtectMiddleware returns a new default protect handler.
//
// nolint:gocyclo
func NewProtectMiddleware(config ...Config) fiber.Handler {
return func(c *fiber.Ctx) error {
cfg := configDefault(config...)
if cfg.Next != nil && cfg.Next(c) {
return c.Next()
}
if strings.HasPrefix(c.Path(), cfg.LoginURL) {
return c.Next()
}
if strings.HasPrefix(c.Path(), cfg.LogoutURL) {
return c.Next()
}
if strings.HasPrefix(c.Path(), cfg.CallbackURL) {
return c.Next()
}
token, err := cfg.Extractor(c)
if err != nil {
return c.Redirect(cfg.LoginURL, fiber.StatusTemporaryRedirect)
}
session, err := cfg.Adapter.GetSession(c.Context(), token)
if err != nil {
return c.Redirect(cfg.LoginURL, fiber.StatusTemporaryRedirect)
}
if !session.IsValid() {
return c.Redirect(cfg.LoginURL, fiber.StatusTemporaryRedirect)
}
duration, err := time.ParseDuration(cfg.Expiry)
if err != nil {
return c.Redirect(cfg.LoginURL, fiber.StatusTemporaryRedirect)
}
expires := time.Now().Add(duration)
session.ExpiresAt = expires
session, err = cfg.Adapter.RefreshSession(c.Context(), session)
if err != nil {
return c.Redirect(cfg.LoginURL, fiber.StatusTemporaryRedirect)
}
cookieValue := fasthttp.Cookie{}
cookieValue.SetKey(cfg.CookieName)
cookieValue.SetValueBytes([]byte(session.SessionToken))
cookieValue.SetHTTPOnly(true)
cookieValue.SetSameSite(cfg.CookieSameSite)
cookieValue.SetExpire(expires)
cookieValue.SetPath(cfg.CookiePath)
c.Response().Header.SetCookie(&cookieValue)
c.Locals(tokenKey, session.ID)
c.Locals(sessionKey, session)
c.Locals(userIDKey, session.UserID)
return c.Next()
}
}
// ProtectedHandler is the default handler for the validation process.
type ProtectedHandler struct{}
// NewProtectedHandler returns a new default protected handler.
func NewProtectedHandler(handler fiber.Handler, config ...Config) fiber.Handler {
return func(c *fiber.Ctx) error {
cfg := configDefault(config...)
if cfg.Next != nil && cfg.Next(c) {
return c.Next()
}
token, err := cfg.Extractor(c)
if err != nil {
return c.Redirect(cfg.LoginURL, fiber.StatusTemporaryRedirect)
}
session, err := cfg.Adapter.GetSession(c.Context(), token)
if err != nil {
return c.Redirect(cfg.LoginURL, fiber.StatusTemporaryRedirect)
}
if !session.IsValid() {
return c.Redirect(cfg.LoginURL, fiber.StatusTemporaryRedirect)
}
duration, err := time.ParseDuration(cfg.Expiry)
if err != nil {
return c.Redirect(cfg.LoginURL, fiber.StatusTemporaryRedirect)
}
expires := time.Now().Add(duration)
session.ExpiresAt = expires
session, err = cfg.Adapter.RefreshSession(c.Context(), session)
if err != nil {
return c.Redirect(cfg.LoginURL, fiber.StatusTemporaryRedirect)
}
cookieValue := fasthttp.Cookie{}
cookieValue.SetKey(cfg.CookieName)
cookieValue.SetValueBytes([]byte(session.SessionToken))
cookieValue.SetHTTPOnly(true)
cookieValue.SetSameSite(cfg.CookieSameSite)
cookieValue.SetExpire(expires)
cookieValue.SetPath(cfg.CookiePath)
c.Response().Header.SetCookie(&cookieValue)
c.Locals(tokenKey, session.ID)
c.Locals(sessionKey, session)
c.Locals(userIDKey, session.UserID)
return handler(c)
}
}
// GetStateFromContext return the state that is returned during the callback.
func GetStateFromContext(ctx *fiber.Ctx) string {
return ctx.Query(state)
}
// ContextWithProvider returns a new request context containing the provider.
func ContextWithProvider(ctx *fiber.Ctx, provider string) *fiber.Ctx {
ctx.Set(fmt.Sprint(providerKey), provider)
return ctx
}
// Session from the request context.
func SessionFromContext(c *fiber.Ctx) (adapters.GothSession, error) {
session, ok := c.Locals(sessionKey).(adapters.GothSession)
if !ok {
return adapters.GothSession{}, ErrMissingSession
}
return session, nil
}
// Config caputes the configuration for running the goth middleware.
type Config struct {
// Next defines a function to skip this middleware when returned true.
Next func(c *fiber.Ctx) bool
// BeginAuthHandler is the handler to start authentication.
BeginAuthHandler GothHandler
// CompleteAuthHandler is the handler to complete the authentication.
CompleteAuthHandler GothHandler
// LogoutHandler is the handler to logout.
LogoutHandler GothHandler
// SessionHandler is the handler to manage the session.
SessionHandler GothHandler
// IndexHandler is the handler to display the index.
IndexHandler fiber.Handler
// ProtectedHandler is the handler to protect the route.
ProtectedHandler fiber.Handler
// CompletionFilter that is executed when responses need to returned.
CompletionFilter func(c *fiber.Ctx) error
// Secret is the secret used to sign the session.
Secret string
// Expiry is the duration that the session is valid for.
Expiry string
// CookieName is the name of the cookie used to store the session.
CookieName string
// CookieSameSite is the SameSite attribute of the cookie.
CookieSameSite fasthttp.CookieSameSite
// CookiePath is the path of the cookie.
CookiePath string
// CookieDomain is the domain of the cookie.
CookieDomain string
// CookieHTTPOnly is the HTTPOnly attribute of the cookie.
CookieHTTPOnly bool
// Encryptor is the function used to encrypt the session.
Encryptor func(decryptedString, key string) (string, error)
// Decryptor is the function used to decrypt the session.
Decryptor func(encryptedString, key string) (string, error)
// Adapter is the adapter used to store the session.
// Adapter adapters.Adapter
Adapter adapters.Adapter
// LoginURL is the URL to redirect to when the user is not authenticated.
LoginURL string
// LogoutURL is the URL to redirect to when the user logs out.
LogoutURL string
// CallbackURL is the URL to redirect to when the user logs out.
CallbackURL string
// CompletionURL is the default url after completion
CompletionURL string
// ErrorHandler is executed when an error is returned from fiber.Handler.
//
// Optional. Default: DefaultErrorHandler
ErrorHandler fiber.ErrorHandler
// Extractor is the function used to extract the token from the request.
Extractor func(c *fiber.Ctx) (string, error)
}
// ConfigDefault is the default config.
var ConfigDefault = Config{
ErrorHandler: defaultErrorHandler,
BeginAuthHandler: BeginAuthHandler{},
CompleteAuthHandler: CompleteAuthCompleteHandler{},
LogoutHandler: LogoutHandler{},
SessionHandler: SessionHandler{},
IndexHandler: defaultIndexHandler,
Encryptor: EncryptCookie,
Decryptor: DecryptCookie,
Expiry: "7h",
CookieName: "fiber_goth.session",
Extractor: TokenFromCookie("fiber_goth.session"),
CookieSameSite: fasthttp.CookieSameSiteLaxMode,
CompletionURL: "/",
LoginURL: "/login",
LogoutURL: "/logout",
CallbackURL: "/auth",
}
// default ErrorHandler that process return error from fiber.Handler
func defaultErrorHandler(_ *fiber.Ctx, err error) error {
return NewError(http.StatusBadRequest, err.Error())
}
// default filter for response that process default return.
func defaultCompletionFilter(completionURL string) fiber.Handler {
return func(c *fiber.Ctx) error {
return c.Redirect(completionURL, fiber.StatusTemporaryRedirect)
}
}
// default index handler that process default return.
func defaultIndexHandler(c *fiber.Ctx) error {
if c.Path() == "/login" {
return c.Next()
}
return c.Redirect("/login", fiber.StatusTemporaryRedirect)
}
// Helper function to set default values
// nolint:gocyclo
func configDefault(config ...Config) Config {
if len(config) < 1 {
return ConfigDefault
}
// Override default config
cfg := config[0]
if cfg.Next == nil {
cfg.Next = ConfigDefault.Next
}
if cfg.Extractor == nil {
cfg.Extractor = ConfigDefault.Extractor
}
if cfg.BeginAuthHandler == nil {
cfg.BeginAuthHandler = ConfigDefault.BeginAuthHandler
}
if cfg.CompleteAuthHandler == nil {
cfg.CompleteAuthHandler = ConfigDefault.CompleteAuthHandler
}
if cfg.LogoutHandler == nil {
cfg.LogoutHandler = ConfigDefault.LogoutHandler
}
if cfg.SessionHandler == nil {
cfg.SessionHandler = ConfigDefault.SessionHandler
}
if cfg.IndexHandler == nil {
cfg.IndexHandler = ConfigDefault.IndexHandler
}
if cfg.Encryptor == nil {
cfg.Encryptor = ConfigDefault.Encryptor
}
if cfg.Decryptor == nil {
cfg.Decryptor = ConfigDefault.Decryptor
}
if cfg.Expiry == "" {
cfg.Expiry = ConfigDefault.Expiry
}
if cfg.CookieName == "" {
cfg.CookieName = ConfigDefault.CookieName
}
if cfg.CookieSameSite == 0 {
cfg.CookieSameSite = ConfigDefault.CookieSameSite
}
if cfg.LoginURL == "" {
cfg.LoginURL = ConfigDefault.LoginURL
}
if cfg.LogoutURL == "" {
cfg.LogoutURL = ConfigDefault.LogoutURL
}
if cfg.CompletionURL == "" {
cfg.CompletionURL = ConfigDefault.CompletionURL
}
if cfg.CallbackURL == "" {
cfg.CallbackURL = ConfigDefault.CallbackURL
}
if cfg.ErrorHandler == nil {
cfg.ErrorHandler = ConfigDefault.ErrorHandler
}
if cfg.CompletionFilter == nil {
cfg.CompletionFilter = defaultCompletionFilter(cfg.CompletionURL)
}
return cfg
}
func stateFromContext(ctx *fiber.Ctx) (string, error) {
state := ctx.Query(state)
if len(state) > 0 {
return state, nil
}
nonce, err := generateRandomString(64)
if err != nil {
return "", err
}
return base64.URLEncoding.EncodeToString(nonce), nil
}
func generateRandomString(n int) ([]byte, error) {
b := make([]byte, n)
for i := 0; i < n; i++ {
num, err := rand.Int(rand.Reader, big.NewInt(int64(len(charset))))
if err != nil {
return b, err
}
b[i] = charset[num.Int64()]
}
return b, nil
}
// TokenFromContext returns the token from the request context.
func TokenFromContext(c *fiber.Ctx) string {
token, ok := c.Locals(tokenKey).(string)
if !ok {
return ""
}
return token
}
// TokenFromCookie returns a function that extracts token from the cookie header.
func TokenFromCookie(param string) func(c *fiber.Ctx) (string, error) {
return func(c *fiber.Ctx) (string, error) {
token := c.Cookies(param)
if token == "" {
return "", ErrMissingCookie
}
return token, nil
}
}