mirror of
https://github.com/element-hq/dendrite.git
synced 2025-09-13 12:52:24 +03:00
Implement MSC3916 (#3397)
Needs https://github.com/matrix-org/gomatrixserverlib/pull/437
This commit is contained in:
parent
8c6cf51b8f
commit
7a4ef240fc
13 changed files with 364 additions and 45 deletions
|
@ -15,6 +15,7 @@
|
|||
package httputil
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
|
@ -44,6 +45,7 @@ type BasicAuth struct {
|
|||
|
||||
type AuthAPIOpts struct {
|
||||
GuestAccessAllowed bool
|
||||
WithAuth bool
|
||||
}
|
||||
|
||||
// AuthAPIOption is an option to MakeAuthAPI to add additional checks (e.g. guest access) to verify
|
||||
|
@ -57,6 +59,13 @@ func WithAllowGuests() AuthAPIOption {
|
|||
}
|
||||
}
|
||||
|
||||
// WithAuth is an option to MakeHTTPAPI to add authentication.
|
||||
func WithAuth() AuthAPIOption {
|
||||
return func(opts *AuthAPIOpts) {
|
||||
opts.WithAuth = true
|
||||
}
|
||||
}
|
||||
|
||||
// MakeAuthAPI turns a util.JSONRequestHandler function into an http.Handler which authenticates the request.
|
||||
func MakeAuthAPI(
|
||||
metricsName string, userAPI userapi.QueryAcccessTokenAPI,
|
||||
|
@ -197,13 +206,32 @@ func MakeExternalAPI(metricsName string, f func(*http.Request) util.JSONResponse
|
|||
return http.HandlerFunc(withSpan)
|
||||
}
|
||||
|
||||
// MakeHTMLAPI adds Span metrics to the HTML Handler function
|
||||
// MakeHTTPAPI adds Span metrics to the HTML Handler function
|
||||
// This is used to serve HTML alongside JSON error messages
|
||||
func MakeHTMLAPI(metricsName string, enableMetrics bool, f func(http.ResponseWriter, *http.Request)) http.Handler {
|
||||
func MakeHTTPAPI(metricsName string, userAPI userapi.QueryAcccessTokenAPI, enableMetrics bool, f func(http.ResponseWriter, *http.Request), checks ...AuthAPIOption) http.Handler {
|
||||
withSpan := func(w http.ResponseWriter, req *http.Request) {
|
||||
trace, ctx := internal.StartTask(req.Context(), metricsName)
|
||||
defer trace.EndTask()
|
||||
req = req.WithContext(ctx)
|
||||
|
||||
// apply additional checks, if any
|
||||
opts := AuthAPIOpts{}
|
||||
for _, opt := range checks {
|
||||
opt(&opts)
|
||||
}
|
||||
|
||||
if opts.WithAuth {
|
||||
logger := util.GetLogger(req.Context())
|
||||
_, jsonErr := auth.VerifyUserFromRequest(req, userAPI)
|
||||
if jsonErr != nil {
|
||||
w.WriteHeader(jsonErr.Code)
|
||||
if err := json.NewEncoder(w).Encode(jsonErr.JSON); err != nil {
|
||||
logger.WithError(err).Error("failed to encode JSON response")
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
f(w, req)
|
||||
}
|
||||
|
||||
|
|
|
@ -218,5 +218,5 @@ func assertNoError(t *testing.T, err error, msg string) {
|
|||
if err == nil {
|
||||
return
|
||||
}
|
||||
t.Fatalf(msg)
|
||||
t.Fatal(msg)
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue