简体   繁体   中英

How to add admin role to only the first user in Firebase?

I am registering as a first user.

How do I add admin role to only a first user in Firebase Firestore database?

  const auth = firebase.auth();
  const db = firebase.firestore();


  // sign up the user
  auth.createUserWithEmailAndPassword(email, password).then((cred) => {
        // set admin to true for the only first user
        return db.collection('users').doc(cred.user.uid).set({
            admin: true
        })

  }).then(() => {
     console.log();
  }).catch(err => {

  });

You could create a cloud function which is triggered if an user is created.

import * as admin from 'firebase-admin';
import * as functions from 'firebase-functions';

admin.initializeApp({
  databaseURL: "https://your-project-name.firebaseio.com"
});

export const onCreateUser = functions.auth.user().onCreate(async (createdUser) => {
  const listUsersResult = await admin.auth().listUsers(2);

  if (listUsersResult.users.length === 1) {
    await admin.auth().setCustomUserClaims(createdUser.uid, {admin: true});
  } else {
    await admin.auth().setCustomUserClaims(createdUser.uid, {admin: false});
  }

  return;
});

With the admin.auth().listUsers(1) method you get an array of users with the length of 1.

If the created user is the first on this project the method returns an empty array. If this is the case the users custom claims are set to {admin: true} .

Now you could create a security rule which allows this user to access all Firestore documents.

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth.uid != null && request.auth.token.admin == true;
    }
  }
}

The custom claims are accessible on the request.auth.token property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM