Dan P.
Dan P.

Reputation: 1775

Firebase Auth: Edit UID

Is it possible to to change a user's UID in Firebase programmatically? There can't seem to be a way to do so manually within Firebase's console.

Upvotes: 21

Views: 14436

Answers (5)

Saurabh
Saurabh

Reputation: 375

Piggybacking on @Vinrynx's post. I recently created a migration tool where I am migrating collections from 1 Firebase Project to another and it required that after I insert users to "users" collection I also create an authentication record with the same doc.id

Variables in the functions below:
outCollData : Data that I am inserting for the user (contains the email inside it)
sourceDBApp : output of the admin.initializeApp({/*service-account.json file location for source firebase project */});
destDBApp : output of the admin.initializeApp({/*service-account.json file location for destination firebase project */});

async function updateUsersUID(
  outCollData: any,
  sourceDBApp: admin.app.App | undefined,
  destDBApp: admin.app.App | undefined
) {
  if (destDBApp === undefined) return;

  const admin = destDBApp;

  const email = outCollData.personali.email ? outCollData.personali.email : "";
  console.log("Email is ", email);

  if (email === "" || email === undefined) return;

  console.log("Inside updateUsersUID");
  let newUserOverrides = {
    uid: outCollData._id,
  };
  let oldUser: any;
  try {
    console.log("Starting update for user with email:", email);
    oldUser = await admin.auth().getUserByEmail(email!);
    //console.log("Old user found:", oldUser);

    if (oldUser.uid === outCollData._id) {
      console.log(
        "User " +
          email +
          " already exists in the destination DB with UID " +
          outCollData._id
      );
      return;
    }
    await admin.auth().deleteUser(oldUser.uid);
    console.log("Old user deleted.");
  } catch (e) {
    console.log("User not found in destination DB ", email);
    console.log("Copying the user data from source DB");
    oldUser = await sourceDBApp?.auth().getUserByEmail(email);
  }

  let dataToTransfer_keys = [
    "disabled",
    "displayName",
    "email",
    "emailVerified",
    "phoneNumber",
    "photoURL",
    "uid",
    "providerData",
  ];
  let newUserData: any = {};
  for (let key of dataToTransfer_keys) {
    newUserData[key] = oldUser[key];
  }
  Object.assign(newUserData, newUserOverrides);
  //console.log("New user data ready: ", newUserData);

  let newUser = await admin.auth().createUser(newUserData);
  console.log("New user created ");
}

Upvotes: 0

Venryx
Venryx

Reputation: 17999

Building on the answer by RoccoB, the below is a complete set of instructions for changing a user's UID:

  1. Create a new folder, and run npm init with default values.
  2. Run npm install firebase-admin.
  3. Create a NodeJS script file (eg. UpdateUserUID.js), with this code:
let admin = require("firebase-admin");

// config
let email = "XXX";
let serviceAccountData = require("XXX.json");
let adminConfig = {
    credential: admin.credential.cert(serviceAccountData),
    databaseURL: "https://XXX.firebaseio.com",
};
let newUserOverrides = {
    uid: "XXX",
};

Start();
async function Start() {
    console.log("Initializing firebase. databaseURL:", adminConfig.databaseURL);
    admin.initializeApp(adminConfig);

    console.log("Starting update for user with email:", email);
    let oldUser = await admin.auth().getUserByEmail(email);
    console.log("Old user found:", oldUser);

    await admin.auth().deleteUser(oldUser.uid);
    console.log("Old user deleted.");

    let dataToTransfer_keys = ["disabled", "displayName", "email", "emailVerified", "phoneNumber", "photoURL", "uid"];
    let newUserData = {};
    for (let key of dataToTransfer_keys) {
        newUserData[key] = oldUser[key];
    }
    Object.assign(newUserData, newUserOverrides);
    console.log("New user data ready: ", newUserData);

    let newUser = await admin.auth().createUser(newUserData);
    console.log("New user created: ", newUser);
}
  1. Replace email and adminConfig.databaseURL with the correct values.
  2. Replace newUserOverrides.uid with the desired new uid. (you can change some other fields too)
  3. Generate/download a private key for your project's Firebase Admin service account: https://firebase.google.com/docs/admin/setup (can skip to the "Initialize the SDK" section)
  4. Update the serviceAccountData variable's import to point to the key json-file from the previous step.
  5. Run node ./UpdateUserUID.js.
  6. If applicable (I didn't seem to need it), use the "reset password" option in the Firebase Admin Console, to have a password-reset email sent to the user, apparently completing the account update. (Perhaps I didn't need this step since I don't use the accounts/authentications for anything besides sign-in on my website...)

Upvotes: 11

RoccoB
RoccoB

Reputation: 2579

TL;DR: If you need to specify the UID, you'll need to create a new user with that UID.

You can't directly change the UID, but I was able to hack something together using the firebase admin API (docs)

My use case was that I needed to change a user's email address. I tried update email with "Update a User", but this actually ended up changing the UID under the hood. In my app, the UID is tied to so much stuff, that I'd have to do a huge architecture change, so this wasn't an option.

The general way I did this with the API was:

  • Pull Down a user using admin.auth().getUserByEmail
  • Delete the user with admin.auth().deleteUser
  • Create a new user with admin.auth().createUser, using relevant data from the getUserByEmail call above, replacing the email address with the new email.
  • "reset password" in the firebase admin console (I think there's a way to do this programmatically too)
  • User gets an email to reset their password and they have a new account with their old UID.

Unlike admin.auth().updateUser, createUser actually lets you specify a UID.

Upvotes: 14

Gastón Saillén
Gastón Saillén

Reputation: 13129

You can't, since is the main tree node of possibles more entries inside it, you can get it, modify and then put it inside the same UID (or create a new one) but you can have things inside, for example take this.

You create your main UID which will hold user data (name, phone, email etc) lets say the structure is this:

-9GJ02kdj2GKS55kg
                  -Name:
                  -Phone:
                  -Email:

so, you can get the main user UID 9GJ02kdj2GKS55kg with mAuth.getCurrentUser().getUid(); and then change it and set a new value inside 9GJ02kdj2GKS55kg, this new value should be the same UID you got but changed, and then inside your main UID you can still have the same structure

 -9GJ02kdj2GKS55kg
      -6GL02kZj2GKS55kN  (this is your changed UID)
                      -Name:
                      -Phone:
                      -Email:

or you can get that changed UID and make a new child, and that will be your parent node with custom UID for the data.

Upvotes: 0

Frank van Puffelen
Frank van Puffelen

Reputation: 598901

The UID of a user is controlled by the identity provider that creates that user. This means that you can't change the UID for any of the built-in providers.

But you can control the UID if you create a custom identity provider. Note that this is quite a bit more involved than changing something in the Firebase console. It requires you to write code that runs in a secure/trusted environment, such as a server you control, or Cloud Functions.

Upvotes: 4

Related Questions