-
Notifications
You must be signed in to change notification settings - Fork 4
/
middleware.go
63 lines (53 loc) · 1.75 KB
/
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
package api
import (
"context"
"log"
"net/http"
"strconv"
"strings"
"github.com/Tech-With-Tim/cdn/utils"
"github.com/golang-jwt/jwt"
)
const errorstring string = "The server could not verify that you are authorized to access the URL requested. " +
"You either supplied the wrong credentials (e.g. a bad password), " +
"or your browser doesn't understand how to supply the credentials required."
func AuthJwtWrap(SecretKey string) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var resp = map[string]interface{}{"error": "unauthorized", "message": "missing authorization token"}
var header = r.Header.Get("Authorization")
header = strings.TrimSpace(header)
if header == "" {
utils.JSON(w, http.StatusUnauthorized, resp)
return
}
//utils.ExportVariables()
token, err := jwt.Parse(header, func(token *jwt.Token) (interface{}, error) {
return []byte(SecretKey), nil
})
if err != nil {
resp["error"] = "unauthorized"
if err.Error() == "Token is expired" {
resp["message"] = err.Error()
utils.JSON(w, http.StatusUnauthorized, resp)
return
}
resp["message"] = errorstring
utils.JSON(w, http.StatusUnauthorized, resp)
log.Println(err.Error())
return
}
claims, _ := token.Claims.(jwt.MapClaims)
uid, err := strconv.Atoi(claims["uid"].(string))
//fmt.Println(sub)
if err != nil {
resp["error"] = "something unexpected occurred"
utils.JSON(w, http.StatusInternalServerError, resp)
log.Println(err.Error())
return
}
ctx := context.WithValue(r.Context(), "uid", uid) // adding the user ID to the context
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}