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

44 lines
1.5 KiB
Swift
Executable File

import Vapor
var deviceManager: DeviceManager!
enum ServerError: Error {
case invalidAuthenticationFileContent
case invalidAuthenticationToken
}
// 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: [Data] = try String(contentsOf: keyFile)
.trimmingCharacters(in: .whitespacesAndNewlines)
.components(separatedBy: "\n")
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
.map {
guard let key = Data(fromHexEncodedString: $0) else {
throw ServerError.invalidAuthenticationToken
}
guard key.count == SHA256.byteCount else {
throw ServerError.invalidAuthenticationToken
}
return key
}
guard authContent.count == 2 else {
throw ServerError.invalidAuthenticationFileContent
}
let deviceKey = authContent[0]
let remoteKey = authContent[1]
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()
}
}
}