Created
February 21, 2020 23:06
-
-
Save odbol/af38b682a1b982b3cab0fbf931db269f to your computer and use it in GitHub Desktop.
Firebase login: the easiest way, with promises
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Handles logging in to Firebase. | |
*/ | |
class Authentication { | |
authPromise; | |
constructor() { | |
this.authPromise = new Promise((resolve, reject) => { | |
firebase.auth().onAuthStateChanged(function(user) { | |
if (user) { | |
// User is signed in. | |
resolve(user); | |
} else { | |
// User is signed out. | |
reject(new Error('Not logged in')); | |
} | |
}); | |
}); | |
} | |
/** | |
* Returns a Promise with the current logged in user, or logs in and then returns the user. | |
* | |
* It is safe to call this every time you need to do an operation requiring an authenticated user; | |
* it will not re-login every time. | |
*/ | |
signIn() { | |
const auth = firebase.auth(); | |
if (auth.currentUser) { | |
return Promise.resolve(auth.currentUser); | |
} | |
return this.authPromise | |
.catch((err) => { | |
// You can replace the provider here with whichever one you're using. | |
const provider = new firebase.auth.GoogleAuthProvider(); | |
return auth.signInWithPopup(provider) | |
.then(function(result) { | |
// This gives you a Google Access Token. You can use it to access the Google API. | |
var token = result.credential.accessToken; | |
// The signed-in user info. | |
var user = result.user; | |
return user; | |
}) | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment