2017-05-23 17:43:05 +01:00
|
|
|
package common
|
|
|
|
|
|
|
|
import (
|
2017-07-17 17:20:57 +01:00
|
|
|
"net/http"
|
2017-09-04 13:14:01 +01:00
|
|
|
"time"
|
2017-07-17 17:20:57 +01:00
|
|
|
|
2017-08-03 15:10:39 +01:00
|
|
|
"github.com/gorilla/mux"
|
2017-05-23 17:43:05 +01:00
|
|
|
"github.com/matrix-org/dendrite/clientapi/auth"
|
|
|
|
"github.com/matrix-org/dendrite/clientapi/auth/authtypes"
|
2017-09-04 13:14:01 +01:00
|
|
|
"github.com/matrix-org/gomatrixserverlib"
|
2017-05-23 17:43:05 +01:00
|
|
|
"github.com/matrix-org/util"
|
|
|
|
"github.com/prometheus/client_golang/prometheus"
|
|
|
|
)
|
|
|
|
|
|
|
|
// MakeAuthAPI turns a util.JSONRequestHandler function into an http.Handler which checks the access token in the request.
|
2017-07-17 17:20:57 +01:00
|
|
|
func MakeAuthAPI(metricsName string, deviceDB auth.DeviceDatabase, f func(*http.Request, *authtypes.Device) util.JSONResponse) http.Handler {
|
2017-09-04 13:14:01 +01:00
|
|
|
h := func(req *http.Request) util.JSONResponse {
|
2017-05-23 17:43:05 +01:00
|
|
|
device, resErr := auth.VerifyAccessToken(req, deviceDB)
|
|
|
|
if resErr != nil {
|
|
|
|
return *resErr
|
|
|
|
}
|
|
|
|
return f(req, device)
|
2017-09-04 13:14:01 +01:00
|
|
|
}
|
|
|
|
return MakeAPI(metricsName, h)
|
2017-05-23 17:43:05 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// MakeAPI turns a util.JSONRequestHandler function into an http.Handler.
|
|
|
|
func MakeAPI(metricsName string, f func(*http.Request) util.JSONResponse) http.Handler {
|
|
|
|
h := util.NewJSONRequestHandler(f)
|
|
|
|
return prometheus.InstrumentHandler(metricsName, util.MakeJSONAPI(h))
|
|
|
|
}
|
2017-08-03 15:10:39 +01:00
|
|
|
|
2017-09-04 13:14:01 +01:00
|
|
|
// MakeFedAPI makes an http.Handler that checks matrix federation authentication.
|
|
|
|
func MakeFedAPI(
|
|
|
|
metricsName string,
|
|
|
|
serverName gomatrixserverlib.ServerName,
|
|
|
|
keyRing gomatrixserverlib.KeyRing,
|
|
|
|
f func(*http.Request, *gomatrixserverlib.FederationRequest) util.JSONResponse,
|
|
|
|
) http.Handler {
|
|
|
|
h := func(req *http.Request) util.JSONResponse {
|
|
|
|
fedReq, errResp := gomatrixserverlib.VerifyHTTPRequest(
|
|
|
|
req, time.Now(), serverName, keyRing,
|
|
|
|
)
|
|
|
|
if fedReq == nil {
|
|
|
|
return errResp
|
|
|
|
}
|
|
|
|
return f(req, fedReq)
|
|
|
|
}
|
|
|
|
return MakeAPI(metricsName, h)
|
|
|
|
}
|
|
|
|
|
2017-08-03 15:10:39 +01:00
|
|
|
// SetupHTTPAPI registers an HTTP API mux under /api and sets up a metrics
|
|
|
|
// listener.
|
|
|
|
func SetupHTTPAPI(servMux *http.ServeMux, apiMux *mux.Router) {
|
2017-09-20 14:54:17 +01:00
|
|
|
// This is deprecated.
|
|
|
|
servMux.Handle("/metrics", prometheus.Handler()) // nolint: megacheck, staticcheck
|
2017-08-03 15:10:39 +01:00
|
|
|
servMux.Handle("/api/", http.StripPrefix("/api", apiMux))
|
|
|
|
}
|