From ef68405fb8c3814858281b2fcaf23c2cb52fd007 Mon Sep 17 00:00:00 2001 From: andig Date: Fri, 24 Dec 2021 00:14:53 +0100 Subject: [PATCH] Intercept parameters from http redirects (#2111) --- util/request/intercept.go | 28 ++++++++++++++++++++++++++++ vehicle/nissan/identity.go | 19 ++++++------------- 2 files changed, 34 insertions(+), 13 deletions(-) create mode 100644 util/request/intercept.go diff --git a/util/request/intercept.go b/util/request/intercept.go new file mode 100644 index 000000000..7bb6d3a35 --- /dev/null +++ b/util/request/intercept.go @@ -0,0 +1,28 @@ +package request + +import ( + "fmt" + "net/http" +) + +type InterceptResult = func() (string, error) + +// InterceptRedirect captures a redirect url parameter +func InterceptRedirect(param string, stop bool) (func(req *http.Request, via []*http.Request) error, InterceptResult) { + var val string + return func(req *http.Request, via []*http.Request) error { + if val == "" { + if val = req.URL.Query().Get(param); val != "" && stop { + return http.ErrUseLastResponse + } + } + return nil + }, + func() (string, error) { + var err error + if val == "" { + err = fmt.Errorf("%s not found", param) + } + return val, err + } +} diff --git a/vehicle/nissan/identity.go b/vehicle/nissan/identity.go index eb38a4f24..21322c146 100644 --- a/vehicle/nissan/identity.go +++ b/vehicle/nissan/identity.go @@ -36,7 +36,6 @@ func (v *Identity) Login(user, password string) error { var nToken Token var realm string - var resp *http.Response var code string if err == nil { @@ -95,20 +94,14 @@ func (v *Identity) Login(user, password string) error { }) if err == nil { - v.CheckRedirect = func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse } - resp, err = v.Do(req) - v.CheckRedirect = nil + var param request.InterceptResult + v.Client.CheckRedirect, param = request.InterceptRedirect("code", true) - if err == nil { - resp.Body.Close() - - var location *url.URL - if location, err = url.Parse(resp.Header.Get("Location")); err == nil { - if code = location.Query().Get("code"); code == "" { - err = fmt.Errorf("missing auth code: %v", location) - } - } + if _, err = v.Do(req); err == nil { + code, err = param() } + + v.CheckRedirect = nil } }