naise_pos/api/middleware.go

52 lines
1.3 KiB
Go
Raw Normal View History

2023-03-15 15:00:36 +07:00
package api
import (
"errors"
"fmt"
"net/http"
"strings"
"git.nochill.in/nochill/naice_pos/token"
"github.com/gin-gonic/gin"
)
const (
authorizationHeaderKey = "authorization"
authorizationTypeBearer = "bearer"
authorizationPayloadKey = "authorization_payload"
)
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 is not provided")
2023-03-22 12:06:09 +07:00
ctx.AbortWithStatusJSON(http.StatusUnauthorized, errorResponse(err, ""))
2023-03-15 15:00:36 +07:00
return
}
fields := strings.Fields(authorizationHeader)
if len(fields) < 2 {
err := errors.New("Invalid authorization header format")
2023-03-22 12:06:09 +07:00
ctx.AbortWithStatusJSON(http.StatusUnauthorized, errorResponse(err, ""))
2023-03-15 15:00:36 +07:00
return
}
authorizationType := strings.ToLower(fields[0])
if authorizationType != authorizationTypeBearer {
err := fmt.Errorf("Authorization only accept bearer type")
2023-03-22 12:06:09 +07:00
ctx.AbortWithStatusJSON(http.StatusUnauthorized, errorResponse(err, ""))
2023-03-15 15:00:36 +07:00
}
accessToken := fields[1]
payload, err := tokenMaker.VerifyToken(accessToken)
if err != nil {
2023-03-22 12:06:09 +07:00
ctx.AbortWithStatusJSON(http.StatusUnauthorized, errorResponse(err, ""))
2023-03-15 15:00:36 +07:00
return
}
ctx.Set(authorizationPayloadKey, payload)
ctx.Next()
}
}