76 lines
2.4 KiB
Swift
76 lines
2.4 KiB
Swift
//
|
|
// KeychainMock.swift
|
|
//
|
|
//
|
|
// Created by NUT.TECH on 16.02.2023.
|
|
//
|
|
|
|
import Foundation
|
|
import WalletFoundation
|
|
|
|
final class KeychainMock: KeychainProtocol {
|
|
|
|
private enum KeychainMockLocals {
|
|
static let password = "PWD"
|
|
static let biometric = "BIO"
|
|
}
|
|
|
|
typealias Value = (value: String, password: String)
|
|
|
|
private var storage: [String: Value]
|
|
|
|
init(storage: [String: Value]? = nil) {
|
|
self.storage = storage ?? [:]
|
|
}
|
|
|
|
func exist(_ key: Key) -> Bool {
|
|
let commonKey = key.with(KeychainMockLocals.password)
|
|
return self.storage[commonKey.rawValue].isExist
|
|
}
|
|
|
|
func bioExist(_ key: Key) -> Bool {
|
|
let commonKey = key.with(KeychainMockLocals.biometric)
|
|
return self.storage[commonKey.rawValue] != nil
|
|
}
|
|
|
|
subscript(biometric key: Key) -> String? {
|
|
let commonKey = key.with(KeychainMockLocals.biometric).rawValue
|
|
let object = self.storage[commonKey]
|
|
return object?.value
|
|
}
|
|
|
|
subscript(key: Key, password password: String) -> String? {
|
|
get {
|
|
let commonKey = key.with(KeychainMockLocals.password).rawValue
|
|
let object = self.storage[commonKey]
|
|
return object?.password == password ? object?.value : nil
|
|
}
|
|
set {
|
|
self.update(key, password: password, newValue: newValue)
|
|
}
|
|
}
|
|
|
|
private func update(_ key: Key, password: String, newValue: String?) {
|
|
if let value = newValue {
|
|
self.updateStorage(key: key.with(KeychainMockLocals.password), password: password, value: value)
|
|
self.updateStorage(key: key.with(KeychainMockLocals.biometric), password: password, value: value)
|
|
} else {
|
|
self.updateStorage(key: key.with(KeychainMockLocals.password), password: password, value: nil)
|
|
self.updateStorage(key: key.with(KeychainMockLocals.biometric), password: password, value: nil)
|
|
}
|
|
}
|
|
|
|
private func updateStorage(key: Key, password: String, value: String?) {
|
|
let stringKey = key.rawValue
|
|
if self.storage[stringKey] != nil, self.storage[stringKey]?.password == password {
|
|
if let value {
|
|
self.storage[stringKey]?.value = value
|
|
} else {
|
|
self.storage.removeValue(forKey: stringKey)
|
|
}
|
|
} else if let value {
|
|
self.storage[stringKey] = Value(value: value, password: password)
|
|
}
|
|
}
|
|
}
|