Skip to content

Instantly share code, notes, and snippets.

@peacefixation
Last active March 27, 2019 01:34
Show Gist options
  • Save peacefixation/f86da588e3bb05c6d907ab548f2bfc30 to your computer and use it in GitHub Desktop.
Save peacefixation/f86da588e3bb05c6d907ab548f2bfc30 to your computer and use it in GitHub Desktop.
HTTP middleware
import "github.com/julienschmidt/httprouter"
// usage
// router.POST("/path", BasicAuth(someRequestHandler))
// BasicAuth middleware for incoming requests that must include basic authentication
func BasicAuth(handler httprouter.Handle) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
log.Printf("Authorizing request from %s", r.RemoteAddr)
username, password, hasAuth := r.BasicAuth()
if hasAuth == false {
w.Header().Set("WWW-Authenticate", "Basic realm=Restricted")
log.Printf("Request from %s not authorized, missing basic authentication credentials", r.RemoteAddr)
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return
}
// check the credentials against the database ...
validCredentials := model.validCredentials(username, password)
if !validCredentials {
w.Header().Set("WWW-Authenticate", "Basic realm=Restricted")
log.Printf("Request from %s not authorized, invalid basic authentication credentials", r.RemoteAddr)
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return
}
log.Printf("Authorized request from %s", r.RemoteAddr)
handler(w, r, p)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment