secretive/SecretKit/SecretStore.swift

55 lines
1.4 KiB
Swift
Raw Normal View History

2020-02-19 04:52:00 +00:00
import Combine
public protocol SecretStore: ObservableObject {
associatedtype SecretType: Secret
2020-03-04 07:14:38 +00:00
var name: String { get }
2020-02-19 04:52:00 +00:00
var secrets: [SecretType] { get }
2020-03-04 07:14:38 +00:00
func sign(data: Data, with secret: SecretType) throws -> Data
func delete(secret: SecretType) throws
}
extension NSNotification.Name {
static let secretStoreUpdated = NSNotification.Name("com.maxgoedjen.Secretive.secretStore.updated")
2020-02-19 04:52:00 +00:00
}
2020-03-07 23:04:36 +00:00
public class AnySecretStore: SecretStore {
2020-03-07 23:06:10 +00:00
fileprivate let base: Any
2020-03-07 23:04:36 +00:00
fileprivate let _name: () -> String
fileprivate let _secrets: () -> [AnySecret]
fileprivate let _sign: (Data, AnySecret) throws -> Data
fileprivate let _delete: (AnySecret) throws -> Void
public init<T>(_ secretStore: T) where T: SecretStore {
2020-03-07 23:06:10 +00:00
base = secretStore
2020-03-07 23:04:36 +00:00
_name = { secretStore.name }
_secrets = { secretStore.secrets.map { AnySecret($0) } }
_sign = { try secretStore.sign(data: $0, with: $1 as! T.SecretType) }
_delete = { try secretStore.delete(secret: $0 as! T.SecretType) }
}
public var name: String {
return _name()
}
public var secrets: [AnySecret] {
return _secrets()
}
public func sign(data: Data, with secret: AnySecret) throws -> Data {
try _sign(data, secret)
}
public func delete(secret: AnySecret) throws {
try _delete(secret)
}
}