Is there a more efficient way to authenticate users on certain handle requests? Right now I am calling a function to authenticate based off of the request token but am doing that for every handle function.
func GetCompanies(w http.ResponseWriter, r *http.Request) {
//Authentication
token := r.Header.Get("Authorization")
err := auth.AuthenticateUser(token)
if err != nil {
if custom, ok := err.(*errors.MyErrorType); ok {
fmt.Println(custom.Error())
w.WriteHeader(custom.Code)
_ = json.NewEncoder(w).Encode("Error: " + custom.Msg)
} else {
fmt.Println(err)
w.WriteHeader(500)
}
return
}
//If user is authenticated do other stuff
}
I have tried using middleware but it runs for every handle function. I want unauthenticated users to access certain API's
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Do stuff here
fmt.Println(r.URL)
// Call the next handler, which can be another middleware in the chain, or the final handler.
next.ServeHTTP(w, r)
})
}
func HandleFunctions() {
//Init Router
r := mux.NewRouter()
r.Use(loggingMiddleware)
//API Paths that do not require Auth
r.HandleFunc("/login", handlers.Authenticate).Methods("POST")
//API Paths that require auth
r.HandleFunc("/stuff", handlers.PostThings).Methods("POST")
}
I also want to be able to implement user roles in the future so based on security permissions different paths will be available or not.
What is the most efficient way to do this?