-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCHReactNativeGatekeeper.tsx
More file actions
327 lines (267 loc) · 7.13 KB
/
CHReactNativeGatekeeper.tsx
File metadata and controls
327 lines (267 loc) · 7.13 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
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
type CHResponse = {
status: number,
headers: Headers,
url: string,
text: string
}
type CHEvents = {
onWait: any,
onRedirect: any,
onRequestStart: any,
onRequestEnd: any,
navigation: any,
}
const API_REDIRECT_ENDPOINT = "https://api.crowdhandler.com/v1/redirect/requests/";
export default class CHReactNativeGatekeeper {
CH_KEY: string;
debug = false;
tokens = {};
events: CHEvents = {
onWait: () => { },
onRedirect: () => { },
onRequestStart: () => { },
onRequestEnd: () => { },
navigation: null,
};
screen_config: any;
timeout: number;
requestType: string;
constructor(config: { CH_KEY: string }, events: CHEvents, timeout: number, debug: boolean) {
this.CH_KEY = config.CH_KEY;
this.debug = debug || false;
this.timeout = timeout || 3000; // default timeout setting of 3 seconds
this.events = {
...this.events,
...events,
};
}
/**
* Sets the room config and starts the process of checking whether the
* user should be shown the Waiting Room screen or directed to the screen
* that is being protected
* @param config
* @returns Promise
*/
redirectOrWait(config: { slug: string, url: string }) {
if (!config.slug && !config.url) {
this.on({
type: 'onRedirect',
payload: {
screen_config: config,
navigation: this.events.navigation,
status: 200
},
});
} else {
this.requestType = 'slug';
if (config.url) {
this.requestType = 'url';
}
this.screen_config = config;
this.makeCrowdHandlerRequest();
}
}
/**
* Stores a reference to the navigation stack.
* This is passed as an argument from the onWait and onRedirect events
* allowing you to respond to these events
*
* @param navigation
*/
setNavigation = (navigation: any) => {
this.events.navigation = navigation;
}
async fetchWithTimeout(resource: string, options: RequestInit) {
try {
const controller = new AbortController();
const id = setTimeout(() => controller.abort(), this.timeout);
const response = await fetch(resource, {
...options,
signal: controller.signal
});
clearTimeout(id);
return response;
} catch (error) {
return error;
}
}
/**
*
* @param url
* @param config
* @returns Promise
*/
async request<CHResponse>(
url: string,
// `RequestInit` is a type for configuring
// a `fetch` request. By default, an empty object.
config: RequestInit = {}
// This function is async, it will return a Promise:
): Promise<CHResponse> {
// Inside, we call the `fetch` function with
// a URL and config given:
return this.fetchWithTimeout(url, config)
.then(async (response) => {
if (response.headers) {
return {
headers: response.headers,
status: response.status,
url: response.url,
} as CHResponse;
} else {
return {
headers: undefined,
status: 504,
url: undefined,
} as CHResponse;
}
})
}
buildRequestURL() : string {
let URL: string;
let saved_token :undefined;
let params: any = [ { name: 'ch-public-key', value: this.CH_KEY } ];
if (this.requestType === 'slug') {
params.push({ name: 'slug', value: this.screen_config.slug });
if (this.tokens[this.screen_config.slug]) {
saved_token = this.tokens[this.screen_config.slug];
}
} else {
params.push({ name: 'url', value: encodeURI(this.screen_config.url) });
if (this.tokens[encodeURI(this.screen_config.url)]) {
saved_token = this.tokens[encodeURI(this.screen_config.url)]
}
}
if (!saved_token){
URL = API_REDIRECT_ENDPOINT;
} else {
URL = `${API_REDIRECT_ENDPOINT}${saved_token}`;
}
URL = `${URL}?${params.map((param) => {
return `${param.name}=${param.value}`
}).join('&')}`
return URL;
}
/**
*
*/
async makeCrowdHandlerRequest() {
this.on({ type: 'onRequestStart' })
const URL : string = this.buildRequestURL();
try {
const response = await this.request<CHResponse>(URL, {
method: 'GET'
});
let token: any;
if (response && response.url) {
token = this.getToken(response.url);
}
if (token) {
this.saveToken((this.requestType === 'slug') ? this.screen_config.slug : encodeURI(this.screen_config.url), token);
}
if (response && response.status === 200) {
this.on({
type: 'onWait',
payload: {
screen_config: {
...this.screen_config,
uri: response.url + `&ch_mode=react-native`,
},
status: response.status,
navigation: this.events.navigation
}
})
} else {
this.on({
type: 'onRedirect',
payload: {
screen_config: this.screen_config,
navigation: this.events.navigation,
referer: 'crowdhandler_check',
status: response.status
}
});
}
this.on({ type: 'onRequestEnd' })
} catch (error) {
this.on({
type: 'onRedirect',
payload: {
screen_config: this.screen_config,
navigation: this.events.navigation,
referer: 'crowdhandler_check',
status: 502
}
});
this.on({ type: 'onRequestEnd' })
}
}
/**
*
* @param action
*/
on(action: { type: string, payload?: object }) {
if (this.events[action.type]) {
this.events[action.type](action.payload);
}
}
/**
*
* @param url
* @returns
*/
getToken(url: string): string {
let token = '';
try {
let params = url.split('?');
if (params[1]) {
let parts = params[1].split('&');
// extract the token
token = parts.reduce((token, key_value) => {
let key = key_value.split('=');
if (key[0] && key[0] === 'ch-id') {
token = key[1];
}
return token;
}, '');
}
} catch (error) {
console.log(error);
}
return token;
}
saveToken(key: string, token: string) {
this.tokens[key] = token;
}
handlePostMessage(message: string) {
let parts = message.split('=');
try {
let payload = JSON.parse(parts[1]);
switch (parts[0]) {
case 'saveToken':
if (this.requestType === 'slug') {
this.saveToken(payload.slug, payload.token)
}
if (this.requestType === 'url') {
this.saveToken(encodeURI(payload.requestURL), payload.token)
}
break;
case 'promoted':
this.on({
type: 'onRedirect',
payload: {
screen_config: this.screen_config,
navigation: this.events.navigation,
referer: 'waiting_room',
status: 200
}
});
break;
default:
break;
}
} catch (error) {
console.log(error);
}
}
}