This repository has been archived on 2023-11-13. You can view files and clone it, but cannot push or open issues or pull requests.
imagini/internal/api/middlewares.go

80 lines
1.7 KiB
Go
Raw Normal View History

2021-01-16 22:00:17 +00:00
package api
2021-01-06 19:36:09 +00:00
import (
2021-02-04 10:16:13 +00:00
"context"
"net/http"
"os"
2021-02-03 03:55:35 +00:00
2021-02-04 10:16:13 +00:00
log "github.com/sirupsen/logrus"
"reichard.io/imagini/graph/model"
2021-01-06 19:36:09 +00:00
)
2021-01-18 04:56:56 +00:00
type Middleware func(http.Handler) http.HandlerFunc
2021-01-06 19:36:09 +00:00
2021-01-18 04:56:56 +00:00
func multipleMiddleware(h http.HandlerFunc, m ...Middleware) http.HandlerFunc {
2021-02-04 10:16:13 +00:00
if len(m) < 1 {
return h
}
wrapped := h
for i := len(m) - 1; i >= 0; i-- {
wrapped = m[i](wrapped)
}
return wrapped
2021-01-06 19:36:09 +00:00
}
2021-02-04 10:16:13 +00:00
/**
* This is used for the graphQL endpoints that may require access to the
* Request and ResponseWriter variables. These are used to get / set cookies.
**/
2021-02-03 03:55:35 +00:00
func (api *API) injectContextMiddleware(next http.Handler) http.Handler {
2021-02-04 10:16:13 +00:00
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authContext := &model.AuthContext{
AuthResponse: &w,
AuthRequest: r,
}
// Add context
ctx := context.WithValue(r.Context(), "auth", authContext)
r = r.WithContext(ctx)
next.ServeHTTP(w, r)
})
2021-02-03 03:55:35 +00:00
}
2021-02-04 10:16:13 +00:00
/**
* This is used for non graphQL endpoints that require authentication.
**/
2021-01-18 04:56:56 +00:00
func (api *API) authMiddleware(next http.Handler) http.HandlerFunc {
2021-02-04 10:16:13 +00:00
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
accessToken, err := api.validateTokens(&w, r)
if err != nil {
errorJSON(w, "Invalid token.", http.StatusUnauthorized)
return
}
// Create Context
authContext := &model.AuthContext{
AccessToken: &accessToken,
}
ctx := context.WithValue(r.Context(), "auth", authContext)
r = r.WithContext(ctx)
next.ServeHTTP(w, r)
})
2021-01-18 04:56:56 +00:00
}
func (api *API) logMiddleware(h http.Handler) http.Handler {
2021-02-04 10:16:13 +00:00
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.SetOutput(os.Stdout)
log.Println(r.Method, r.URL)
h.ServeHTTP(w, r)
})
2021-01-06 19:36:09 +00:00
}