Skip to content

Instantly share code, notes, and snippets.

@jdmcd
Created April 29, 2018 14:35
Show Gist options
  • Save jdmcd/7bbddc649c63dad8a5545854bee45fe8 to your computer and use it in GitHub Desktop.
Save jdmcd/7bbddc649c63dad8a5545854bee45fe8 to your computer and use it in GitHub Desktop.
Vapor 3 helper for validating Google Recaptchas
import Foundation
import Vapor
struct GoogleCaptcha {
let client: Client
let secretKey: String
private let endpoint = "https://www.google.com/recaptcha/api/siteverify"
func validate(captchaResponse: String) throws -> Future<Bool> {
let requestData = GoogleCaptchaRequest(secret: secretKey, response: captchaResponse)
return client.post(endpoint, headers: [HTTPHeaderName.contentType.description: MediaType.urlEncodedForm.description], content: requestData).flatMap(to: GoogleCaptchaResponse.self) { response in
return try response.content.decode(GoogleCaptchaResponse.self)
}.map(to: Bool.self) { response in
return response.success ?? false
}
}
}
private struct GoogleCaptchaRequest: Content {
var secret: String
var response: String
}
private struct GoogleCaptchaResponse: Content {
var success: Bool?
}
private func contactForm(req: Request, contactForm: ContactRequest) throws -> Future<Response> {
let client = try req.make(Client.self)
return try GoogleCaptcha(client: client, secretKey: "MY-CAPTCHA-SECRET")
.validate(captchaResponse: "MY-CAPTCHA-RESPONSE-FROM-FORM")
.flatMap(to: Void.self) { success in
guard success else { throw Abort(.unauthorized) }
return .done(on: req)
}.flatMap(to: Response.self) { _ in
//do something else now that captcha is verified
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment