Created
December 3, 2018 22:23
-
-
Save katowulf/f1c45055b91672f27c094a77103c78f4 to your computer and use it in GitHub Desktop.
Create a Firebase user from an authenticated Cloud Functions HTTPS endpoint.
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
const functions = require('firebase-functions'); | |
const admin = require('firebase-admin'); | |
admin.initializeApp(); | |
const express = require('express'); | |
const cookieParser = require('cookie-parser')(); | |
const cors = require('cors')({origin: true}); | |
const app = express(); | |
// See https://github.com/firebase/functions-samples/blob/Node-8/authorized-https-endpoint/functions/index.js | |
const validateFirebaseIdToken = require('./validateFirebaseIdToken'); | |
app.use(cors); | |
app.use(cookieParser); | |
app.use(validateFirebaseIdToken); | |
app.get('/createUser', (req, res) => { | |
const userData = req.params; | |
// This represents some criteria you set for determining who can call this endpoint | |
// possible a list of approved uids in your database? | |
if( req.user.uid !== VALID_ADMIN_USER ) { | |
res.status(401).send('Unauthorized'); | |
return; | |
} | |
// See https://firebase.google.com/docs/auth/admin/manage-users#create_a_user | |
admin.auth().createUser({ | |
email: userData.email, | |
displayName: userData.name, | |
... | |
}) | |
.then(function(userRecord) { | |
// See the UserRecord reference doc for the contents of userRecord. | |
res.json({result: 'success', uid: userRecord.uid}); | |
console.log("Successfully created new user:", userRecord.uid); | |
}) | |
.catch(function(error) { | |
console.error("Failed to create new user"); | |
console.error(error); | |
res.status(500).json({status: 'error', error: 'Unable to process the request'}); | |
}); | |
}); | |
// This HTTPS endpoint can only be accessed by your Firebase Users. | |
// Requests need to be authorized by providing an `Authorization` HTTP header | |
// with value `Bearer <Firebase ID Token>`. | |
exports.app = functions.https.onRequest(app); | |
© 2018 GitHub, |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment