I have an api that manages various company jobs, authorizes with bearer token I want from user to select one of the available task from the tasks list in order to use /api/tasks/{task} url like this: /api/tasks/checkaccount if the given task doesn't on the tasks list return not valid url. Is there a way that can handle this job in the validateMiddleware function?
My startApi function:
func (s *ApiServerStruct) Start(interval int) {
router := mux.NewRouter()
log.Println("Starting the Api")
log.Printf("Api Listen: %s
", "127.0.0.1:8080")
router.HandleFunc("/api/customer/newcustomer", ValidateMiddleware(s.newcustomer)).Methods("POST")
router.HandleFunc("/api/customer/setsalary", ValidateMiddleware(s.SetSalary)).Methods("POST")
router.HandleFunc("/api/customer/listcustomers", ValidateMiddleware(s.ListCustomers)).Methods("GET")
router.HandleFunc("/api/customer/{login:0x[0-9a-fA-F]{40}}/newjob", ValidateMiddleware(s.NewJob)).Methods("POST")
router.HandleFunc("/api/tasks/{task}/setnewtask", ValidateMiddleware(s.SetNewTask)).Methods("POST")
And a validateMiddleware function that checks whether given token in the header valid or not:
func ValidateMiddleware(next http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
authorizationHeader := req.Header.Get("authorization")
if authorizationHeader != "" {
bearerToken := strings.Split(authorizationHeader, " ")
tempData := Data[bearerToken[1]]
secretKey := tempData["secretkey"]
if secretKey == "" {
json.NewEncoder(w).Encode(Exception{Message: "Invalid authorization token"})
return
}
if len(bearerToken) == 2 {
token, error := jwt.Parse(bearerToken[1], func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("There was an error")
}
return []byte(secretKey), nil
})
if error != nil {
json.NewEncoder(w).Encode(Exception{Message: error.Error()})
return
}
if token.Valid {
context.Set(req, "decoded", token.Claims)
next(w, req)
} else {
json.NewEncoder(w).Encode(Exception{Message: "Invalid authorization token"})
}
}
} else {
json.NewEncoder(w).Encode(Exception{Message: "An authorization header is required"})
}
})
}