-
-
Notifications
You must be signed in to change notification settings - Fork 293
/
Copy pathfirebase.js
108 lines (78 loc) · 2.76 KB
/
firebase.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
import app from 'firebase/app';
import 'firebase/auth';
import 'firebase/database';
const config = {
apiKey: process.env.REACT_APP_API_KEY,
authDomain: process.env.REACT_APP_AUTH_DOMAIN,
databaseURL: process.env.REACT_APP_DATABASE_URL,
projectId: process.env.REACT_APP_PROJECT_ID,
storageBucket: process.env.REACT_APP_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_MESSAGING_SENDER_ID,
};
class Firebase {
constructor() {
app.initializeApp(config);
/* Helper */
this.serverValue = app.database.ServerValue;
this.emailAuthProvider = app.auth.EmailAuthProvider;
/* Firebase APIs */
this.auth = app.auth();
this.db = app.database();
/* Social Sign In Method Provider */
this.googleProvider = new app.auth.GoogleAuthProvider();
this.facebookProvider = new app.auth.FacebookAuthProvider();
this.twitterProvider = new app.auth.TwitterAuthProvider();
}
// *** Auth API ***
doCreateUserWithEmailAndPassword = (email, password) =>
this.auth.createUserWithEmailAndPassword(email, password);
doSignInWithEmailAndPassword = (email, password) =>
this.auth.signInWithEmailAndPassword(email, password);
doSignInWithGoogle = () =>
this.auth.signInWithPopup(this.googleProvider);
doSignInWithFacebook = () =>
this.auth.signInWithPopup(this.facebookProvider);
doSignInWithTwitter = () =>
this.auth.signInWithPopup(this.twitterProvider);
doSignOut = () => this.auth.signOut();
doPasswordReset = email => this.auth.sendPasswordResetEmail(email);
doSendEmailVerification = () =>
this.auth.currentUser.sendEmailVerification({
url: process.env.REACT_APP_CONFIRMATION_EMAIL_REDIRECT,
});
doPasswordUpdate = password =>
this.auth.currentUser.updatePassword(password);
// *** Merge Auth and DB User API *** //
onAuthUserListener = (next, fallback) =>
this.auth.onAuthStateChanged(authUser => {
if (authUser) {
this.user(authUser.uid)
.once('value')
.then(snapshot => {
const dbUser = snapshot.val();
// default empty roles
if (!dbUser.roles) {
dbUser.roles = {};
}
// merge auth and db user
authUser = {
uid: authUser.uid,
email: authUser.email,
emailVerified: authUser.emailVerified,
providerData: authUser.providerData,
...dbUser,
};
next(authUser);
});
} else {
fallback();
}
});
// *** User API ***
user = uid => this.db.ref(`users/${uid}`);
users = () => this.db.ref('users');
// *** Message API ***
message = uid => this.db.ref(`messages/${uid}`);
messages = () => this.db.ref('messages');
}
export default Firebase;