-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAuthContext.js
275 lines (241 loc) · 8.1 KB
/
AuthContext.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
import React, {createContext, useState, useEffect} from 'react';
import { getDatabase, ref, set } from "firebase/database";
import AsyncStorage from '@react-native-async-storage/async-storage';
import { auth } from '../firebase-config';
import { signInWithEmailAndPassword, createUserWithEmailAndPassword, sendPasswordResetEmail, signOut, } from 'firebase/auth';
export const AuthContext = createContext();
const db = getDatabase();
export const AuthProvider = ({children}) =>{
const [ isLoading, setisLoading ] = useState(false);
const [ user, setUser] = useState(null);
const [ user_name, setUser_Name] = useState(null)
const [userImg, setUserImg] = useState(null)
const [error, setError] = useState(null);
const [ userToken, setUserToken ] = useState(null);
const [ userRole, setUserRole] = useState("");
const [ whichRole, setWhichRole] = useState("");
const [Page, setPage] = useState();
const [submitted, setSubmitted] = useState(false);
const Login = async (email, password) =>{
try {
setisLoading(true);
await signInWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
const user = userCredential.user;
setUserToken(user.accessToken);
AsyncStorage.setItem('userToken', user.accessToken);
AsyncStorage.setItem('userRole', 'Donor');
setUserRole('Donor');
setisLoading(false);
setSubmitted(false);
})
} catch (error) {
setisLoading(false);
setError(alert('Invalid Credentials'))
setSubmitted(false);
console.log(`Error ${error}`);
}
}
const LoginAsMed = async (email, password) =>{
try {
setisLoading(true);
await signInWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
const user = userCredential.user;
setUserToken(user.accessToken);
AsyncStorage.setItem('MedUserToken', user.accessToken);
AsyncStorage.setItem('userRole', 'Medical');
setUserRole('Medical');
setisLoading(false);
setSubmitted(false);
})
} catch (error) {
setisLoading(false);
setError(alert('Invalid Credentials'))
setSubmitted(false);
console.log(`Error ${error}`);
}
}
// const LoginWithGoogle = async () =>{
// try {
// setisLoading(true);
// const provider = new GoogleAuthProvider();
// await signInWithPopup(auth, provider)
// .then((result) => {
// const credential = GoogleAuthProvider.credentialFromResult(result);
// const token = credential.accessToken;
// setUserToken(token);
// AsyncStorage.setItem('userToken', token);
// setisLoading(false);
// // ...
// }).catch((error) => {
// const errorCode = error.code;
// const errorMessage = error.message;
// const email = error.customData.email;
// const credential = GoogleAuthProvider.credentialFromError(error);
// // ...
// });
// }
// catch(error){
// setisLoading(false);
// setError(alert('Cant Access Google Account'))
// console.log(`Error ${error}`);
// }
// // }
// const LoginWithFacebook = async () =>{
// try {
// setisLoading(true);
// const provider = new FacebookAuthProvider();
// await signInWithPopup(auth, provider)
// .then((result) => {
// const credential = FacebookAuthProvider.credentialFromResult(result);
// const token = credential.accessToken;
// setUserToken(token);
// AsyncStorage.setItem('userToken', token);
// setisLoading(false);
// // ...
// }).catch((error) => {
// const errorCode = error.code;
// const errorMessage = error.message;
// const email = error.customData.email;
// const credential = GoogleAuthProvider.credentialFromError(error);
// // ...
// });
// }
// catch(error){
// setisLoading(false);
// setError(alert('Cant Access Facebook Account'))
// console.log(`Error ${error}`);
// }
// }
// const LoginWithTwitter = async () =>{
// try {
// setisLoading(true);
// const provider = new TwitterAuthProvider();
// await signInWithPopup(auth, provider)
// .then((result) => {
// const credential = TwitterAuthProvider.credentialFromResult(result);
// const token = credential.accessToken;
// setUserToken(token);
// AsyncStorage.setItem('userToken', token);
// setisLoading(false);
// // ...
// }).catch((error) => {
// const errorCode = error.code;
// const errorMessage = error.message;
// const email = error.customData.email;
// const credential = TwitterAuthProvider.credentialFromError(error);
// // ...
// });
// }
// catch(error){
// setisLoading(false);
// setError(alert('Cant Access Twitter Account'))
// console.log(`Error ${error}`);
// }
// }
const Register = async (email, password)=>{
try {
setisLoading(true);
await createUserWithEmailAndPassword(auth, email, password).then((userCredential) => {
const user = userCredential.user;
set(ref(db, 'users/' + user.uid), {
username: '',
email: email,
gender:'',
blood_group:'',
contact:'',
state:'',
profile_picture : ''
});
})
setisLoading(false);
} catch (e) {
setisLoading(false);
setError(alert('Email Already Exist'))
console.log(`Error ${e}`);
}
}
const RegisterAsMed = async (email, password)=>{
try {
setisLoading(true);
await createUserWithEmailAndPassword(auth, email, password).then((userCredential) => {
const user = userCredential.user;
set(ref(db, 'med-users/' + user.uid), {
clinic_name: '',
address:'',
RC_NUMBER:'',
state:'',
});
})
setisLoading(false);
} catch (e) {
setisLoading(false);
setError(alert('Error'))
console.log(`Error ${e}`);
}
}
const resetUserPassword = async (email) => {
try {
await sendPasswordResetEmail(auth, email);
setSubmitted(true);
setError(null);
} catch (error) {
if (error.code === 'auth/user-not-found') {
setError('User not found');
} else {
setError('There was a problem with your request');
}
}
};
const DonorClick = async () =>{
await AsyncStorage.setItem('PageD', 'Donor');
setPage(AsyncStorage.getItem('PageD'));
}
const MedClick = async () =>{
await AsyncStorage.setItem('PageM', 'Med');
setPage(AsyncStorage.getItem('PageM'));
}
const Logout = async ()=>{
try {
setisLoading(true);
setUserToken(null);
await signOut(auth);
await AsyncStorage.removeItem('userToken');
setisLoading(false);
} catch (e) {
console.log(`Error ${e}`);
}
}
const LogoutAsMed = async () =>{
try {
setisLoading(true);
setUserToken(null);
await signOut(auth);
await AsyncStorage.removeItem('MedUserToken');
setisLoading(false);
} catch (e) {
console.log(`Error ${e}`);
}
}
const isLoggedIn = async ()=>{
try {
setisLoading(true);
let userToken = userRole === 'Donor' ? await AsyncStorage.getItem('userToken') : await AsyncStorage.getItem('MedUserToken');
let userRoleString = userToken === 'userToken' ? 'Donor' : 'Med';
setUserRole(userRoleString)
setUserToken(userToken);
setisLoading(false);
} catch (e) {
console.log(`Error ${e}`);
}
}
useEffect(()=>{
isLoggedIn();
}, [])
return(
<AuthContext.Provider value={{Login, Logout, LogoutAsMed, Register, LoginAsMed, DonorClick, MedClick, RegisterAsMed, resetUserPassword, setPage, setUser_Name, setUserImg, setWhichRole, whichRole, user_name, userImg, Page, user, submitted, userRole, error, setUser, isLoading, userToken}} >
{children}
</AuthContext.Provider>
)
}