Skip to content

Commit

Permalink
Merge pull request #242 from tangem/IOS-2779_add_logs
Browse files Browse the repository at this point in the history
  • Loading branch information
tureck1y authored Dec 27, 2022
2 parents 72b51b9 + 4bbf03c commit ad17fae
Show file tree
Hide file tree
Showing 9 changed files with 56 additions and 16 deletions.
17 changes: 14 additions & 3 deletions TangemSdk/TangemSdk/Common/Core/CardSession.swift
Original file line number Diff line number Diff line change
Expand Up @@ -339,17 +339,22 @@ public class CardSession {
private func prepareSession<T: CardSessionRunnable>(for runnable: T, completion: @escaping CompletionResult<Void>) {
Log.session("Prepare card session")
preflightReadMode = runnable.preflightReadMode

guard runnable.allowsAccessCodeFromRepository else {

Log.session("Current policy is \(environment.config.accessCodeRequestPolicy)")

guard runnable.shouldAskForAccessCode else {
Log.session("Skip an access codes request")
runnable.prepare(self, completion: completion)
return
}

let requestAccessCodeAction = {
Log.session("Request for an access code")
self.environment.accessCode = UserCode(.accessCode, value: nil)
self.requestUserCodeIfNeeded(.accessCode) { result in
switch result {
case .success:
Log.session("Continue the runnable")
runnable.prepare(self, completion: completion)
case .failure(let error):
completion(.failure(error))
Expand All @@ -360,10 +365,12 @@ public class CardSession {
switch environment.config.accessCodeRequestPolicy {
case .alwaysWithBiometrics:
if shouldRequestBiometrics {
Log.session("Request the biometric auth")
let reason = environment.config.biometricsLocalizedReason
accessCodeRepository?.unlock(localizedReason: reason) { result in
switch result {
case .success:
Log.session("Biometric auth completed successfully")
runnable.prepare(self, completion: completion)
case .failure:
requestAccessCodeAction()
Expand Down Expand Up @@ -510,15 +517,18 @@ public class CardSession {
}

func fetchAccessCodeIfNeeded() {
Log.session("Try fetch an access code")
guard let card = environment.card, card.isAccessCodeSet,
let accessCodeValue = accessCodeRepository?.fetch(for: card.cardId) else {
return
}


Log.session("The access code fetched successfully")
environment.accessCode = UserCode(.accessCode, value: accessCodeValue)
}

func saveAccessCodeIfNeeded() {
Log.session("Try save an access code")
guard let card = environment.card,
let code = environment.accessCode.value else {
return
Expand All @@ -527,6 +537,7 @@ public class CardSession {
do {
try accessCodeRepository?.save(code, for: card.cardId)
accessCodeRepository?.lock()
Log.session("The access code saved successfully")
} catch {
Log.error(error)
}
Expand Down
6 changes: 3 additions & 3 deletions TangemSdk/TangemSdk/Common/Core/CardSessionRunnable.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ public protocol CardSessionRunnable {
/// Mode for preflight read. Change this property only if you understand what to do
var preflightReadMode: PreflightReadMode { get }

/// Allows SDK to fetch access code from the local encrypted repository when running the command
var allowsAccessCodeFromRepository: Bool { get }
/// Allow SDK to fetch access code from the local encrypted repository when running the command
var shouldAskForAccessCode: Bool { get }

/// Simple interface for responses received after sending commands to Tangem cards.
associatedtype Response
Expand All @@ -37,7 +37,7 @@ public protocol CardSessionRunnable {
extension CardSessionRunnable {
public var preflightReadMode: PreflightReadMode { .fullCardRead }

public var allowsAccessCodeFromRepository: Bool { true }
public var shouldAskForAccessCode: Bool { true }

public func prepare(_ session: CardSession, completion: @escaping CompletionResult<Void>) {
completion(.success(()))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,53 +29,67 @@ public class AccessCodeRepository {
}

public func save(_ accessCode: Data, for cardIds: [String]) throws {
Log.debug("Save the access code for cardIds: \(cardIds)")
guard BiometricsUtil.isAvailable else {
throw TangemSdkError.biometricsUnavailable
}

guard updateCodesIfNeeded(with: accessCode, for: cardIds) else {
Log.debug("Skip saving")
return //Nothing changed. Return
}

var savedCardIds = getCards()

for cardId in cardIds {
Log.debug("Start saving the code for \(cardId)")
let storageKey = SecureStorageKey.accessCode(for: cardId)

if savedCardIds.contains(cardId) {
Log.debug("Try delete the code for \(cardId)")
try biometricsStorage.delete(storageKey)
}


Log.debug("Try save the code for \(cardId)")
try biometricsStorage.store(accessCode, forKey: storageKey)

savedCardIds.insert(cardId)
Log.debug("The code saved for \(cardId)")
}

saveCards(cardIds: savedCardIds)
Log.debug("The saving was completed successfully")
}

public func save(_ accessCode: Data, for cardId: String) throws {
Log.debug("Delete the access code for \(cardId)")
try save(accessCode, for: [cardId])
}

public func deleteAccessCode(for cardIds: [String]) throws {
Log.debug("Delete access codes for \(cardIds)")
if cardIds.isEmpty {
return
}

var savedCardIds = getCards()
for cardId in cardIds {
Log.debug("Delete the access code for \(cardId)")
guard savedCardIds.contains(cardId) else {
Log.debug("Skip \(cardId)")
continue
}

try biometricsStorage.delete(SecureStorageKey.accessCode(for: cardId))
savedCardIds.remove(cardId)
Log.debug("The access code for \(cardId) was deleted successfully")
}
saveCards(cardIds: savedCardIds)
Log.debug("The deletion was completed successfully")
}

public func clear() {
Log.debug("Clear AccessCodeRepository")
do {
let cardIds = getCards()
try deleteAccessCode(for: Array(cardIds))
Expand All @@ -86,7 +100,9 @@ public class AccessCodeRepository {

func contains(_ cardId: String) -> Bool {
let savedCards = getCards()
return savedCards.contains(cardId)
let contains = savedCards.contains(cardId)
Log.debug("Check if the repo contains the code for the \(cardId). Result: \(contains)")
return contains
}

func unlock(localizedReason: String, completion: @escaping (Result<Void, TangemSdkError>) -> Void) {
Expand All @@ -96,7 +112,8 @@ public class AccessCodeRepository {
}

self.accessCodes = [:]

Log.debug("Start unlocking with biometrics")

BiometricsUtil.requestAccess(localizedReason: localizedReason) { [weak self] result in
guard let self = self else { return }

Expand All @@ -105,12 +122,14 @@ public class AccessCodeRepository {
Log.error(error)
completion(.failure(error))
case .success(let context):
Log.debug("Storage was unlocked successfully")
do {
var fetchedAccessCodes: [String: Data] = [:]

for cardId in self.getCards() {
let accessCode = try self.biometricsStorage.get(SecureStorageKey.accessCode(for: cardId), context: context)
fetchedAccessCodes[cardId] = accessCode
Log.debug("The access code for cardId \(cardId) was fetched successfully")
}

self.accessCodes = fetchedAccessCodes
Expand All @@ -124,32 +143,40 @@ public class AccessCodeRepository {
}

func lock() {
Log.debug("Lock the access codes repo")
accessCodes = .init()
}

func fetch(for cardId: String) -> Data? {
return accessCodes[cardId]
let code = accessCodes[cardId]
Log.debug("Fetch the code for cardId: \(cardId). Result: \(code != nil)")
return code
}

private func updateCodesIfNeeded(with accessCode: Data, for cardIds: [String]) -> Bool {
var hasChanges: Bool = false

for cardId in cardIds {
Log.debug("Try update the access code for \(cardId)")
let existingCode = accessCodes[cardId]

if existingCode == accessCode {
Log.debug("We already know this code. Ignoring.")
continue //We already know this code. Ignoring
}

//We found default code
if accessCode == UserCodeType.accessCode.defaultValue.sha256() {
if existingCode == nil {
Log.debug("Ignore the default code")
continue //Ignore default code
} else {
accessCodes[cardId] = nil //User deleted the code. We should update the storage
Log.debug("User deleted the code. We should update the storage.")
accessCodes[cardId] = nil //User deleted the code. We should update the storage.
hasChanges = true
}
} else {
Log.debug("Save a new code")
accessCodes[cardId] = accessCode //Save a new code
hasChanges = true
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import Foundation

@available(iOS 13.0, *)
class FinalizeBackupCardTask: CardSessionRunnable {
var allowsAccessCodeFromRepository: Bool { false }
var shouldAskForAccessCode: Bool { false }

private let primaryCard: PrimaryCard
private let backupCards: [BackupCard]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import Foundation

@available(iOS 13.0, *)
class FinalizePrimaryCardTask: CardSessionRunnable {
var allowsAccessCodeFromRepository: Bool { false }
var shouldAskForAccessCode: Bool { false }

private let backupCards: [BackupCard]
private let accessCode: Data
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import Combine

@available(iOS 13.0, *)
final class StartBackupCardLinkingTask: CardSessionRunnable {
var allowsAccessCodeFromRepository: Bool { false }
var shouldAskForAccessCode: Bool { false }

private let primaryCard: PrimaryCard
private let addedBackupCards: [String]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import Combine

@available(iOS 13.0, *)
public class StartPrimaryCardLinkingTask: CardSessionRunnable {
public var allowsAccessCodeFromRepository: Bool { false }
public var shouldAskForAccessCode: Bool { false }

private var attestationTask: AttestationTask? = nil
private let onlineCardVerifier = OnlineCardVerifier()
Expand Down
2 changes: 1 addition & 1 deletion TangemSdk/TangemSdk/Operations/ScanTask.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import Foundation
/// Returns data from a Tangem card after successful completion of `ReadCommand` and `AttestWalletKeyCommand`, subsequently.
@available(iOS 13.0, *)
public final class ScanTask: CardSessionRunnable {
public var allowsAccessCodeFromRepository: Bool { false }
public var shouldAskForAccessCode: Bool { false }

private var attestationTask: AttestationTask? = nil

Expand Down
2 changes: 2 additions & 0 deletions TangemSdk/TangemSdk/TangemSdk.swift
Original file line number Diff line number Diff line change
Expand Up @@ -670,6 +670,8 @@ extension TangemSdk {
BiometricsUtil.isAvailable {
return AccessCodeRepository()
}

Log.debug("Failed to initialize AccessCodeRepository. Biometrics is unavailable.")

return nil
}
Expand Down

0 comments on commit ad17fae

Please sign in to comment.