MakeAuthAPI turns a util.JSONRequestHandler function into an http.Handler which authenticates the request.
( metricsName string, userAPI userapi.QueryAcccessTokenAPI, f func(*http.Request, *userapi.Device) util.JSONResponse, )
| 44 | |
| 45 | // MakeAuthAPI turns a util.JSONRequestHandler function into an http.Handler which authenticates the request. |
| 46 | func MakeAuthAPI( |
| 47 | metricsName string, userAPI userapi.QueryAcccessTokenAPI, |
| 48 | f func(*http.Request, *userapi.Device) util.JSONResponse, |
| 49 | ) http.Handler { |
| 50 | h := func(req *http.Request) util.JSONResponse { |
| 51 | logger := util.GetLogger(req.Context()) |
| 52 | device, err := auth.VerifyUserFromRequest(req, userAPI) |
| 53 | if err != nil { |
| 54 | logger.Debugf("VerifyUserFromRequest %s -> HTTP %d", req.RemoteAddr, err.Code) |
| 55 | return *err |
| 56 | } |
| 57 | // add the user ID to the logger |
| 58 | logger = logger.WithField("user_id", device.UserID) |
| 59 | req = req.WithContext(util.ContextWithLogger(req.Context(), logger)) |
| 60 | // add the user to Sentry, if enabled |
| 61 | hub := sentry.GetHubFromContext(req.Context()) |
| 62 | if hub != nil { |
| 63 | hub.Scope().SetTag("user_id", device.UserID) |
| 64 | hub.Scope().SetTag("device_id", device.ID) |
| 65 | } |
| 66 | defer func() { |
| 67 | if r := recover(); r != nil { |
| 68 | if hub != nil { |
| 69 | hub.CaptureException(fmt.Errorf("%s panicked", req.URL.Path)) |
| 70 | } |
| 71 | // re-panic to return the 500 |
| 72 | panic(r) |
| 73 | } |
| 74 | }() |
| 75 | |
| 76 | jsonRes := f(req, device) |
| 77 | // do not log 4xx as errors as they are client fails, not server fails |
| 78 | if hub != nil && jsonRes.Code >= 500 { |
| 79 | hub.Scope().SetExtra("response", jsonRes) |
| 80 | hub.CaptureException(fmt.Errorf("%s returned HTTP %d", req.URL.Path, jsonRes.Code)) |
| 81 | } |
| 82 | return jsonRes |
| 83 | } |
| 84 | return MakeExternalAPI(metricsName, h) |
| 85 | } |
| 86 | |
| 87 | // MakeExternalAPI turns a util.JSONRequestHandler function into an http.Handler. |
| 88 | // This is used for APIs that are called from the internet. |
nothing calls this directly
no test coverage detected