-
Notifications
You must be signed in to change notification settings - Fork 1
/
gin_middleware.go
55 lines (46 loc) · 1.4 KB
/
gin_middleware.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
package auth
import (
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt"
)
type tokenSvc interface {
VerifyToken(token string) (*jwt.Token, error)
ValidateAccessTokenClaims(claims jwt.Claims) (string, error)
}
func GinStdMiddleware(conf Config) gin.HandlerFunc {
return GinMiddleware(NewStdClaimsSvc(
time.Duration(conf.AccessTokenValiditySeconds),
time.Duration(conf.RefreshTokenValiditySeconds),
conf.SecretKey,
))
}
func GinMiddleware(tokenSvc tokenSvc) gin.HandlerFunc {
return func(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Authorization header is missing"})
return
}
authHeaderParts := strings.Split(authHeader, " ")
if len(authHeaderParts) != 2 || authHeaderParts[0] != "Bearer" {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid Authorization header format"})
return
}
parsedToken, err := tokenSvc.VerifyToken(authHeaderParts[1])
if err != nil {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"})
return
}
sub, err := tokenSvc.ValidateAccessTokenClaims(parsedToken.Claims)
if err != nil {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
return
}
c.Set(CtxKeyTokenClaims, parsedToken.Claims)
c.Set(CtxKeyUserID, sub)
c.Next()
}
}