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

57 lines
1.5 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-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-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-01-18 04:56:56 +00:00
w.WriteHeader(http.StatusUnauthorized)
return
}
2021-01-18 21:16:52 +00:00
// Validate JWT Tokens
2021-01-19 21:26:10 +00:00
// accessToken, accessOK := api.Auth.ValidateJWTAccessToken(accessCookie.Value)
2021-01-18 21:16:52 +00:00
_, accessOK := api.Auth.ValidateJWTAccessToken(accessCookie.Value)
2021-01-18 04:56:56 +00:00
2021-01-18 21:16:52 +00:00
if accessOK {
2021-01-19 21:26:10 +00:00
// Acquire UserID and DeviceID
// uid, _ := accessToken.Get("sub")
// did, _ := accessToken.Get("did")
// Set context uid & did
2021-01-18 21:16:52 +00:00
next.ServeHTTP(w, r)
} else {
w.WriteHeader(http.StatusUnauthorized)
}
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)
})
}