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

74 lines
2.1 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 (
"os"
2021-01-22 05:00:55 +00:00
"context"
2021-01-19 21:26:10 +00:00
"net/http"
2021-01-18 04:56:56 +00:00
log "github.com/sirupsen/logrus"
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-01-06 19:36:09 +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-18 04:56:56 +00:00
func (api *API) authMiddleware(next http.Handler) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2021-02-01 23:24:09 +00:00
2021-01-18 21:16:52 +00:00
// Acquire Token
accessCookie, err := r.Cookie("AccessToken")
2021-01-18 04:56:56 +00:00
if err != nil {
2021-01-18 21:16:52 +00:00
log.Warn("[middleware] AccessToken not found")
2021-02-01 23:24:09 +00:00
errorJSON(w, "Invalid token.", http.StatusUnauthorized)
2021-01-18 04:56:56 +00:00
return
}
2021-01-18 21:16:52 +00:00
// Validate JWT Tokens
2021-02-01 23:24:09 +00:00
accessToken, err := api.Auth.ValidateJWTAccessToken(accessCookie.Value)
if err != nil && err.Error() == "exp not satisfied" {
log.Info("[middleware] Refreshing AccessToken")
accessToken, err = api.refreshAccessToken(w, r)
if err != nil {
log.Warn("[middleware] Refreshing AccessToken failed: ", err)
errorJSON(w, "Invalid token.", http.StatusUnauthorized)
return
}
log.Info("[middleware] AccessToken Refreshed")
} else if err != nil {
log.Warn("[middleware] AccessToken failed to validate")
errorJSON(w, "Invalid token.", http.StatusUnauthorized)
return
2021-01-18 21:16:52 +00:00
}
2021-02-01 23:24:09 +00:00
// Acquire UserID and DeviceID
reqInfo := make(map[string]string)
uid, _ := accessToken.Get("sub")
did, _ := accessToken.Get("did")
reqInfo["uid"] = uid.(string)
reqInfo["did"] = did.(string)
// Add context
ctx := context.WithValue(r.Context(), "uuids", reqInfo)
sr := r.WithContext(ctx)
next.ServeHTTP(w, sr)
2021-01-19 21:26:10 +00:00
})
2021-01-18 04:56:56 +00:00
}
func (api *API) logMiddleware(h http.Handler) http.Handler {
2021-01-06 19:36:09 +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)
})
}