/
auth_middleware.go
52 lines (44 loc) · 1.27 KB
/
auth_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
package middlewares
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
"github.com/opentracing/opentracing-go"
"github.com/x-Iabs/packages/functions"
"github.com/x-Iabs/packages/types"
)
// AuthMiddleware is a middleware that checks if the user is authenticated
func AuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
span, _ := opentracing.StartSpanFromContext(c.Request.Context(), "AuthMiddleware")
defer span.Finish()
authHeader := c.GetHeader("Authorization")
bearerToken := strings.Split(authHeader, " ")
if len(bearerToken) != 2 {
response := types.ErrorResponse{
Status: http.StatusUnauthorized,
Message: "Unauthorized",
Errors: []string{"Invalid authorization header format"},
}
c.JSON(http.StatusUnauthorized, response)
c.Abort()
return
}
// Check if the token is valid
// If the token is not valid, return a 401 Unauthorized
// If the token is valid, call c.Next()
userClaims, err := functions.ValidateToken(bearerToken[1])
if err != nil {
response := types.ErrorResponse{
Status: http.StatusUnauthorized,
Message: "Unauthorized",
Errors: []string{err.Error()},
}
c.JSON(http.StatusUnauthorized, response)
c.Abort()
return
}
c.Set("user_claims", userClaims)
c.Next()
}
}