Skip to content

Commit

Permalink
Merge pull request #52 from tidal-music/fix-get-latest-tokens-crash
Browse files Browse the repository at this point in the history
Fix Credentials related crashes
  • Loading branch information
e-kononenko authored Aug 2, 2024
2 parents c187da6 + a43eff2 commit b20ff37
Showing 1 changed file with 22 additions and 8 deletions.
30 changes: 22 additions & 8 deletions Sources/Auth/Storage/DefaultTokensStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ final class DefaultTokensStore: TokensStore {

private var latestTokens: Tokens?

private let credentialsQueue = DispatchQueue(label: "com.tidal.auth.credentialsQueue")

init(credentialsKey: String, credentialsAccessGroup: String?) {
storageKey = "\(credentialsKey)_\(PREFS_FILE_NAME)"
self.credentialsKey = credentialsKey
Expand All @@ -20,8 +22,12 @@ final class DefaultTokensStore: TokensStore {
}

func getLatestTokens() throws -> Tokens? {
latestTokens = try latestTokens ?? loadTokens()
return latestTokens
try credentialsQueue.sync {
if latestTokens == nil {
latestTokens = try loadTokens()
}
return latestTokens
}
}

private func loadTokens() throws -> Tokens? {
Expand All @@ -38,7 +44,7 @@ final class DefaultTokensStore: TokensStore {
// try to decode legacy tokens, convert them to tokens and save tokens
print("Failed to decode tokens. Attempting to decode legacy tokens")
if let convertedLegacyTokens = try? decoder.decode(LegacyTokens.self, from: data).toTokens() {
try saveTokens(tokens: convertedLegacyTokens)
try saveTokensUnsafe(tokens: convertedLegacyTokens)
return convertedLegacyTokens
} else {
throw error
Expand All @@ -48,14 +54,22 @@ final class DefaultTokensStore: TokensStore {
}

func saveTokens(tokens: Tokens) throws {
try credentialsQueue.sync {
try saveTokensUnsafe(tokens: tokens)
}
}

func eraseTokens() throws {
try credentialsQueue.sync {
latestTokens = nil
try encryptedStorage.removeAll()
}
}

private func saveTokensUnsafe(tokens: Tokens) throws {
let data = try JSONEncoder().encode(tokens)
encryptedStorage[credentialsKey] = String(data: data, encoding: .utf8)
latestTokens = tokens
// TODO: emit credentails update: `bus.emit(CredentialsUpdatedMessage)`
}

func eraseTokens() throws {
latestTokens = nil
try encryptedStorage.removeAll()
}
}

0 comments on commit b20ff37

Please sign in to comment.