Created
April 29, 2018 14:35
-
-
Save jdmcd/7bbddc649c63dad8a5545854bee45fe8 to your computer and use it in GitHub Desktop.
Vapor 3 helper for validating Google Recaptchas
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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? | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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