Improve header access

This commit is contained in:
Christoph Hagen 2022-10-11 12:08:44 +02:00
parent b00f0826b9
commit 56b7fa1ba8
2 changed files with 45 additions and 5 deletions

View File

@ -0,0 +1,41 @@
import Foundation
import Vapor
enum HeaderKey: String {
case name
case password
case email
case token
}
extension Request {
/**
Get a header for a key, or abort with a `badRequest`.
*/
func header(_ key: HeaderKey) throws -> String {
guard let value = headers.first(name: key.rawValue) else {
throw Abort(.badRequest)
}
return value
}
func optionalHeader(_ key: HeaderKey) -> String? {
headers.first(name: key.rawValue)
}
/**
Get the password from the request header and hash it.
Possible error responses:
- `400`: No password header found
- `424`: Failed to hash the password
*/
func hashedPassword() throws -> String {
let password = try header(.password)
guard let hash = try? self.password.hash(password) else {
throw Abort(.failedDependency) // 424
}
return hash
}
}

View File

@ -60,9 +60,8 @@ func registerPlayer(_ app: Application) {
throw Abort(.notAcceptable) // 406
}
guard let hash = try? req.password.hash(password) else {
throw Abort(.failedDependency) // 424
}
let hash = try req.hashedPassword() // errors: 400, 424
// Can throw conflict (409)
return server.registerPlayer(named: name, hash: hash, in: req.db)
}