forked from SI669-internal/week11ChatF22
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathAuthManager.js
64 lines (52 loc) · 1.56 KB
/
AuthManager.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
import { getAuth, createUserWithEmailAndPassword,
signInWithEmailAndPassword,
updateProfile,
signOut as fbSignOut,
initializeAuth,
getReactNativePersistence,
onAuthStateChanged
} from 'firebase/auth';
import ReactNativeAsyncStorage from '@react-native-async-storage/async-storage';
import { getApps, initializeApp } from 'firebase/app';
import { firebaseConfig } from './Secrets';
import { setUser } from './data/Actions';
let app, auth;
const apps = getApps();
if (apps.length == 0) {
app = initializeApp(firebaseConfig);
} else {
app = apps[0];
}
try {
auth = initializeAuth(app, {
persistence: getReactNativePersistence(ReactNativeAsyncStorage)
});
} catch (error) {
auth = getAuth(app); // if auth already initialized
}
const subscribeToAuthChanges = (navigation, dispatch) => {
onAuthStateChanged(auth, (authUser) => {
if (authUser) {
console.log('got an auth change:', authUser);
dispatch(setUser(authUser));
navigation.navigate('Home');
} else {
navigation.navigate('Login');
}
})
}
const signIn = async (email, password) => {
await signInWithEmailAndPassword(auth, email, password);
}
const signUp = async (displayName, email, password) => {
const userCred = await createUserWithEmailAndPassword(auth, email, password);
await updateProfile(userCred.user, {displayName: displayName});
return userCred.user;
}
const signOut = async () => {
await fbSignOut(auth);
}
const getAuthUser = () => {
return auth.currentUser;
}
export { signUp, signIn, signOut, getAuthUser, subscribeToAuthChanges };