PromucFlow_constructor/app/server/api/middleware/middleware.go
Arpit Mohan 1133b53437 Adding Google authentication via Goth. All endpoints can now be authenticated.
Other changes include:
* Also removing httprouter mux in favour of gorilla for being more mature and having more integrations and resources available for debugging.
* Adding http middlewares for logging req processing time and handling authentication.

TODO: Need to add context in the middleware as well. Will be useful for logging and debugging.
2019-03-16 15:47:47 +05:30

82 lines
1.8 KiB
Go

package middleware
import (
"log"
"net/http"
"time"
"github.com/markbates/goth/gothic"
)
type Middleware func(http.HandlerFunc) http.HandlerFunc
// Logging logs all requests with its path and the time it took to process
func Logging() Middleware {
// Create a new Middleware
return func(f http.HandlerFunc) http.HandlerFunc {
// Define the http.HandlerFunc
return func(w http.ResponseWriter, r *http.Request) {
// Do middleware things
start := time.Now()
defer func() { log.Println(r.URL.Path, time.Since(start)) }()
// Call the next middleware/handler in chain
f(w, r)
}
}
}
// Method ensures that url can only be requested with a specific method, else returns a 400 Bad Request
func Method(m string) Middleware {
// Create a new Middleware
return func(f http.HandlerFunc) http.HandlerFunc {
// Define the http.HandlerFunc
return func(w http.ResponseWriter, r *http.Request) {
// Do middleware things
if r.Method != m {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
// Call the next middleware/handler in chain
f(w, r)
}
}
}
func Authenticated() Middleware {
// Create a new Middleware
return func(f http.HandlerFunc) http.HandlerFunc {
// Define the http.HandlerFunc
return func(w http.ResponseWriter, r *http.Request) {
sess, err := gothic.GetFromSession("google", r)
if err != nil {
// Write an error and stop the handler chain
http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
return
}
log.Printf("Got the authenticated user: %s", sess)
f(w, r)
}
}
}
// Chain applies middlewares to a http.HandlerFunc
func Chain(f http.HandlerFunc, middlewares ...Middleware) http.HandlerFunc {
for _, m := range middlewares {
f = m(f)
}
return f
}