-
Notifications
You must be signed in to change notification settings - Fork 0
/
App.js
324 lines (295 loc) · 13.4 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
import React, {useEffect, useState} from 'react';
import Constants from 'expo-constants';
import {NavigationContainer} from '@react-navigation/native';
import {createStackNavigator} from '@react-navigation/stack';
import {createBottomTabNavigator} from '@react-navigation/bottom-tabs';
import * as Notifications from 'expo-notifications';
import Ionicons from 'react-native-vector-icons/Ionicons';
import AsyncStorage from '@react-native-async-storage/async-storage';
import {Alert, SafeAreaView} from "react-native";
import {Platform, StatusBar, StyleSheet} from 'react-native';
import * as CryptoES from "crypto-es";
import AuthContext from './components/AuthContext.js';
import Bills from './Pages/Bills.js';
import BillDetails from './Pages/BillDetails.js';
import MpProfile from './Pages/MpProfile.js';
import Preferences from './Pages/Preferences.js';
import Login from "./Pages/Login";
import Signup from "./Pages/Signup";
import MpMessage from './Pages/MpMessage';
export default function App() {
const [expoPushToken, setExpoPushToken] = useState("ExpoToken[XXXXXXXX]");
const [state, dispatch] = React.useReducer(
(prevState, action) => {
switch (action.type) {
case 'RESTORE_TOKEN':
return {
...prevState,
userAuthenticationToken: action.token,
email: action.email,
isLoading: false,
};
case 'SIGN_IN':
return {
...prevState,
isSignout: false,
userAuthenticationToken: action.token,
email: action.email,
};
case 'SIGN_OUT':
return {
...prevState,
isSignout: true,
storedTokenInvalid: true,
userAuthenticationToken: null,
email: null,
};
case 'POSTCODE_UPDATE':
return {
...prevState,
postcodeUpdated: true,
};
case 'POSTCODE_UPDATE_CONFIRM':
return {
...prevState,
postcodeUpdated: false,
}
}
},
{
isLoading: true,
isSignout: true,
storedTokenInvalid: false,
userAuthenticationToken: null,
email: "",
postcodeUpdated: false,
},
);
useEffect(() => {
registerForPushNotificationsAsync().then(token => {
setExpoPushToken(token)
});
if (state.isSignout && !state.storedTokenInvalid) {
authContext.signInWithToken()
}
}, []);
const authContext = React.useMemo(
() => ({
signIn: async data => {
console.log(data)
const salt = CryptoES.default.enc.Base64.parse('insightsalt');
const hashedPasswordWords = CryptoES.default.PBKDF2(data.password, salt, { keySize: 128/32 });
const hashedPassword = CryptoES.default.enc.Base64.stringify(hashedPasswordWords);
const formdata = new FormData();
formdata.append("email", data.emailAddress)
formdata.append("password", hashedPassword)
fetch('https://bills-app-305000.ew.r.appspot.com/login', {
method: 'POST',
body: formdata
})
.then((res) => res.json())
.then((result) => {
if ("session_token" in result) {
console.log(result["session_token"])
AsyncStorage.setItem('email', data.emailAddress)
AsyncStorage.setItem('userAuthenticationToken', result["session_token"])
dispatch({type: 'SIGN_IN', token: result["session_token"], email: data.emailAddress});
} else {
console.log(result["error"])
let errorMessage = "Error"
if (result["error"] === "new_email_error") {
errorMessage = "No account exists for this email"
}
Alert.alert(
"Error",
errorMessage,
[
{ text: "OK", onPress: () => console.log("OK Pressed") }
],
{ cancelable: false }
);
}
});
},
signInWithToken: async data => {
const formdata = new FormData();
const email = await AsyncStorage.getItem('email')
const token = await AsyncStorage.getItem('userAuthenticationToken')
formdata.append("email", email)
formdata.append("session_token", token)
fetch('https://bills-app-305000.ew.r.appspot.com/login_with_token', {
method: 'POST',
body: formdata
})
.then((res) => res.json())
.then((result) => {
if (result["success"] === "login_successful") {
dispatch({type: 'SIGN_IN', token: token, email: email});
} else {
AsyncStorage.setItem('userAuthenticationToken', null)
dispatch({type: 'SIGN_OUT'})
}
});
},
signOut: () => {
AsyncStorage.setItem('userAuthenticationToken', null)
dispatch({type: 'SIGN_OUT'})
},
signUp: async data => {
const salt = CryptoES.default.enc.Base64.parse('insightsalt');
const hashedPasswordWords = CryptoES.default.PBKDF2(data.password, salt, { keySize: 128/32 });
const hashedPassword = CryptoES.default.enc.Base64.stringify(hashedPasswordWords);
const formdata = new FormData();
formdata.append("email", data.emailAddress)
formdata.append("password", hashedPassword)
formdata.append("notification_token", expoPushToken)
formdata.append("postcode", data.postcode)
fetch('https://bills-app-305000.ew.r.appspot.com/register', {
method: 'POST',
body: formdata
})
.then((res) => res.json())
.then((result) => {
if ("session_token" in result) {
console.log(result["session_token"])
AsyncStorage.setItem('email', data.emailAddress)
AsyncStorage.setItem('userAuthenticationToken', result["session_token"])
dispatch({type: 'SIGN_IN', token: result["session_token"], email: data.emailAddress});
} else {
let errorMessage = "Error"
if (result["error"] === "password_error") {
errorMessage = "Invalid password"
} else if (result["error"] === "notification_token_error") {
errorMessage = "There was an issue fetching your notification token. Please allow notifications for Insight/Expo Go. You may need to restart the app after doing so."
} else if (result["error"] === "postcode_error") {
errorMessage = "Invalid postcode"
} else if (result["error"] === "email_error") {
errorMessage = "Invalid email"
} else if (result["error"] === "email_in_use_error") {
errorMessage = "That email is already in use"
}
Alert.alert(
"Error",
errorMessage,
[
{ text: "OK", onPress: () => console.log("OK Pressed") }
],
{ cancelable: false }
);
console.log(result["error"])
}
});
},
postcodeUpdate: async data => {
dispatch({type: 'POSTCODE_UPDATE'})
},
postcodeUpdateConfirm: async data => {
dispatch({type: 'POSTCODE_UPDATE_CONFIRM'})
},
userAuthenticationToken: state.userAuthenticationToken,
email: state.email,
postcodeUpdated: state.postcodeUpdated,
}),
[state.userAuthenticationToken, state.email, state.postcodeUpdated]
);
const Tab = createBottomTabNavigator();
const Stack = createStackNavigator();
function BillsStack() {
return (
<Stack.Navigator>
<Stack.Screen name="Bill Feed" component={Bills}/>
<Stack.Screen name="Bill Details" component={BillDetails}/>
</Stack.Navigator>
);
}
function MpProfileStack() {
return (
<Stack.Navigator>
<Stack.Screen name="MP Information" component={MpProfile}/>
<Stack.Screen name="MP Message" component={MpMessage}/>
</Stack.Navigator>
);
}
function PreferencesStack() {
return (
<Stack.Navigator>
<Stack.Screen name="Preferences" component={Preferences}/>
</Stack.Navigator>
);
}
return (
<AuthContext.Provider value={authContext}>
<NavigationContainer>
{(state.userAuthenticationToken !== "null" && state.userAuthenticationToken !== null) ? (
<SafeAreaView style={paddingStyles.padding}>
<Tab.Navigator screenOptions={({route}) => ({
tabBarIcon: ({focused, color, size}) => {
let icon;
if (route.name === 'Bill Feed') {
icon = focused ? 'layers' : 'layers-outline';
} else if (route.name === 'MP Information') {
icon = focused ? 'person' : 'person-outline';
} else if (route.name === 'Preferences')
icon = focused ? 'ellipsis-horizontal' : 'ellipsis-horizontal-outline';
return <Ionicons name={icon} size={size} color={color}/>;
},
})}>
<Tab.Screen name="Bill Feed" component={BillsStack} options={{title: ''}}/>
<Tab.Screen name="MP Information" component={MpProfileStack} options={{title: ''}}/>
<Tab.Screen name="Preferences" component={PreferencesStack} options={{title: ''}}/>
</Tab.Navigator>
</SafeAreaView>
) : (
<SafeAreaView style={paddingStyles.noPadding}>
<Stack.Navigator>
<Stack.Screen name={"Login"} component={Login}/>
<Stack.Screen name={"Signup"} component={Signup}/>
</Stack.Navigator>
</SafeAreaView>
)}
</NavigationContainer>
</AuthContext.Provider>
);
}
const registerForPushNotificationsAsync = async () => {
if (Constants.isDevice) {
const {status: existingStatus} = await Notifications.getPermissionsAsync();
let finalStatus = existingStatus;
if (existingStatus !== 'granted') {
const {status} = await Notifications.requestPermissionsAsync();
finalStatus = status;
}
if (finalStatus !== 'granted') {
// Alert.alert(
// "Error",
// "Failed to get your notification token! Please allow notifications for Insight/Expo Go in your settings. ",
// [
// { text: "OK", onPress: () => console.log("OK Pressed") }
// ],
// { cancelable: false }
// );
return;
}
return (await Notifications.getExpoPushTokenAsync()).data;
} else {
//alert('Must use physical device for Push Notifications');
}
if (Platform.OS === 'android') {
await Notifications.setNotificationChannelAsync('default', {
name: 'default',
importance: Notifications.AndroidImportance.MAX,
vibrationPattern: [0, 250, 250, 250],
lightColor: '#FF231F7C',
});
}
};
const paddingStyles = StyleSheet.create({
padding: {
flex: 1,
paddingTop: Platform.OS === 'android' ? StatusBar.currentHeight : 0
},
noPadding: {
flex: 1,
paddingTop: 0
},
});