im using a middleware (CheckToken
) to check a JWT and get the custom claim (Id
) (it will be the id of the user on my DB) but i need to pass it to campaign.Attack (so i can know who is the user who is doing the "attack") but i cant find out a way to do it.
i tried to pass it as a parameter in next(w, req, claim.id)
in token.go
but i would need to touch the http.HandlerFunc
function so this isnt a valid option.
any idea about how to pass the claim.id
from CheckToken
to campaign.Attack()
?
thank you
***** main.go*****
func main() {
router := mux.NewRouter()
router.HandleFunc("/attack", token.CheckToken(campaign.Attack)).Methods("GET", "OPTIONS")
log.Fatal(http.ListenAndServe(":3000", handlers.CORS(handlers.AllowedOrigins([]string{"*"}),
handlers.AllowedHeaders([]string{"Content-Type", "authorization"}))(router)))
}
******campaign.go*****
package campaign
import (
"log"
"net/http"
)
func init() {
}
func Attack(w http.ResponseWriter, req *http.Request) {
log.Println("attack")
//i need to get the claim.Id here
}
****token.go****
type MyCustomClaims struct {
Id int `json:"id"` //the Id of the user
jwt.StandardClaims
}
func CheckToken(next http.HandlerFunc) (MyCustomClaims, http.HandlerFunc) {
return MyCustomClaims{}, http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
authorizationHeader := req.Header.Get("authorization")
if authorizationHeader != "" {
bearerToken := strings.Split(authorizationHeader, " ")
if len(bearerToken) == 2 {
token, err := jwt.ParseWithClaims(bearerToken[1], &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) {
return []byte("magicword"), nil
})
if token.Valid {
if claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid {
//**************************
//***********i have the claims.id here and it works.*******
//**************************
log.Println(claims.Id)
//but i need to pass it or find a way to read it in campaign.Attack()
next(w, req)
} else {
log.Println(err)
}
} else if ve, ok := err.(*jwt.ValidationError); ok {
if ve.Errors&jwt.ValidationErrorMalformed != 0 {
} else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 {
// Token is either expired or not active yet
}
}
}
}
})
}