This repository has been archived on 2021-03-29. You can view files and clone it, but cannot push or open issues or pull requests.
statusboard/Sources/App/routes.swift
2020-11-15 01:43:27 -08:00

62 lines
2.6 KiB
Swift

import Vapor
import Foundation
import FoundationNetworking
import Crypto
import Leaf
func routes(_ app: Application) throws {
// Render home page when root domain is loaded
app.get { req -> EventLoopFuture<View> in
let fileData = try String(contentsOfFile: "\(app.directory.resourcesDirectory)/config.json").data(using: .utf8)
let config: Config = try! JSONDecoder().decode(Config.self, from: fileData!)
let loginStatus = req.session.data["loggedIn"] ?? "false"
let loginBool = loginStatus == "true" ? true : false
return req.view.render("home", LContext(config: config, loggedIn: loginBool))
}
app.get("status", ":url") { req -> [String: String] in
let url = URL(string: "http://\(req.parameters.get("url")!)")
var statusDict: [String:String] = [:]
var headReq = URLRequest(url: url!)
headReq.httpMethod = "HEAD"
let semaphore = DispatchSemaphore(value: 0)
URLSession.shared.dataTask(with: headReq, completionHandler: { (_, response, error) in
if let httpURLResponse = response as? HTTPURLResponse {
statusDict["code"] = String(httpURLResponse.statusCode)
statusDict["down"] = "false"
}
semaphore.signal()
}).resume()
semaphore.wait()
return statusDict.count > 0 ? statusDict : ["code": "0", "down": "true"]
}
app.get("login") { req -> EventLoopFuture<View> in
let fileData = try String(contentsOfFile: "\(app.directory.resourcesDirectory)/config.json").data(using: .utf8)
let config: Config = try! JSONDecoder().decode(Config.self, from: fileData!)
return req.view.render("login", LContext(config: config, loggedIn: false))
}
app.post("login") { req -> Response in
let data = try req.content.decode(Login.self)
let fileData = try String(contentsOfFile: "\(app.directory.resourcesDirectory)/config.json").data(using: .utf8)
let config: Config = try! JSONDecoder().decode(Config.self, from: fileData!)
let loginPassData = data.password?.data(using: .utf8)
let loginPassHash = SHA256.hash(data: loginPassData ?? "".data(using: .utf8)!)
let stringHash = loginPassHash.map { String(format: "%02hhx", $0) }.joined()
if stringHash == config.passwordHash {
req.session.data["loggedIn"] = "true"
return try req.redirect(to: "/")
} else {
throw Abort(.unauthorized)
}
}
app.get("logout") { req -> Response in
req.session.destroy()
return try req.redirect(to: "/")
}
}