watchforstock / evohome-client

Python client to access the Evohome web service
Apache License 2.0
88 stars 52 forks source link

evohomeclient2 fails to use user credentials after refresh_token fails #94

Closed zxdavb closed 5 years ago

zxdavb commented 5 years ago

This is what should happen when the refresh_token is invalid (FWIW the access_token is expired):

[evohomeclient2] No/Expired/Invalid access_token, re-authenticating...
[evohomeclient2] Trying refresh_token...

[evohomeclient2] Invalid refresh_token, will try user credentials.
[evohomeclient2] Trying user credentials...
[evohomeclient2] refresh_token = lLpiUoQYFQSvf0AXf9oq9fV16D6U...
[evohomeclient2] access_token = EWI3r8YM4LFN2udpVOoLhGcPWAG4R...
[evohomeclient2] access_token_expires = 2019-05-19 18:08:28

This is what I'm getting:

[evohomeclient2] No/Expired/Invalid access_token, re-authenticating...
[evohomeclient2] Trying refresh_token...

[homeassistant.components.evohome] setup(): Failed to authenticate with the vendor's server. Check your username and password are correct. Resolve any errors and restart HA. Message is: Unable to obtain an Access Token, hint: {"error":"invalid_grant"}
zxdavb commented 5 years ago

The reason is the regression in line 112: https://github.com/watchforstock/evohome-client/blob/f1cb9273e97946d79c0651f00a218abbf7ada53a/evohomeclient2/__init__.py#L110-L115

Should have instead except AuthenticationError:: https://github.com/zxdavb/evohome-client/blob/4bb338998e49315bb07c166ede93bd8570bddfaf/evohomeclient2/__init__.py#L110-L115

This is because in _obtain_access_token(), we introduced some raises towards the end of the refactoring:

    try:
        response.raise_for_status()
    except requests.HTTPError:
        msg = "Unable to obtain an Access Token"
        if response.text:  # if there is a message, then raise with it
            msg = msg + ", hint: " + response.text
        raise AuthenticationError(msg)
...
        except KeyError:
            raise AuthenticationError("Unable to obtain an Access Token, "
                                      "hint: " + response_json)

        except ValueError:
            raise AuthenticationError("Unable to obtain an Access Token, "
                                      "hint: " + response.text)

I have tested a solution, as above, and will submit a PR shortly.

zxdavb commented 5 years ago

@watchforstock Thanks for merging to master - any chance you could push this to PyPi as a new release? I am implementing a feature in HomeAssistant that requires this fix.

watchforstock commented 5 years ago

@zxdavb Sorry for the delay - v0.3.3 is now available in PyPI...

zxdavb commented 5 years ago

Thanks!