2022-01-23 20:49:06 +01:00
|
|
|
import Vapor
|
|
|
|
|
2022-04-07 23:53:25 +02:00
|
|
|
var deviceManager: DeviceManager!
|
2022-01-24 17:17:06 +01:00
|
|
|
|
2022-05-01 13:12:16 +02:00
|
|
|
enum ServerError: Error {
|
|
|
|
case invalidAuthenticationFileContent
|
2022-05-01 13:28:06 +02:00
|
|
|
case invalidAuthenticationToken
|
2022-05-01 13:12:16 +02:00
|
|
|
}
|
|
|
|
|
2022-01-23 20:49:06 +01:00
|
|
|
// configures your application
|
|
|
|
public func configure(_ app: Application) throws {
|
2022-01-24 17:17:06 +01:00
|
|
|
let storageFolder = URL(fileURLWithPath: app.directory.resourcesDirectory)
|
2023-01-31 19:10:33 +01:00
|
|
|
let logFolder = storageFolder.appendingPathComponent("logs")
|
|
|
|
|
|
|
|
|
|
|
|
let configUrl = storageFolder.appendingPathComponent("config.json")
|
|
|
|
let config = try Config(loadFrom: configUrl)
|
|
|
|
|
|
|
|
app.http.server.configuration.port = config.port
|
|
|
|
|
|
|
|
let keyFile = storageFolder.appendingPathComponent(config.keyFileName)
|
|
|
|
|
|
|
|
let (deviceKey, remoteKey) = try loadKeys(at: keyFile)
|
|
|
|
deviceManager = DeviceManager(deviceKey: deviceKey, remoteKey: remoteKey, deviceTimeout: config.deviceTimeout)
|
|
|
|
try routes(app)
|
|
|
|
|
|
|
|
// Gracefully shut down by closing potentially open socket
|
|
|
|
DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + .seconds(5)) {
|
|
|
|
_ = app.server.onShutdown.always { _ in
|
|
|
|
deviceManager.removeDeviceConnection()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private func loadKeys(at url: URL) throws -> (deviceKey: Data, remoteKey: Data) {
|
|
|
|
let authContent: [Data] = try String(contentsOf: url)
|
2022-01-24 17:17:06 +01:00
|
|
|
.trimmingCharacters(in: .whitespacesAndNewlines)
|
2022-05-01 13:12:16 +02:00
|
|
|
.components(separatedBy: "\n")
|
|
|
|
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
|
2022-05-01 13:28:06 +02:00
|
|
|
.map {
|
|
|
|
guard let key = Data(fromHexEncodedString: $0) else {
|
|
|
|
throw ServerError.invalidAuthenticationToken
|
|
|
|
}
|
|
|
|
guard key.count == SHA256.byteCount else {
|
|
|
|
throw ServerError.invalidAuthenticationToken
|
|
|
|
}
|
|
|
|
return key
|
|
|
|
}
|
2022-05-01 13:12:16 +02:00
|
|
|
guard authContent.count == 2 else {
|
|
|
|
throw ServerError.invalidAuthenticationFileContent
|
|
|
|
}
|
2023-01-31 19:10:33 +01:00
|
|
|
return (deviceKey: authContent[0], remoteKey: authContent[1])
|
2022-01-23 20:49:06 +01:00
|
|
|
}
|