-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwithFireAuth.tsx
99 lines (88 loc) · 2.7 KB
/
withFireAuth.tsx
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
import React from "react";
import firebase from "firebase";
export type WrappedComponentProps = {
signInWithGoogle: () => void;
signOut: () => void;
user?: firebase.User | null;
error?: string;
loading: boolean;
};
export type FirebaseHOCState = {
loading: boolean;
user?: firebase.User | null;
error?: string;
};
export default function withFireAuth<P extends object>(
firebaseAppAuth: firebase.auth.Auth
) {
// const firebaseApp = firebase.initializeApp(firebaseConfig);
const provider = new firebase.auth.GoogleAuthProvider();
// const firebaseAppAuth = firebaseApp.auth();
return (WrappedComponent: React.ComponentType<P & WrappedComponentProps>) => {
return class FirebaseHOC extends React.PureComponent<P, FirebaseHOCState> {
static displayName = `withFireAuth(${
WrappedComponent.displayName || WrappedComponent.name
})`;
state: FirebaseHOCState = {
loading: false,
user: undefined,
error: undefined,
};
componentDidMount() {
firebaseAppAuth.onAuthStateChanged((user) => {
if (user) {
this.setState({ user });
}
});
}
signOut = async () => {
try {
this.setState({ loading: true });
await firebaseAppAuth.signOut();
this.setState({ user: null });
} catch (error) {
this.setState({ error });
return error;
} finally {
this.setState({ loading: false });
}
};
signInWithGoogle = async () => {
try {
this.setState({ loading: true });
const result = await firebaseAppAuth.signInWithPopup(provider);
const user = result.user;
this.setState({ user });
} catch (error) {
this.setState({ error });
const email = error.email;
const credential = error.credential;
if (error.code === "auth/account-exists-with-different-credential") {
// When adding multiple providers this will handle existing account error
// e.g. Sign in with FB email but Google Email Account already exists
firebaseAppAuth
.fetchSignInMethodsForEmail(email)
.then(function (providers) {});
}
} finally {
this.setState({ loading: false });
}
};
render() {
const props = {
...this.props,
loading: this.state.loading,
user: this.state.user,
error: this.state.error,
};
return (
<WrappedComponent
{...props}
signInWithGoogle={this.signInWithGoogle}
signOut={this.signOut}
/>
);
}
};
};
}