/
middleware.go
59 lines (50 loc) · 1.55 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
55
56
57
58
59
package api
import (
"errors"
"fmt"
"log"
"net/http"
"strings"
"github.com/gin-gonic/gin"
"github.com/oluijks/golang-starter/server/internal/config"
"github.com/oluijks/golang-starter/server/internal/token"
)
const (
authorizationHeaderKey = "Authorization"
authorizationTypeBearer = "bearer"
authorizationPayloadKey = "authorization_payload"
)
func authMiddleware(config *config.Config) gin.HandlerFunc {
tokenMaker, err := token.PasetoMaker(config.SymmectricTokenKey)
if err != nil {
log.Fatal("Error creating token maker:", err)
}
return func(ctx *gin.Context) {
autorizationHeader := ctx.GetHeader(authorizationHeaderKey)
if len(autorizationHeader) == 0 {
err := errors.New("missing authorization header")
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
return
}
fields := strings.Fields(autorizationHeader)
if len(fields) < 2 {
err := errors.New("invalid authorization header")
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
return
}
authorizationType := strings.ToLower(fields[0])
if authorizationType != authorizationTypeBearer {
err := fmt.Errorf("unsupported authorization type %s", authorizationType)
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
return
}
accessToken := fields[1]
payload, err := tokenMaker.VerifyToken(accessToken)
if err != nil {
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
return
}
ctx.Set(authorizationPayloadKey, payload)
ctx.Next()
}
}