-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.go
54 lines (46 loc) · 1.47 KB
/
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
package api
import (
"errors"
"fmt"
"net/http"
"strings"
"github.com/blessedmadukoma/go-simple-bank/token"
"github.com/gin-gonic/gin"
)
const (
authorizationHeaderKey = "authorization"
authorizationTypeBearer = "bearer"
authorizationPayloadKey = "authorization_payload"
)
// authMiddleware authorizes/validates a user
func authMiddleware(tokenMaker token.Maker) gin.HandlerFunc {
return func(ctx *gin.Context) {
authorizationHeader := ctx.GetHeader(authorizationHeaderKey)
if len(authorizationHeader) == 0 {
err := errors.New("authorization header not provided")
ctx.AbortWithStatusJSON(http.StatusUnauthorized, errorResponse("unauthorized", err))
return
}
fields := strings.Fields(authorizationHeader)
if len(fields) < 2 {
err := errors.New("invalid authorization header format")
ctx.AbortWithStatusJSON(http.StatusUnauthorized, errorResponse("unauthorized", err))
return
}
authorizationType := strings.ToLower(fields[0])
if authorizationType != authorizationTypeBearer {
err := fmt.Errorf("unsupported authorization type %s", authorizationType)
ctx.AbortWithStatusJSON(http.StatusUnauthorized, errorResponse("unauthorized", err))
return
}
accessToken := fields[1]
payload, err := tokenMaker.VerifyToken(accessToken)
if err != nil {
ctx.AbortWithStatusJSON(http.StatusUnauthorized, errorResponse("invalid access token", err))
return
}
// store payload in the context
ctx.Set(authorizationPayloadKey, payload)
ctx.Next()
}
}