Sesame-Server/Sources/App/configure.swift
2022-05-01 13:12:16 +02:00

40 lines
1.4 KiB
Swift
Executable File

import Vapor
var deviceManager: DeviceManager!
enum ServerError: Error {
case invalidAuthenticationFileContent
case invalidRemoteAuthenticationToken
}
// configures your application
public func configure(_ app: Application) throws {
app.http.server.configuration.port = Config.port
let storageFolder = URL(fileURLWithPath: app.directory.resourcesDirectory)
let keyFile = storageFolder.appendingPathComponent(Config.keyFileName)
let authContent = try String(contentsOf: keyFile)
.trimmingCharacters(in: .whitespacesAndNewlines)
.components(separatedBy: "\n")
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
guard authContent.count == 2 else {
throw ServerError.invalidAuthenticationFileContent
}
let deviceKey = authContent[0]
guard let remoteKey = Data(fromHexEncodedString: authContent[1]) else {
throw ServerError.invalidRemoteAuthenticationToken
}
guard remoteKey.count == SHA256.byteCount else {
throw ServerError.invalidRemoteAuthenticationToken
}
deviceManager = DeviceManager(deviceKey: deviceKey, remoteKey: remoteKey)
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()
}
}
}