-
Notifications
You must be signed in to change notification settings - Fork 3
/
middleware.go
40 lines (34 loc) · 951 Bytes
/
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
package cognito
import (
"errors"
"net/http"
"strings"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
)
func (cog *Cognito) Authorize(c *gin.Context) {
tokenHeader, err := tokenFromAuthHeader(c.Request)
if err != nil {
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"message": "invalid Authorization header"})
return
}
token, err := cog.VerifyToken(tokenHeader)
if err != nil {
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"message": "invalid token"})
return
}
c.Set("token", token)
c.Set("email", token.Claims.(jwt.MapClaims)["email"])
c.Next()
}
func tokenFromAuthHeader(r *http.Request) (string, error) {
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
return "", errors.New("no token")
}
parts := strings.Fields(authHeader)
if len(parts) != 2 || strings.ToLower(parts[0]) != "bearer" {
return "", errors.New("invalid Authorization header format")
}
return parts[1], nil
}