-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.js
399 lines (367 loc) · 10.9 KB
/
auth.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
389
390
391
392
393
394
395
396
397
398
399
import React, { Component, useState, useEffect } from "react";
import {
StyleSheet,
ScrollView,
View,
KeyboardAvoidingView,
Text,
TextInput,
ActivityIndicator,
Keyboard,
Modal,
Pressable,
StatusBar,
TouchableHighlight,
NativeEventEmitter,
NativeModules,
Platform,
PermissionsAndroid,
AppState,
Dimensions,
FlatList,
Image
} from "react-native";
import { Button } from "react-native-elements";
import LinearGradient from "react-native-linear-gradient";
// import sha256 from "crypto-js/sha256";
// import Hex from "crypto-js/enc-hex";
import {
GoogleSignin,
GoogleSigninButton,
statusCodes
} from "@react-native-community/google-signin";
import {
appleAuth,
appleAuthAndroid,
AppleButton
} from "@invertase/react-native-apple-authentication";
import auth from "@react-native-firebase/auth";
import { set } from "react-native-reanimated";
import { BleManager } from 'react-native-ble-plx';
export const manager = new BleManager();
var sess = require("./sess.js");
const styles = StyleSheet.create({
appleButton: {
width: 190,
height: 35,
shadowColor: "#555",
shadowOpacity: 0.5,
shadowOffset: {
width: 0,
height: 1
},
marginVertical: 5
},
centeredView: {
flex: 1,
justifyContent: "center",
alignItems: "center",
marginTop: 22
},
modalView: {
margin: 20,
backgroundColor: "white",
borderRadius: 20,
padding: 30,
alignItems: "center",
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 2
},
shadowOpacity: 0.25,
shadowRadius: 4,
elevation: 5,
width: "80%"
},
modalText: {
marginBottom: 15,
textAlign: "center"
},
textStyle: {
color: "white",
fontWeight: "bold",
textAlign: "center"
},
button: {
borderRadius: 10,
padding: 10,
elevation: 2,
margin: 5
},
buttonSignin: {
backgroundColor: "#2196F3"
},
buttonClose: {
backgroundColor: "rgb(100,100,100)"
},
buttonForgot: {
backgroundColor: "rgb(200,20,20)"
}
});
function opensenecaForgotpassword(username) {
if (username.length == 0) {
alert("Input your email address");
} else
try {
auth().sendPasswordResetEmail(username);
alert(
"An email has been sent to " + username + " with a password reset link"
);
} catch (error) {
alert("Input your email address");
}
}
function opensenecaSignin(username, password) {
auth()
.createUserWithEmailAndPassword(username, password)
.then(() => {
console.log("user account created and signed in");
})
.catch(error => {
if (error.code === "auth/email-already-in-use") {
// console.log('That email address is already in use!');
auth()
.signInWithEmailAndPassword(username, password)
.then(() => {
console.log("user account signed in");
})
.catch(error => {
alert("Incorrect email or password");
});
} else {
if (error.code === "auth/invalid-email") {
alert("Email address invalid");
}
console.error(error);
}
});
}
async function onAppleButtonPress() {
// Start the sign-in request
const appleAuthRequestResponse = await appleAuth.performRequest({
requestedOperation: appleAuth.Operation.LOGIN,
requestedScopes: [appleAuth.Scope.EMAIL, appleAuth.Scope.FULL_NAME]
});
// Ensure Apple returned a user identityToken
if (!appleAuthRequestResponse.identityToken) {
throw "Apple Sign-In failed - no identify token returned";
}
// Create a Firebase credential from the response
const { identityToken, nonce, fullName } = appleAuthRequestResponse;
const appleCredential = auth.AppleAuthProvider.credential(
identityToken,
nonce
);
// Sign the user in with the credential
const userCredential = await auth().signInWithCredential(appleCredential);
if (
fullName.givenName !== null ||
fullName.middleName !== null ||
fullName.familyName !== null
) {
let fullname = "";
if (fullName.givenName !== null) fullname += fullName.givenName + " ";
if (fullName.middleName !== null) fullname += fullName.middleName + " ";
if (fullName.familyName !== null) fullname += fullName.familyName;
console.log("full name is: " + fullname);
if (userCredential.user.displayName === null) {
console.log("updating display name in Firebase");
userCredential.user.updateProfile({ displayName: fullname });
}
}
}
async function onGoogleButtonPress() {
console.log("clicked sigin");
try {
console.log("has play");
await GoogleSignin.hasPlayServices();
console.log("google sig in");
const userInfo = await GoogleSignin.signIn();
// console.log("got userinfo",userInfo,"now attempting firebase auth");
// Create a Google credential with the token
console.log("google cred");
const googleCredential = auth.GoogleAuthProvider.credential(
userInfo.idToken
);
// Sign-in the user with the credential
console.log("firebase sign in");
const userCredential = await auth().signInWithCredential(googleCredential);
console.log("firebase get id");
let idToken = await userCredential.user.getIdToken(true);
console.log("backend signin");
sess.backendSignin(idToken, userCredential.user, userCredential, userInfo);
} catch (error) {
if (error.code === statusCodes.SIGN_IN_CANCELLED) {
console.log("user cancelled the login flow");
} else if (error.code === statusCodes.IN_PROGRESS) {
console.log("operation (e.g. sign in) is in progress already");
} else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
console.log("play services not available or outdated");
} else {
console.log("some other error happened");
throw error;
}
}
}
async function signOut() {
console.log("Signing out");
try {
// sess.unsubscribeAuthStateHandler()
if (auth().currentUser) {
console.log("Signing out", auth().currentUser);
auth()
.signOut()
.then(() => {
// console.log("disconnecting BLE");
sess.disconnectBLE();
sess.setUser(null);
});
} else {
console.log("Signout failed, no user", auth().currentUser);
}
} catch (error) {
console.error(error);
}
}
sess.reloadAuth = async () => {
console.log("attempting to reload user");
let user = auth().currentUser;
let idToken = await user.getIdToken(true);
sess.backendSignin(idToken, user, null, null);
};
class LoginScreen extends Component {
constructor(props) {
super(props);
this.state = {
modalVisible: false,
value: "",
password: ""
}
}
componentDidMount() {
GoogleSignin.configure({
webClientId:
"917957692861-ij34bmovlk3ni4hlcnt7isdg2mhf3f4d.apps.googleusercontent.com"
});
}
render() {
let signinBtn = (
<GoogleSigninButton
style={{ width: 200, height: 48 }}
size={GoogleSigninButton.Size.Wide}
color={GoogleSigninButton.Color.Dark}
onPress={() => onGoogleButtonPress()}
/>
);
let opensenecaBtn = (
<Button
ViewComponent={LinearGradient} // Don't forget this!
linearGradientProps={{
colors: ["rgb(245,245,245)", "rgb(210,210,210)"],
start: { x: 0, y: 0 },
end: { x: 1, y: 3 }
}}
title="Sign in with open-seneca"
titleStyle={{ fontSize: 14.5, color: "rgb(80,80,80)" }}
buttonStyle={{ marginTop: 10, borderRadius: 5, width: 190 }}
onPress={() => this.setState({modalVisible: true})}
/>
);
let appleBtn = [];
if (Platform.OS === "ios" && appleAuth.isSupported) {
appleBtn = (
<AppleButton
buttonStyle={AppleButton.Style.WHITE}
buttonType={AppleButton.Type.SIGN_IN}
style={styles.appleButton}
onPress={() => onAppleButtonPress()}
/>
);
}
return (
<View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
<Image
resizeMode="contain"
style={{ width: "90%", marginLeft: "auto", marginRight: "auto" }}
source={require("./logo.png")}
/>
<Modal
animationType="slide"
transparent={true}
visible={this.state.modalVisible}
onRequestClose={() => {
this.setState({modalVisible: false});
}}
>
<View style={styles.centeredView}>
<View style={styles.modalView}>
<Text style={{ fontSize: 20, marginBottom: 10 }}>
Create account or login
</Text>
<Text style={styles.modalText}>
Create a new account or {"\n"}login with an existing
</Text>
<TextInput
style={{
height: 40,
borderColor: "gray",
borderWidth: 1,
width: 200,
padding: 10
}}
placeholder="Email address"
maxLength={60}
onChangeText={text => this.setState({value: text})}
value={this.state.value}
autoCapitalize={"none"}
autoCorrect={false}
autoFocus={true}
/>
<TextInput
style={{
height: 40,
borderColor: "gray",
borderWidth: 1,
width: 200,
padding: 10
}}
placeholder="Password"
maxLength={60}
onChangeText={text => this.setState({password: text})}
value={this.state.password}
autoCapitalize={"none"}
autoCorrect={false}
autoFocus={false}
secureTextEntry={true}
onSubmitEditing={() => opensenecaSignin(this.state.value, this.state.password)} // for pressing enter
/>
<Pressable
style={[styles.button, styles.buttonSignin]}
onPress={() => opensenecaSignin(this.state.value, this.state.password)}
>
<Text style={styles.textStyle}>Continue</Text>
</Pressable>
<Pressable
style={[styles.button, styles.buttonForgot]}
onPress={() => opensenecaForgotpassword(value)}
>
<Text style={styles.textStyle}>Forgot password?</Text>
</Pressable>
<Pressable
style={[styles.button, styles.buttonClose]}
onPress={() => this.setState({modalVisible: false})}
>
<Text style={styles.textStyle}>Cancel</Text>
</Pressable>
</View>
</View>
</Modal>
{signinBtn}
{appleBtn}
{opensenecaBtn}
</View>
);
}
}
export { LoginScreen, signOut };