2020-05-17 20:01:30 +02:00
|
|
|
import Vapor
|
2020-05-19 15:19:19 +02:00
|
|
|
|
2022-05-28 21:59:32 +02:00
|
|
|
/// The decoder to extract caps from JSON payloads given to the `cap` route.
|
|
|
|
private let decoder = JSONDecoder()
|
|
|
|
|
2022-05-27 09:25:41 +02:00
|
|
|
private func authorize(_ request: Request) throws {
|
|
|
|
let key = try request.query.get(String.self, at: "key")
|
|
|
|
guard server.hasAuthorization(for: key) else {
|
|
|
|
throw Abort(.forbidden)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-09-20 11:36:35 +02:00
|
|
|
func routes(_ app: Application) throws {
|
2022-05-28 21:59:32 +02:00
|
|
|
|
|
|
|
// Add or change a cap
|
|
|
|
app.postCatching("cap") { request in
|
2022-05-27 09:25:41 +02:00
|
|
|
try authorize(request)
|
2022-05-28 21:59:32 +02:00
|
|
|
guard let buffer = request.body.data else {
|
2020-09-20 11:36:35 +02:00
|
|
|
log("Invalid body data")
|
2020-05-19 15:19:19 +02:00
|
|
|
throw CapError.invalidBody
|
|
|
|
}
|
2022-05-28 21:59:32 +02:00
|
|
|
let cap = try decoder.decode(Cap.self, from: buffer)
|
|
|
|
try server.addOrUpdate(cap)
|
2020-05-19 15:19:19 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Upload an image
|
2022-05-28 21:59:32 +02:00
|
|
|
app.postCatching("images", ":n") { request in
|
2022-05-27 09:25:41 +02:00
|
|
|
try authorize(request)
|
2020-09-20 11:36:35 +02:00
|
|
|
guard let cap = request.parameters.get("n", as: Int.self) else {
|
|
|
|
log("Invalid parameter for cap")
|
|
|
|
throw Abort(.badRequest)
|
|
|
|
}
|
|
|
|
guard let buffer = request.body.data else {
|
|
|
|
log("Invalid body data")
|
2020-05-19 15:19:19 +02:00
|
|
|
throw CapError.invalidBody
|
|
|
|
}
|
2020-09-20 11:36:35 +02:00
|
|
|
let data = Data(buffer: buffer)
|
2022-05-28 21:59:32 +02:00
|
|
|
try server.save(image: data, for: cap)
|
2020-05-17 20:01:30 +02:00
|
|
|
}
|
|
|
|
}
|