-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
86 lines (77 loc) · 2.04 KB
/
auth.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
package middleware
import (
"errors"
"fmt"
"net/http"
"strings"
"time"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
hh "github.com/patsnapops/http-headers"
"github.com/spf13/cast"
)
// TokenAuthMiddleware is a middleware function that checks for a valid token in the Authorization header
func TokenAuthMiddleware(ignorePaths []string, secret []byte) gin.HandlerFunc {
return func(c *gin.Context) {
// let the request pass if request method is OPTIONS
if c.Request.Method == http.MethodOptions {
c.Next()
return
}
// Check if the current path is in the ignore list
for _, path := range ignorePaths {
if strings.HasPrefix(c.Request.URL.Path, path) {
c.Next()
return
}
}
token := extractBearerToken(c.Request.Header)
claims, err := parse(token, secret)
if err != nil {
c.AbortWithStatusJSON(http.StatusUnauthorized, err.Error())
return
}
// log.Debugf(tea.Prettify(claims))
err = checkIfExpired(claims)
if err != nil {
c.AbortWithStatusJSON(http.StatusUnauthorized, err.Error())
return
}
c.Next()
}
}
func extractBearerToken(header http.Header) string {
const BearerSpace = "Bearer "
auth := header.Get(hh.Authorization)
token := strings.TrimPrefix(auth, BearerSpace)
return token
}
func checkIfExpired(claims map[string]any) error {
const Exp = "exp"
exp := claims[Exp]
if exp == nil {
return errors.New("exp not found")
}
expTimestamp, ok := exp.(float64)
if !ok {
return errors.New("exp is not a valid int64")
}
if time.Now().Unix() > cast.ToInt64(expTimestamp) {
return errors.New("token expired")
}
return nil
}
// parse use HMAC to decrypt the token
func parse(token string, secret []byte) (map[string]any, error) {
parsedToken, err := jwt.Parse(token, func(token *jwt.Token) (any, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
const Alg = "alg"
return nil, fmt.Errorf("unexpected signing method: %v", token.Header[Alg])
}
return secret, nil
})
if err != nil {
return nil, err
}
return parsedToken.Claims.(jwt.MapClaims), nil
}