Serialize renewing the access token

This commit is contained in:
Maurice Parker 2020-05-07 02:33:43 -05:00
parent 48ceb655d6
commit 26041a067f
1 changed files with 18 additions and 5 deletions

View File

@ -48,6 +48,7 @@ public final class RedditFeedProvider: FeedProvider {
return oauthSwift?.client return oauthSwift?.client
} }
private var renewingAccessToken = false
private var rateLimitRemaining: Int? private var rateLimitRemaining: Int?
private var rateLimitReset: Date? private var rateLimitReset: Date?
@ -324,25 +325,37 @@ private extension RedditFeedProvider {
if case .tokenExpired = error { if case .tokenExpired = error {
os_log(.debug, log: self.log, "Access token expired, attempting to renew...") os_log(.debug, log: self.log, "Access token expired, attempting to renew...")
if renewingAccessToken {
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
completion(nil)
}
}
renewingAccessToken = true
oauthSwift?.renewAccessToken(withRefreshToken: oauthRefreshToken) { [weak self] result in oauthSwift?.renewAccessToken(withRefreshToken: oauthRefreshToken) { [weak self] result in
guard let self = self, let username = self.username else { guard let strongSelf = self, let username = strongSelf.username else {
self?.renewingAccessToken = false
completion(nil) completion(nil)
return return
} }
switch result { switch result {
case .success(let tokenSuccess): case .success(let tokenSuccess):
self.oauthToken = tokenSuccess.credential.oauthToken strongSelf.oauthToken = tokenSuccess.credential.oauthToken
self.oauthRefreshToken = tokenSuccess.credential.oauthRefreshToken strongSelf.oauthRefreshToken = tokenSuccess.credential.oauthRefreshToken
do { do {
try Self.storeCredentials(username: username, oauthToken: self.oauthToken, oauthRefreshToken: self.oauthRefreshToken) try Self.storeCredentials(username: username, oauthToken: strongSelf.oauthToken, oauthRefreshToken: strongSelf.oauthRefreshToken)
os_log(.debug, log: self.log, "Access token renewed.") os_log(.debug, log: strongSelf.log, "Access token renewed.")
} catch { } catch {
strongSelf.renewingAccessToken = false
completion(error) completion(error)
return return
} }
strongSelf.renewingAccessToken = false
completion(nil) completion(nil)
case .failure(let oathError): case .failure(let oathError):
strongSelf.renewingAccessToken = false
completion(oathError) completion(oathError)
} }
} }