This repository was archived by the owner on May 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathmain.go
More file actions
59 lines (50 loc) · 1.4 KB
/
main.go
File metadata and controls
59 lines (50 loc) · 1.4 KB
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
// 🚀 Fiber is an Express inspired web framework written in Go with 💖
// 📌 API Documentation: https://fiber.wiki
// 📝 Github Repository: https://github.com/gofiber/fiber
// Special thanks to Echo: https://github.com/labstack/echo/blob/master/middleware/jwt.go
package jwtware
import (
"reflect"
"github.com/gofiber/fiber/v2"
"github.com/golang-jwt/jwt/v5"
)
var (
defaultTokenLookup = "header:" + fiber.HeaderAuthorization
)
// New ...
func New(config ...Config) fiber.Handler {
cfg := makeCfg(config)
extractors := cfg.getExtractors()
// Return middleware handler
return func(c *fiber.Ctx) error {
// Filter request to skip middleware
if cfg.Filter != nil && cfg.Filter(c) {
return c.Next()
}
var auth string
var err error
for _, extractor := range extractors {
auth, err = extractor(c)
if auth != "" && err == nil {
break
}
}
if err != nil {
return cfg.ErrorHandler(c, err)
}
var token *jwt.Token
if _, ok := cfg.Claims.(jwt.MapClaims); ok {
token, err = jwt.Parse(auth, cfg.KeyFunc)
} else {
t := reflect.ValueOf(cfg.Claims).Type().Elem()
claims := reflect.New(t).Interface().(jwt.Claims)
token, err = jwt.ParseWithClaims(auth, claims, cfg.KeyFunc)
}
if err == nil && token.Valid {
// Store user information from token into context.
c.Locals(cfg.ContextKey, token)
return cfg.SuccessHandler(c)
}
return cfg.ErrorHandler(c, err)
}
}