package main import ( "encoding/json" "log" "net/http" "github.com/devict/magopie" "github.com/devict/magopie/vendor/github.com/gorilla/mux" "github.com/devict/magopie/vendor/github.com/justinas/alice" ) // WebServer ... type WebServer struct { addr string tlsCert string tlsKey string adminMode bool } // Listen makes it listen for connetions func (s *WebServer) Listen() { if s.tlsCert != "" && s.tlsKey != "" { log.Printf("Listening for HTTPS on %s with key %s and cert %s", s.addr, s.tlsKey, s.tlsCert) log.Fatal(http.ListenAndServeTLS(s.addr, s.tlsCert, s.tlsKey, s.router(a))) } else { log.Printf("Listening for HTTP on %s", *addr) log.Fatal(http.ListenAndServe(*addr, s.router(a))) } } // Router defines all of the routes func (s *WebServer) Router() http.Handler { r := mux.NewRouter() r.HandleFunc("/", s.handleAllSites).Methods("GET") r.HandleFunc("/genAPIKey/{db}", s.genAPIKey).Methods("POST") chain := alice.New(mwLogger, mwAuthenticationCheck(a.key)).Then(r) return chain } func (s *WebServer) handleRequest(w http.ResponseWriter, r *http.Request) { err := json.NewEncoder(w).Encode() if err != nil { log.Println(err) } } func (s *WebServer) genAPIKey(w http.ResponseWriter, r *http.Request) { err := json.NewEncoder(w).Encode() if err != nil { log.Println(err) } } func (s *WebServer) mwLogger(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { log.Println("Serving", r.Method, r.URL.String(), "to", r.RemoteAddr) next.ServeHTTP(w, r) }) } func (s *WebServer) mwAuthenticationCheck(key string) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if !magopie.CheckMAC(r.Header.Get("X-Request-ID"), r.Header.Get("X-HMAC"), key) { log.Println("Request failed HMAC") w.WriteHeader(http.StatusUnauthorized) return } next.ServeHTTP(w, r) }) } }