-
Notifications
You must be signed in to change notification settings - Fork 0
/
admin_middleware.go
70 lines (58 loc) · 1.68 KB
/
admin_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
60
61
62
63
64
65
66
67
68
69
70
package middlewares
import (
"net/http"
"strings"
"github.com/educolog9/packages/functions"
"github.com/educolog9/packages/types"
"github.com/gin-gonic/gin"
"github.com/opentracing/opentracing-go"
)
type Key int
const UserClaimsKey Key = iota
// AdminMiddleware is a middleware that checks if the user is an admin
func AdminMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
span, _ := opentracing.StartSpanFromContext(c.Request.Context(), "AdminMiddleware")
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, check if the user is an admin
// If the user is not an admin, return a 403 Forbidden
// If the user is an admin, 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
}
if !userClaims.IsAdmin() {
response := types.ErrorResponse{
Status: http.StatusForbidden,
Message: "Forbidden",
Errors: []string{"User is not an admin"},
}
c.JSON(http.StatusForbidden, response)
c.Abort()
return
}
c.Set("userClaims", userClaims)
c.Next()
}
}