Caps-Server/Sources/App/routes.swift

43 lines
1.2 KiB
Swift
Raw Normal View History

import Vapor
2020-05-19 15:19:19 +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 {
2022-06-11 00:20:43 +02:00
guard let key = request.headers.first(name: "key") else {
throw Abort(.badRequest)
}
2022-05-27 09:25:41 +02:00
guard server.hasAuthorization(for: key) else {
throw Abort(.forbidden)
}
}
2020-09-20 11:36:35 +02:00
func routes(_ app: Application) throws {
// Add or change a cap
app.postCatching("cap") { request in
2022-05-27 09:25:41 +02:00
try authorize(request)
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
}
let cap = try decoder.decode(Cap.self, from: buffer)
try server.addOrUpdate(cap)
2020-05-19 15:19:19 +02:00
}
// Upload an image
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)
try server.save(image: data, for: cap)
}
}