/
ReCaptchaWebViewManager.swift
256 lines (212 loc) · 7.17 KB
/
ReCaptchaWebViewManager.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
//
// ReCaptchaWebViewManager.swift
// ReCaptcha
//
// Created by Flávio Caetano on 22/03/17.
// Copyright © 2018 ReCaptcha. All rights reserved.
//
import Foundation
import WebKit
/** Handles comunications with the webview containing the ReCaptcha challenge.
*/
internal class ReCaptchaWebViewManager {
enum JSCommand: String {
case execute = "execute();"
case reset = "reset();"
}
fileprivate struct Constants {
static let ExecuteJSCommand = "execute();"
static let ResetCommand = "reset();"
static let BotUserAgent = "Googlebot/2.1"
}
#if DEBUG
/// Forces the challenge to be explicitly displayed.
var forceVisibleChallenge = false {
didSet {
// Also works on iOS < 9
webView.performSelector(
onMainThread: "_setCustomUserAgent:",
with: forceVisibleChallenge ? Constants.BotUserAgent : nil,
waitUntilDone: true
)
}
}
/// Allows validation stubbing for testing
public var shouldSkipForTests = false
#endif
/// Sends the result message
var completion: ((ReCaptchaResult) -> Void)?
/// Notifies the JS bundle has finished loading
var onDidFinishLoading: (() -> Void)? {
didSet {
if didFinishLoading {
onDidFinishLoading?()
}
}
}
/// Configures the webview for display when required
var configureWebView: ((WKWebView) -> Void)?
/// The dispatch token used to ensure `configureWebView` is only called once.
var configureWebViewDispatchToken = UUID()
/// If the ReCaptcha should be reset when it errors
var shouldResetOnError = true
/// The JS message recoder
fileprivate var decoder: ReCaptchaDecoder!
/// Indicates if the script has already been loaded by the `webView`
fileprivate var didFinishLoading = false {
didSet {
if didFinishLoading {
onDidFinishLoading?()
}
}
}
/// The observer for `.UIWindowDidBecomeVisible`
fileprivate var observer: NSObjectProtocol?
/// The endpoint url being used
fileprivate var endpoint: String
/// The webview that executes JS code
lazy var webView: WKWebView = {
let webview = WKWebView(
frame: CGRect(x: 0, y: 0, width: 1, height: 1),
configuration: self.buildConfiguration()
)
webview.accessibilityIdentifier = "webview"
webview.accessibilityTraits = UIAccessibilityTraits.link
webview.isHidden = true
return webview
}()
/**
- parameters:
- html: The HTML string to be loaded onto the webview
- apiKey: The Google's ReCaptcha API Key
- baseURL: The URL configured with the API Key
- endpoint: The JS API endpoint to be loaded onto the HTML file.
*/
init(html: String, apiKey: String, baseURL: URL, endpoint: String) {
self.endpoint = endpoint
self.decoder = ReCaptchaDecoder { [weak self] result in
self?.handle(result: result)
}
let formattedHTML = String(format: html, arguments: ["apiKey": apiKey, "endpoint": endpoint])
if let window = UIApplication.shared.keyWindow {
setupWebview(on: window, html: formattedHTML, url: baseURL)
}
else {
observer = NotificationCenter.default.addObserver(
forName: UIWindow.didBecomeVisibleNotification,
object: nil,
queue: nil
) { [weak self] notification in
guard let window = notification.object as? UIWindow else { return }
self?.setupWebview(on: window, html: formattedHTML, url: baseURL)
}
}
}
/**
- parameter view: The view that should present the webview.
Starts the challenge validation
*/
func validate(on view: UIView) {
#if DEBUG
guard !shouldSkipForTests else {
completion?(.token(""))
return
}
#endif
webView.isHidden = false
view.addSubview(webView)
executeJS(command: .execute)
}
/// Stops the execution of the webview
func stop() {
webView.stopLoading()
}
/**
Resets the ReCaptcha.
The reset is achieved by calling `grecaptcha.reset()` on the JS API.
*/
func reset() {
configureWebViewDispatchToken = UUID()
executeJS(command: .reset)
didFinishLoading = false
}
}
// MARK: - Private Methods
/** Private methods for ReCaptchaWebViewManager
*/
fileprivate extension ReCaptchaWebViewManager {
/**
- returns: An instance of `WKWebViewConfiguration`
Creates a `WKWebViewConfiguration` to be added to the `WKWebView` instance.
*/
func buildConfiguration() -> WKWebViewConfiguration {
let controller = WKUserContentController()
controller.add(decoder, name: "recaptcha")
let conf = WKWebViewConfiguration()
conf.userContentController = controller
return conf
}
/**
- parameter result: A `ReCaptchaDecoder.Result` with the decoded message.
Handles the decoder results received from the webview
*/
func handle(result: ReCaptchaDecoder.Result) {
switch result {
case .token(let token):
completion?(.token(token))
case .error(let error):
if shouldResetOnError, let view = webView.superview {
reset()
validate(on: view)
}
else {
completion?(.error(error))
}
case .showReCaptcha:
DispatchQueue.once(token: configureWebViewDispatchToken) { [weak self] in
guard let `self` = self else { return }
self.configureWebView?(self.webView)
}
case .didLoad:
didFinishLoading = true
if completion != nil {
executeJS(command: .execute)
}
case .log(let message):
#if DEBUG
print("[JS LOG]:", message)
#endif
}
}
/**
- parameters:
- window: The window in which to add the webview
- html: The embedded HTML file
- url: The base URL given to the webview
Adds the webview to a valid UIView and loads the initial HTML file
*/
func setupWebview(on window: UIWindow, html: String, url: URL) {
window.addSubview(webView)
webView.loadHTMLString(html, baseURL: url)
if let observer = observer {
NotificationCenter.default.removeObserver(observer)
}
}
/**
- parameters:
- command: The JavaScript command to be executed
Executes the JS command that loads the ReCaptcha challenge. This method has no effect if the webview hasn't
finished loading.
*/
func executeJS(command: JSCommand) {
guard didFinishLoading else {
// Hasn't finished loading all the resources
return
}
webView.evaluateJavaScript(command.rawValue) { [weak self] _, error in
if let error = error {
self?.decoder.send(error: .unexpected(error))
}
}
}
}