SchwartzLizer / NimbleSurvey

MIT License
0 stars 0 forks source link

[Question] Automatic usage of refresh tokens with Timer #3

Closed suho closed 11 months ago

suho commented 11 months ago

Issue

Regarding automatic usage of refresh tokens, you are using Timer to call APIs every 2 hours, which leads to unnecessary API call (e.g., the access token is still expired, but the app still call refresh token API).

https://github.com/SchwartzLizer/NimbleSurvey/blob/ddfb80dcf8bc3a802aa6cc46158444bf75e38101/NimbleSurvey/NimbleSurvey/Router/TokenRefresher.swift#L23

Do we have another approach to optimize this?

SchwartzLizer commented 11 months ago

@suho I've updated the refreshToken() function in the token refresher. Now, when the login is successful, but the server response is missing or empty, an alert will be displayed. Upon selecting "OK", the timer will stop, the key will be removed, and the user will be directed back to the login screen.

On a successful service call, the timer will start, the token will be saved, and the refresherTokenOnSuccessAutoLogin notification will be triggered.

On a failed service call, the timer will stop, the key will be removed, and both refresherTokenOnFailureAutoLogin and refresherTokenOnFailure notifications will be triggered. The refresherTokenOnFailureAutoLogin is meant to run tasks on the login screen, whereas refresherTokenOnFailure will be executed in the notificationhandler class to display an alert and redirect the user back to the login screen when they are not already on it.

I have also set up setupNotificationObservers() to listen for appDidEnterBackground and appWillEnterForeground events. When the app enters the background, stopTimer() will be executed, and when the app comes to the foreground, refreshToken() will be called.

I'm going to take a test tomorrow. after I can login again.

suho commented 11 months ago

@SchwartzLizer I would prefer you to check ResponseInterceptor technique to implement the automatic usage of refresh tokens. For instance: https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#authenticationinterceptor

Feel free to check Alamofire, and raise any concerns 🙏