-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathApp.js
388 lines (368 loc) · 10.3 KB
/
App.js
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
import React, {useState, useEffect} from 'react';
import {NavigationContainer} from '@react-navigation/native';
import {createStackNavigator} from '@react-navigation/stack';
import AsyncStorage from '@react-native-async-storage/async-storage';
import HttpAgent from './httpAgent';
import {
NativeFunction,
getSDKEventEmitter,
MobileSDKEvent,
MeetingError,
} from './utils/Bridge';
// import CurrentRoomScreen from './screens/CurrentRoomScreen';
import {
SafeAreaView,
StyleSheet,
ScrollView,
View,
Text,
TextInput,
Button,
StatusBar,
PermissionsAndroid,
Alert,
} from 'react-native';
const {Navigator: RootNavigator, Screen: RootScreen} = createStackNavigator();
const {Navigator: MainNavigator, Screen: MainScreen} = createStackNavigator();
const HomeScreen = ({navigation, authUser}) => {
const [isInRoom, setIsInRoom] = useState(false);
useEffect(() => {
this.onMeetingStartSubscription = getSDKEventEmitter().addListener(
MobileSDKEvent.OnMeetingStart,
() => {
setIsInRoom(true);
},
);
this.onMeetingEndSubscription = getSDKEventEmitter().addListener(
MobileSDKEvent.OnMeetingEnd,
() => {
setIsInRoom(false);
},
);
this.onErrorSubscription = getSDKEventEmitter().addListener(
MobileSDKEvent.OnError,
(message) => {
Alert.alert('SDK Error', message);
},
);
}, []);
function createAndJoinMeeting() {
const httpAgent = new HttpAgent('http://22428beafa99.ngrok.io/api');
httpAgent
._post('/spaces', {
title: 'testing space',
})
.then((res) => {
console.log('meeting data', res);
return NativeFunction.startMeeting(
res.joinInfo.meeting,
res.joinInfo.attendee,
);
})
.catch((error) => {
console.log(
'there was an error while creating and joining the room in',
{error},
);
});
}
return (
<View>
<Text>Hello, {authUser ? `@${authUser.user.username}` : ''} </Text>
{!isInRoom ? (
<Button onPress={createAndJoinMeeting} title="Start a room" />
) : null}
<Button
onPress={() => navigation.navigate('testScreen')}
title="open screen">
Test screen
</Button>
<Button
onPress={() => navigation.navigate('roomModal')}
title="open modal">
Open room
</Button>
</View>
);
};
const TestScreen = ({navigation}) => {
return (
<View>
<Text>Test Screen</Text>
<Button
onPress={() => navigation.navigate('roomModal')}
title="open modal">
Go to modal
</Button>
</View>
);
};
const SignInScreen = ({navigation, updateAuth}) => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
function attemptLogin() {
const httpAgent = new HttpAgent('http://22428beafa99.ngrok.io/api');
httpAgent
._post('/users/login', {
email,
password,
})
.then((res) => {
if (res.success) {
updateAuth(true);
}
})
.catch((error) => {
console.log('there was an error while logging in', {error});
});
}
return (
<View>
<Text>Sign In</Text>
<TextInput
placeholder="email"
onChangeText={(text) => setEmail(text)}
value={email}
/>
<TextInput
placeholder="password"
secureTextEntry
onChangeText={(text) => setPassword(text)}
value={password}
/>
<Button title="Login" onPress={attemptLogin} />
<Text>or</Text>
<Button
title="Create a new Space account"
onPress={() => navigation.navigate('registerScreen')}
/>
</View>
);
};
const RegisterScreen = ({updateAuth}) => {
const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [username, setUsername] = useState('');
function handleRegister() {
const httpAgent = new HttpAgent('http://22428beafa99.ngrok.io/api');
httpAgent
._post('/users', {
email,
password,
username,
firstName,
lastName,
})
.then((res) => {
if (res.success) {
updateAuth(true);
}
})
.catch((error) => {
console.log('there was an error while logging in', {error});
});
}
return (
<View>
<Text>Sign In</Text>
<TextInput
placeholder="first name"
onChangeText={(text) => setFirstName(text)}
value={firstName}
/>
<TextInput
placeholder="last name"
onChangeText={(text) => setLastName(text)}
value={lastName}
/>
<TextInput
placeholder="email"
onChangeText={(text) => setEmail(text)}
value={email}
/>
<TextInput
placeholder="unique username"
onChangeText={(text) => setUsername(text)}
value={username}
/>
<TextInput
placeholder="password"
secureTextEntry
onChangeText={(text) => setPassword(text)}
value={password}
/>
<Button title="Register" onPress={handleRegister} />
</View>
);
};
const MainStack = ({isAuth, updateAuth, logout, authUser}) => {
console.log('the isAuth state is', isAuth);
return (
<MainNavigator
initialRouteName="HomeScreen"
mode="card"
screenOptions={() => {
if (!isAuth) {
return;
}
return {
headerRight() {
return <Button title="Log out" onPress={logout} />;
},
};
}}>
{isAuth ? (
<>
<MainScreen name="homeScreen">
{(props) => (
<HomeScreen {...props} logout={logout} authUser={authUser} />
)}
</MainScreen>
<MainScreen name="testScreen" component={TestScreen} />
</>
) : (
<>
<MainScreen name="signInScreen">
{(props) => <SignInScreen {...props} updateAuth={updateAuth} />}
</MainScreen>
<MainScreen name="registerScreen">
{(props) => <RegisterScreen {...props} updateAuth={updateAuth} />}
</MainScreen>
</>
)}
</MainNavigator>
);
};
const CurrentRoomScreen = ({navigation}) => {
return (
<View>
<Text>Current Room Screen modal</Text>
<Button
onPress={() => navigation.goBack()}
title="go back to other rooms"
/>
<Button
onPress={() => navigation.navigate('testScreen')}
title="open test screen"
/>
<Button
onPress={() => navigation.navigate('roomModal')}
title="open modal"
/>
</View>
);
};
const App = () => {
// get persisted isAuth value from storage, and set global isAuth state for app
// let this dictate showing the proper stack
// if isAuth is false, or that isn't any isAuth state persisted, the logged out screens
// will show
// if isAuth is true then the logged in screens will show, and any authenticated request from there
// will attempt to use the persisted JWT token, if any unauthorized error is returned then the JWT
// key will be cleared and isAuth modified in the app state, and in the persisted storage
// The http agent wrapping Axios will handle fetching the JWT from the storage and including it in the
// the request
const [isLoading, setLoading] = useState(true);
const [authUser, setAuthUser] = useState(null);
const [isAuth, setIsAuth] = useState(null);
function updateAuth(_isAuth) {
return AsyncStorage.setItem('@isAuth', `${_isAuth}`).then(() => {
setIsAuth(_isAuth);
});
}
function logout() {
// make request to invalidate JWT
// lacking valid authentication credentials for the target resource
HttpAgent.setToken('@secureJwt', '')
.then(() => {
updateAuth(false);
setAuthUser(null);
})
.catch(() => {
console.log('error while resetting JWT');
});
}
useEffect(() => {
const grants = PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.RECORD_AUDIO,
);
AsyncStorage.getItem('@isAuth')
.then((persistedIsAuth) => {
// console.log('the persisted auth is', {persistedIsAuth});
updateAuth(JSON.parse(persistedIsAuth)).finally(() => {
setLoading(false);
});
})
.catch((error) => {
updateAuth(false).finally(() => {
setLoading(false);
});
});
}, []);
// on isAuth changes, we check if a user is authenticated then attempt to fetch the user's data
useEffect(() => {
const httpAgent = new HttpAgent('http://22428beafa99.ngrok.io/api');
if (isAuth) {
httpAgent
._get('/users')
.then((user) => {
console.log('response', user);
setAuthUser(user);
})
.catch((error) => {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
if (error.response.status === 401) {
// lacking valid authentication credentials for the target resource
logout();
}
// console.log(error.response.data);
// console.log(error.response.status);
// console.log(error.response.headers);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log('error', {...error});
});
}
}, [isAuth]);
if (isLoading) {
return (
<View>
<Text>Loading</Text>
</View>
);
}
return (
<NavigationContainer>
<RootNavigator mode="modal">
<RootScreen name="mainStack" options={{headerShown: false}}>
{(props) => (
<MainStack
{...props}
isAuth={isAuth}
updateAuth={updateAuth}
logout={logout}
authUser={authUser}
/>
)}
</RootScreen>
<RootScreen name="roomModal" component={CurrentRoomScreen} />
</RootNavigator>
</NavigationContainer>
);
};
const styles = StyleSheet.create({
footer: {
fontSize: 12,
fontWeight: '600',
padding: 4,
paddingRight: 12,
textAlign: 'right',
},
});
export default App;