forked from hCaptcha/react-native-hcaptcha
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHcaptcha.js
More file actions
193 lines (183 loc) · 6.19 KB
/
Copy pathHcaptcha.js
File metadata and controls
193 lines (183 loc) · 6.19 KB
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
import React, { useMemo, useCallback } from 'react';
import WebView from 'react-native-webview';
import { Linking, StyleSheet, View, ActivityIndicator } from 'react-native';
const patchPostMessageJsCode = `(${String(function () {
var originalPostMessage = window.ReactNativeWebView.postMessage;
var patchedPostMessage = function (message, targetOrigin, transfer) {
originalPostMessage(message, targetOrigin, transfer);
};
patchedPostMessage.toString = function () {
return String(Object.hasOwnProperty).replace(
'hasOwnProperty',
'postMessage'
);
};
window.ReactNativeWebView.postMessage = patchedPostMessage;
})})();`;
const buildHcaptchaApiUrl = (siteKey, languageCode, theme) => {
var url = 'https://hcaptcha.com/1/api.js?render=explicit&onload=onloadCallback';
url += `&host=${siteKey || 'missing-sitekey'}.react-native.hcaptcha.com`;
if (languageCode) {
url += '&hl=' + languageCode;
}
if (typeof theme === 'object') {
url += '&custom=true';
}
return url;
};
/**
*
* @param {*} onMessage: callback after receiving response, error, or when user cancels
* @param {*} siteKey: your hCaptcha sitekey
* @param {*} style: custom style
* @param {*} url: base url
* @param {*} languageCode: can be found at https://docs.hcaptcha.com/languages
* @param {*} cancelButtonText: title of cancel button
* @param {*} showLoading: loading indicator for webview till hCaptcha web content loads
* @param {*} loadingIndicatorColor: color for the ActivityIndicator
* @param {*} backgroundColor: backgroundColor which can be injected into HTML to alter css backdrop colour
* @param {*} theme: can be 'light', 'dark', 'contrast' or custom theme object
* @param {*} rqdata: see Enterprise docs
*/
const Hcaptcha = ({
onMessage,
siteKey,
style,
url,
languageCode,
cancelButtonText = 'Cancel',
showLoading,
loadingIndicatorColor,
backgroundColor,
theme,
rqdata,
}) => {
const apiUrl = buildHcaptchaApiUrl(siteKey, languageCode, theme);
if (theme && typeof theme === 'string') {
theme = `"${theme}"`;
}
if (rqdata && typeof rqdata === 'string') {
rqdata = `"${rqdata}"`;
}
const generateTheWebViewContent = useMemo(
() =>
`<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="${apiUrl}" async defer></script>
<script type="text/javascript">
var onloadCallback = function() {
try {
console.log("challenge onload starting");
hcaptcha.render("submit", getRenderConfig("${siteKey || ''}", ${theme}));
// have loaded by this point; render is sync.
console.log("challenge render complete");
} catch (e) {
console.log("challenge failed to render");
window.ReactNativeWebView.postMessage("error");
}
try {
console.log("showing challenge");
hcaptcha.execute(getExecuteOpts());
} catch (e) {
console.log("failed to show challenge");
window.ReactNativeWebView.postMessage("error");
}
};
var onDataCallback = function(response) {
window.ReactNativeWebView.postMessage(response);
};
var onCancel = function() {
window.ReactNativeWebView.postMessage("cancel");
};
var onOpen = function() {
// NOTE: disabled for simplicity.
// window.ReactNativeWebView.postMessage("open");
console.log("challenge opened");
};
var onDataExpiredCallback = function(error) { window.ReactNativeWebView.postMessage("expired"); };
var onChalExpiredCallback = function(error) { window.ReactNativeWebView.postMessage("cancel"); };
var onDataErrorCallback = function(error) {
console.log("challenge error callback fired");
window.ReactNativeWebView.postMessage("error");
};
const getRenderConfig = function(siteKey, theme) {
var config = {
sitekey: siteKey,
size: "invisible",
callback: onDataCallback,
"close-callback": onCancel,
"open-callback": onOpen,
"expired-callback": onDataExpiredCallback,
"chalexpired-callback": onChalExpiredCallback,
"error-callback": onDataErrorCallback
};
if (theme) {
config.theme = theme;
}
return config;
};
const getExecuteOpts = function() {
var opts;
const rqdata = ${rqdata};
if (rqdata) {
opts = {"rqdata": rqdata};
}
return opts;
};
</script>
</head>
<body style="background-color: ${backgroundColor};">
<div id="submit"></div>
</body>
</html>`,
[siteKey, backgroundColor, theme]
);
// This shows ActivityIndicator till webview loads hCaptcha images
const renderLoading = useCallback(
() => (
<View style={[styles.loadingOverlay]}>
<ActivityIndicator size="large" color={loadingIndicatorColor} />
</View>
),
[loadingIndicatorColor]
);
return (
<WebView
originWhitelist={['*']}
onShouldStartLoadWithRequest={(event) => {
if (event.url.slice(0, 24) === 'https://www.hcaptcha.com') {
Linking.openURL(event.url);
return false;
}
return true;
}}
mixedContentMode={'always'}
onMessage={onMessage}
javaScriptEnabled
injectedJavaScript={patchPostMessageJsCode}
automaticallyAdjustContentInsets
style={[{ backgroundColor: 'transparent', width: '100%' }, style]}
source={{
html: generateTheWebViewContent,
baseUrl: `${url}`,
}}
renderLoading={renderLoading}
startInLoadingState={showLoading}
/>
);
};
const styles = StyleSheet.create({
loadingOverlay: {
bottom: 0,
justifyContent: 'center',
left: 0,
position: 'absolute',
right: 0,
top: 0,
},
});
export default Hcaptcha;