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

64 lines
1.4 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"
"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-04 20:31:07 +00:00
func (api *API) contextMiddleware(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) {
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
}