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"
|
|
|
|
|
|
|
|
"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-10 05:09:57 +00:00
|
|
|
func (api *API) queryMiddleware(next http.Handler) http.Handler {
|
2021-02-04 10:16:13 +00:00
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
2021-02-10 05:09:57 +00:00
|
|
|
|
|
|
|
// TODO: REMOVE (SOME OF) THIS!! Only for developement due to CORS
|
|
|
|
w.Header().Set("Access-Control-Allow-Credentials", "true")
|
|
|
|
w.Header().Set("Access-Control-Allow-Origin", "*")
|
|
|
|
w.Header().Set("Access-Control-Expose-Headers", "*")
|
|
|
|
w.Header().Set("Access-Control-Allow-Headers", "*")
|
|
|
|
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
|
|
|
|
|
2021-02-04 10:16:13 +00:00
|
|
|
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) {
|
2021-02-04 20:31:07 +00:00
|
|
|
// Validate Tokens
|
2021-02-04 10:16:13 +00:00
|
|
|
accessToken, err := api.validateTokens(&w, r)
|
|
|
|
if err != nil {
|
2021-02-04 20:31:07 +00:00
|
|
|
w.WriteHeader(http.StatusUnauthorized)
|
2021-02-04 10:16:13 +00:00
|
|
|
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-06 19:36:09 +00:00
|
|
|
}
|