Extract key importing logic and put it into separate class

This commit is contained in:
Danny Moesch 2019-06-29 23:09:24 +02:00 committed by Mingshen Sun
parent 47c9af0127
commit 7bee780b46
7 changed files with 148 additions and 36 deletions

View file

@ -6,7 +6,7 @@
// Copyright © 2017 Bob Sun. All rights reserved.
//
public enum AppError: Error {
public enum AppError: Error, Equatable {
case RepositoryNotSet
case RepositoryRemoteBranchNotFound(_: String)
case RepositoryBranchNotFound(_: String)

View file

@ -0,0 +1,40 @@
//
// KeyFileManager.swift
// passKit
//
// Created by Danny Moesch on 29.06.19.
// Copyright © 2019 Bob Sun. All rights reserved.
//
public class KeyFileManager {
public typealias KeyHandler = (Data, String) -> ()
public static let PublicPgp = KeyFileManager(keyType: PgpKeyType.PUBLIC)
public static let PrivatePgp = KeyFileManager(keyType: PgpKeyType.PRIVATE)
private let keyType: PgpKeyType
private let keyPath: String
private let keyHandler: KeyHandler
private convenience init(keyType: PgpKeyType) {
self.init(keyType: keyType, keyPath: keyType.getFileSharingPath())
}
public init(keyType: PgpKeyType, keyPath: String, keyHandler: @escaping KeyHandler = AppKeychain.add) {
self.keyType = keyType
self.keyPath = keyPath
self.keyHandler = keyHandler
}
public func importKeyAndDeleteFile() throws {
guard let keyFileContent = FileManager.default.contents(atPath: keyPath) else {
throw AppError.ReadingFile(URL(fileURLWithPath: keyPath).lastPathComponent)
}
keyHandler(keyFileContent, keyType.getKeychainKey())
try FileManager.default.removeItem(atPath: keyPath)
}
public func doesKeyFileExist() -> Bool {
return FileManager.default.fileExists(atPath: keyPath)
}
}

View file

@ -0,0 +1,30 @@
//
// PgpKeyType.swift
// passKit
//
// Created by Danny Moesch on 29.06.19.
// Copyright © 2019 Bob Sun. All rights reserved.
//
public enum PgpKeyType {
case PUBLIC
case PRIVATE
public func getKeychainKey() -> String {
switch self {
case .PUBLIC:
return "pgpPublicKey"
case .PRIVATE:
return "pgpPrivateKey"
}
}
func getFileSharingPath() -> String {
switch self {
case .PUBLIC:
return Globals.iTunesFileSharingPGPPublic
case .PRIVATE:
return Globals.iTunesFileSharingPGPPrivate
}
}
}