Skip to content

Commit

Permalink
fix: Accomodate infinite refresh token
Browse files Browse the repository at this point in the history
  • Loading branch information
PhilippeWeidmann committed Jan 16, 2024
1 parent 52a17e2 commit dc0c526
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 10 deletions.
31 changes: 21 additions & 10 deletions Sources/InfomaniakCore/Account/KeychainHelper.swift
Original file line number Diff line number Diff line change
Expand Up @@ -113,19 +113,30 @@ public class KeychainHelper {

if let savedToken = getSavedToken(for: token.userId) {
keychainQueue.sync {
let queryUpdate: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: "\(token.userId)"
]

let attributes: [String: Any] = [
kSecValueData as String: tokenData
]

// Save token only if it's more recent
if savedToken.expirationDate <= token.expirationDate {
let queryUpdate: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: "\(token.userId)"
]

let attributes: [String: Any] = [
kSecValueData as String: tokenData
]
if let savedTokenExpirationDate = savedToken.expirationDate,
let newTokenExpirationDate = token.expirationDate,
savedTokenExpirationDate <= newTokenExpirationDate {
resultCode = SecItemUpdate(queryUpdate as CFDictionary, attributes as CFDictionary)
DDLogInfo("Successfully updated token ? \(resultCode == noErr)")
SentrySDK.addBreadcrumb(token.generateBreadcrumb(level: .info, message: "Successfully updated token"))
} else if savedToken.expirationDate == nil || token.expirationDate == nil {
// Or if one of them is now an infinite refresh token
resultCode = SecItemUpdate(queryUpdate as CFDictionary, attributes as CFDictionary)
DDLogInfo("Successfully updated unlimited token ? \(resultCode == noErr)")
SentrySDK.addBreadcrumb(token.generateBreadcrumb(
level: .info,
message: "Successfully updated unlimited token"
))
}
}
} else {
Expand Down Expand Up @@ -234,7 +245,7 @@ public extension ApiToken {
crumb.type = level == .info ? "info" : "error"
crumb.message = message
crumb.data = ["User id": userId,
"Expiration date": expirationDate.timeIntervalSince1970,
"Expiration date": expirationDate?.timeIntervalSince1970 ?? "infinite",
"Access Token": truncatedAccessToken,
"Refresh Token": truncatedRefreshToken,
"Keychain error code": keychainError]
Expand Down
3 changes: 3 additions & 0 deletions Sources/InfomaniakCore/Networking/ApiFetcher.swift
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,9 @@ open class OAuthAuthenticator: Authenticator {

extension ApiToken: AuthenticationCredential {
public var requiresRefresh: Bool {
guard let expirationDate else {
return false
}
return Date() > expirationDate
}
}
Expand Down

0 comments on commit dc0c526

Please sign in to comment.