refactor(verify-client): simplify error handling

This commit is contained in:
ArcticLampyrid 2024-11-15 03:12:26 +08:00
parent bb79471139
commit dfebd176df
No known key found for this signature in database
GPG key ID: DC72A2519E77D6CF

View file

@ -71,37 +71,34 @@ func (h *Headscale) VerifyHandler(
Str("handler", "/verify"). Str("handler", "/verify").
Msg("verify client") Msg("verify client")
doVerify := func() (bool, error) {
body, err := io.ReadAll(req.Body) body, err := io.ReadAll(req.Body)
if err != nil { if err != nil {
log.Error(). return false, fmt.Errorf("cannot read request body: %w", err)
Str("handler", "/verify").
Err(err).
Msg("Cannot read request body")
http.Error(writer, "Internal error", http.StatusInternalServerError)
return
} }
var derpAdmitClientRequest tailcfg.DERPAdmitClientRequest var derpAdmitClientRequest tailcfg.DERPAdmitClientRequest
if err := json.Unmarshal(body, &derpAdmitClientRequest); err != nil { if err := json.Unmarshal(body, &derpAdmitClientRequest); err != nil {
log.Error(). return false, fmt.Errorf("cannot parse derpAdmitClientRequest: %w", err)
Caller().
Err(err).
Msg("Cannot parse derpAdmitClientRequest")
http.Error(writer, "Internal error", http.StatusInternalServerError)
return
} }
nodes, err := h.db.ListNodes() nodes, err := h.db.ListNodes()
if err != nil {
return false, fmt.Errorf("cannot list nodes: %w", err)
}
return nodes.ContainsNodeKey(derpAdmitClientRequest.NodePublic), nil
}
allow, err := doVerify()
if err != nil { if err != nil {
log.Error(). log.Error().
Caller(). Caller().
Err(err). Err(err).
Msg("Cannot list nodes") Msg("Failed to verify client")
http.Error(writer, "Internal error", http.StatusInternalServerError) http.Error(writer, "Internal error", http.StatusInternalServerError)
} }
allow := nodes.ContainsNodeKey(derpAdmitClientRequest.NodePublic)
resp := tailcfg.DERPAdmitClientResponse{ resp := tailcfg.DERPAdmitClientResponse{
Allow: allow, Allow: allow,
} }