-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.go
41 lines (31 loc) · 922 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
41
package auth
import (
"context"
"net/http"
"strings"
"github.com/golang-jwt/jwt/v5"
)
func Validate(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
tokenString := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
claims := new(Claims)
token, err := jwt.ParseWithClaims(tokenString, claims, func(t *jwt.Token) (interface{}, error) {
return []byte(jwtSecret), nil
})
if err != nil {
if err == jwt.ErrSignatureInvalid {
http.Error(rw, err.Error(), http.StatusUnauthorized)
return
}
http.Error(rw, err.Error(), http.StatusBadRequest)
return
}
if !token.Valid {
http.Error(rw, err.Error(), http.StatusUnauthorized)
return
}
ctx := context.WithValue(r.Context(), "user_id", claims.UserID)
ctx = context.WithValue(ctx, "user_name", claims.UserName)
next.ServeHTTP(rw, r.WithContext(ctx))
})
}