Repository navigation
Expand file tree
/
Copy pathchangeLocalUserEmail.js
More file actions
60 lines (53 loc) · 1.73 KB
/
Copy pathchangeLocalUserEmail.js
File metadata and controls
60 lines (53 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
const admin = require("firebase-admin");
const prod = "/prodAccKey.json";
const dev = "/testAccKey.json";
admin.initializeApp({
credential: admin.credential.cert(require("." + dev)),
});
const auth = admin.auth();
const db = admin.firestore();
function generateTempPassword(length = 8) {
const chars = "abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
let password = "";
for (let i = 0; i < length; i++) {
password += chars.charAt(Math.floor(Math.random() * chars.length));
}
return password;
}
async function changeLocalUserEmail(oldEmail, newEmail) {
const userRecord = await auth.getUserByEmail(oldEmail);
const uid = userRecord.uid;
const tempPassword = generateTempPassword();
try {
await auth.updateUser(uid, {
email: newEmail,
password: tempPassword,
emailVerified: true,
});
} catch (err) {
if (err.code === "auth/email-already-exists") {
console.log(
`[${new Date().toISOString()}] Cannot update ${uid}: ${newEmail} is already in use by another account`,
);
return;
}
throw err;
}
console.log(
`[${new Date().toISOString()}] Updated Auth email for ${uid}: ${oldEmail} -> ${newEmail}, Temporary Password: ${tempPassword}`,
);
const userDoc = db.collection("User").doc(uid);
const snapshot = await userDoc.get();
if (!snapshot.exists) {
console.log(
`[${new Date().toISOString()}] No User doc found for ${uid}, skipping Firestore update`,
);
return;
}
await userDoc.update({ Email: newEmail });
console.log(
`[${new Date().toISOString()}] Updated User/${uid} Email field: ${oldEmail} -> ${newEmail}`,
);
}
//update with the rigtht details
changeLocalUserEmail("old@email.com", "new@email.com").catch(console.error);