Last active
October 17, 2018 04:58
-
-
Save BehindTheMath/7c6be4921364d33f54e2514daa3154c2 to your computer and use it in GitHub Desktop.
Sample code for Firebase Auth
This file contains 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
import {auth, credential, initializeApp} from "firebase-admin"; | |
// Call this before starting the server | |
export function init() { | |
const serviceAccount = { | |
clientEmail: process.env.FIREBASE_SERVICE_ACCOUNT_CLIENT_EMAIL, | |
privateKey: process.env.FIREBASE_SERVICE_ACCOUNT_PRIVATE_KEY, | |
projectId: process.env.FIREBASE_SERVICE_ACCOUNT_PROJECT_ID | |
}; | |
initializeApp({ | |
credential: credential.cert(serviceAccount), | |
databaseURL: '' | |
}); | |
} | |
// Call this to verify the ID token. Returns a Promise with the UserRecord, or throws if invalid. | |
export async function decodeIdToken(idToken) { | |
const decodedIdToken = await auth().verifyIdToken(idToken); | |
return auth().getUser(decodedIdToken.uid); | |
} |
This file contains 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
import firebase from "firebase/app"; | |
import "firebase/auth"; | |
// Call this right when you want to enforce login. | |
// This will check if the user is logged in, and redirect to the logi screen if they are not. | |
export function initAuth() { | |
return new Promise((resolve, reject) => { | |
const config = { | |
apiKey: "", | |
authDomain: "", | |
databaseURL: "", | |
projectId: "", | |
storageBucket: "", | |
messagingSenderId: "", | |
}; | |
firebase.initializeApp(config); | |
const unsubscribe = firebase.auth().onAuthStateChanged(function (user) { | |
if (!user) { | |
// User is not signed in. | |
try { | |
resolve(firebase.auth().signInWithRedirect(new firebase.auth.GoogleAuthProvider())); | |
} catch (e) { | |
reject(e); | |
} | |
} else { | |
unsubscribe(); | |
resolve(); | |
} | |
}); | |
}); | |
} | |
// Call this function to get an ID token that you can send with your requests (in a header) | |
// to be able to authenticate the user on the backend. | |
export async function getIdToken() { | |
const currentUser = firebase.auth().currentUser; | |
return currentUser ? currentUser.getIdToken() : null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment