Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhance token management in cloud command handling #56

Merged
merged 4 commits into from
Aug 26, 2024

Conversation

d3dfantasy99
Copy link
Contributor

@d3dfantasy99 d3dfantasy99 commented Aug 19, 2024

Description

  • Introduced a mechanism to check and refresh the IoT token before sending commands.
  • Enhanced the send_cloud_command method to ensure token validity.
  • Added error handling for token expiration scenarios.

Changes walkthrough 📝

Relevant files
Enhancement
cloud_gateway.py
Enhance token management in cloud command handling             

pymammotion/aliyun/cloud_gateway.py

  • Added token check and refresh logic in send_cloud_command.
  • Implemented check_or_refresh_session method to handle token
    expiration.
  • Updated session management with new token attributes.
  • +40/-4   
    session_by_authcode_response.py
    Update session response structure for token data                 

    pymammotion/aliyun/dataclass/session_by_authcode_response.py

  • Modified SessionByAuthCodeResponse to include token data.
  • Added field import for future enhancements.
  • +2/-2     

    @mikey0000 mikey0000 changed the base branch from main to make-em-mow August 19, 2024 19:28
    if self._iot_token_issued_at + self._session_by_authcode_response.data.refreshTokenExpire > (int(time.time())):
    self.check_or_refresh_session()
    else:
    raise Exception("Refresh token expired. Please re-login")
    Copy link
    Owner

    Choose a reason for hiding this comment

    The reason will be displayed to describe this comment to others. Learn more.

    Need to create a token expired exception type so it can be caught

    @@ -1,4 +1,5 @@
    from dataclasses import dataclass
    from dataclasses import dataclass, field
    from datetime import time
    Copy link
    Owner

    Choose a reason for hiding this comment

    The reason will be displayed to describe this comment to others. Learn more.

    Unused import?

    if int(response_body_dict.get("code")) != 200:
    raise Exception("Error check or refresh token: " + response_body_dict.get('msg', ''))

    identityId = response_body_dict.get('data', {}).get('identityId', None)
    Copy link
    Owner

    Choose a reason for hiding this comment

    The reason will be displayed to describe this comment to others. Learn more.

    There should be a dataclass for this, so you can do e.g IotToken().from_dict(response_body_dict.get('data', {}))

    Or create one, plenty of examples in the make-em-mow branch

    @mikey0000 mikey0000 marked this pull request as ready for review August 26, 2024 20:23
    @mikey0000 mikey0000 merged commit 2f96392 into mikey0000:make-em-mow Aug 26, 2024
    1 check failed
    @penify-dev penify-dev bot added the enhancement New feature or request label Aug 26, 2024
    @penify-dev penify-dev bot changed the title Add check and refresh token into send_cloud_command Enhance token management in cloud command handling Aug 26, 2024
    Copy link
    Contributor

    penify-dev bot commented Aug 26, 2024

    PR Review 🔍

    ⏱️ Estimated effort to review [1-5]

    4, because the changes involve significant modifications to token management and error handling, requiring careful review of both the logic and potential edge cases.

    🧪 Relevant tests

    No

    ⚡ Possible issues

    Possible Bug: The logic for checking token expiration may not account for clock skew between the client and server, which could lead to premature token refresh attempts.

    Possible Bug: The error handling in check_or_refresh_session may not cover all scenarios, such as network failures or unexpected response formats.

    🔒 Security concerns

    No

    Copy link
    Contributor

    penify-dev bot commented Aug 26, 2024

    PR Code Suggestions ✨

    CategorySuggestion                                                                                                                                    Score
    Possible issue
    Add validation for the response dictionary to prevent KeyErrors

    Ensure that the response_body_dict is validated before accessing its keys to avoid
    potential KeyErrors.

    pymammotion/aliyun/cloud_gateway.py [445]

    -if int(response_body_dict.get("code")) != 200:
    +if "code" not in response_body_dict or int(response_body_dict["code"]) != 200:
     
    Suggestion importance[1-10]: 9

    Why: The suggestion addresses a potential issue with KeyErrors, which is crucial for maintaining the robustness of the code.

    9
    Best practice
    Replace the generic exception with a more specific exception type for clarity

    Consider using a more specific exception type instead of the generic Exception for better
    error handling and debugging.

    pymammotion/aliyun/cloud_gateway.py [517]

    -raise Exception("Refresh token expired. Please re-login")
    +raise RuntimeError("Refresh token expired. Please re-login")
     
    Suggestion importance[1-10]: 8

    Why: This suggestion improves error handling by recommending a more specific exception type, which enhances clarity and debugging.

    8
    Maintainability
    Log the error message before raising the exception for improved debugging

    Consider logging the error message in the exception for better debugging information.

    pymammotion/aliyun/cloud_gateway.py [446]

    +logger.error("Error check or refresh token: " + response_body_dict.get('msg', ''))
     raise Exception("Error check or refresh token: " + response_body_dict.get('msg', ''))
     
    Suggestion importance[1-10]: 8

    Why: This suggestion enhances maintainability by recommending logging of error messages, which is beneficial for debugging.

    8
    Possible bug
    Adjust the token expiration check to avoid potential future timestamp issues

    Ensure that the token expiration check accounts for the possibility of the token being
    issued in the future, which could lead to incorrect behavior.

    pymammotion/aliyun/cloud_gateway.py [512]

    -if self._iot_token_issued_at + self._session_by_authcode_response.data.iotTokenExpire <= (int(time.time()) + (5 * 3600)):
    +if self._iot_token_issued_at + self._session_by_authcode_response.data.iotTokenExpire <= int(time.time()):
     
    Suggestion importance[1-10]: 7

    Why: The suggestion correctly identifies a potential issue with the token expiration check, but the proposed change may not fully consider the logic of the application.

    7

    mikey0000 added a commit that referenced this pull request Aug 27, 2024
    * start work on mowing
    
    * update mtrl nav
    
    * fix nav commands for none luba 1s
    
    * ruff format and so on
    
    * add product key to commands for checking device
    
    * fix blade on off
    
    * Try to implement MQTT response - Need helo on Lock
    
    * update protobufs with basestation
    
    * adding report info model and map conversions for lla enu
    
    * release 0.1.7
    
    * try to keep last data if its missing in report cfg
    
    * fix report info
    
    * Add missing calls for ble sync as well as hook up callbacks, remove dead code and general clean up, added test call to verify things work
    
    * format and run ruff
    
    * add cloud as part of base MammotionDevice
    
    * rename http class
    
    * fix up the client sesion for http
    
    * update login to login_info
    
    * bump version to 0.2.1
    
    * add start sync and sync maps calls to MammotionDevice
    
    * refactor mammotion to handle multiple devices and match to a name
    
    * update test examples
    
    * fix oops
    
    * fix quite a few errors and issues
    
    * stability improvements
    
    * fix more issues
    
    * adding movement commands
    
    * fix issue with device identification messing up sync maps
    
    * remove operation lock for mqtt
    
    * publish 0.2.7
    
    * Add check and refresh token into send_cloud_command (#56)
    
    Co-authored-by: Andrea Cagnola <[email protected]>
    Co-authored-by: Michael Arthur <[email protected]>
    
    * add methods for getting credentials for storing in HA when reloading or restarting without having to re-login
    
    * fix queuing of requests for mqtt, sync maps now works bump version to 0.2.9
    
    * don't create cloud or initiate cloud connection if there isn't credentials
    
    * bump version to 0.2.11 and catch small issue with futures queue being empty
    
    ---------
    
    Co-authored-by: Andrea Cagnola <[email protected]>
    Co-authored-by: d3dfantasy99 <[email protected]>
    Co-authored-by: Andrea Cagnola <[email protected]>
    mikey0000 added a commit that referenced this pull request Aug 27, 2024
    * start work on mowing
    
    * update mtrl nav
    
    * fix nav commands for none luba 1s
    
    * ruff format and so on
    
    * add product key to commands for checking device
    
    * fix blade on off
    
    * Try to implement MQTT response - Need helo on Lock
    
    * update protobufs with basestation
    
    * adding report info model and map conversions for lla enu
    
    * release 0.1.7
    
    * try to keep last data if its missing in report cfg
    
    * fix report info
    
    * Add missing calls for ble sync as well as hook up callbacks, remove dead code and general clean up, added test call to verify things work
    
    * format and run ruff
    
    * add cloud as part of base MammotionDevice
    
    * rename http class
    
    * fix up the client sesion for http
    
    * update login to login_info
    
    * bump version to 0.2.1
    
    * add start sync and sync maps calls to MammotionDevice
    
    * refactor mammotion to handle multiple devices and match to a name
    
    * update test examples
    
    * fix oops
    
    * fix quite a few errors and issues
    
    * stability improvements
    
    * fix more issues
    
    * adding movement commands
    
    * fix issue with device identification messing up sync maps
    
    * remove operation lock for mqtt
    
    * publish 0.2.7
    
    * Add check and refresh token into send_cloud_command (#56)
    
    Co-authored-by: Andrea Cagnola <[email protected]>
    Co-authored-by: Michael Arthur <[email protected]>
    
    * add methods for getting credentials for storing in HA when reloading or restarting without having to re-login
    
    * fix queuing of requests for mqtt, sync maps now works bump version to 0.2.9
    
    * don't create cloud or initiate cloud connection if there isn't credentials
    
    * bump version to 0.2.11 and catch small issue with futures queue being empty
    
    * fix issue with model having optional nickName
    
    ---------
    
    Co-authored-by: Andrea Cagnola <[email protected]>
    Co-authored-by: d3dfantasy99 <[email protected]>
    Co-authored-by: Andrea Cagnola <[email protected]>
    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
    Labels
    Projects
    None yet
    Development

    Successfully merging this pull request may close these issues.

    2 participants