Last active
December 13, 2022 14:39
-
-
Save maucaro/7570519b82ac25bbfec5f42a1166df45 to your computer and use it in GitHub Desktop.
Firebase add admin user (with admin custom claim) to tenant
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
import admin from 'firebase-admin'; | |
import { initializeApp } from 'firebase-admin/app'; | |
initializeApp({ | |
apiKey: process.env.API_KEY, | |
authDomain: process.env.AUTH_DOMAIN, | |
credential: admin.credential.applicationDefault(), | |
projectId: process.env.PROJECT_ID, | |
}); | |
export const addAdminUser = (req, res) => { | |
if (!req.body.email || req.body.email === '') { | |
const error = 'The email must be a valid non-empty string.'; | |
console.error(error); | |
res.status(400).send(error); | |
return; | |
} | |
if (!req.body.password || req.body.password === '') { | |
const error = 'The password must be a valid non-empty string.'; | |
console.error(error); | |
res.status(400).send(error); | |
return; | |
} | |
const tenantManager = admin.auth().tenantManager(); | |
const tenantAuth = tenantManager.authForTenant(req.body.tenantId); | |
tenantAuth | |
.createUser({ | |
email: req.body.email, | |
emailVerified: false, | |
password: req.body.password, | |
disabled: false, | |
}) | |
.then((userRecord) => { | |
tenantAuth.setCustomUserClaims(userRecord.uid, {admin: true}); | |
console.log('Successfully created new admin user:', userRecord.uid); | |
res.status(200).send(userRecord.uid); | |
return; | |
}) | |
.catch((error) => { | |
console.error('Error creating new user:', error); | |
res.status(400).send(error); | |
return; | |
}); | |
}; |
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
{ | |
"name": "tenant-add-user", | |
"version": "1.0.0", | |
"description": "Adds user to tenant in Cloud Identity Platform with a custom claim: {admin: true}", | |
"main": "index.js", | |
"type": "module", | |
"scripts": { | |
"start": "functions-framework --target=addAdminUser -r dotenv/config ", | |
"test": "echo \"Error: no test specified\" && exit 1", | |
"debug": "node --inspect node_modules/.bin/functions-framework --target=addAdminUser -r dotenv/config" | |
}, | |
"author": "Mauricio Caro", | |
"license": "ISC", | |
"dependencies": { | |
"@google-cloud/functions-framework": "^3.1.2", | |
"firebase-admin": "^11.3.0" | |
}, | |
"devDependencies": { | |
"dotenv": "^16.0.3" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment