Cloud Functions Code
unknown
javascript
4 months ago
3.5 kB
13
No Index
const functions = require("firebase-functions");
const admin = require("firebase-admin");
// Create user as admin function
exports.adminCreateAuthUser = functions.https.onCall(
{region: "europe-west3"},
async (data, context) => {
// Verify the user is authenticated
if (!context.auth) {
throw new functions.https.HttpsError(
"unauthenticated",
"Not logged in",
);
}
// Verify the user has admin privileges
if (!context.auth.token.admin) {
throw new functions.https.HttpsError(
"permission-denied",
"Admin privileges required",
);
}
const {email, password} = data;
// Validate input
if (!email || !password) {
throw new functions.https.HttpsError(
"invalid-argument",
"Email and password are required",
);
}
if (password.length < 8) {
throw new functions.https.HttpsError(
"invalid-argument",
"Password must be at least 8 characters",
);
}
try {
// Create the user in Firebase Auth
const userRecord = await admin.auth().createUser({
email: email,
password: password,
emailVerified: false,
});
// Log the operation
console.log(`Admin ${context.auth.uid} created user ` +
`${userRecord.uid} with email ${email}`);
return {
success: true,
userId: userRecord.uid,
email: userRecord.email,
};
} catch (error) {
console.error(`error creating user ${email}:`, error);
// Handle specific Firebase Auth errors
if (error.code === "auth/email-already-exists") {
throw new functions.https.HttpsError(
"already-exists",
"A user with this email already exists",
);
} else if (error.code === "auth/invalid-email") {
throw new functions.https.HttpsError(
"invalid-argument",
"Invalid email address",
);
} else if (error.code === "auth/weak-password") {
throw new functions.https.HttpsError(
"invalid-argument",
"Password is too weak",
);
}
throw new functions.https.HttpsError("internal", "Failed to create");
}
});
// Function to delete user from Auth
exports.adminDeleteAuthUser = functions.https.onCall(
{region: "europe-west3"},
async (data, context) => {
// Verify the user is authenticated and has admin privileges
if (!context.auth) {
throw new functions.https.HttpsError(
"unauthenticated",
"Must be logged in",
);
}
if (!context.auth.token.admin) {
throw new functions.https.HttpsError(
"permission-denied",
"Admin privileges required",
);
}
const {userId} = data;
if (!userId) {
throw new functions.https.HttpsError(
"invalid-argument",
"User ID is required",
);
}
try {
// Delete from Firebase Auth
await admin.auth().deleteUser(userId);
console.log(`Admin ${context.auth.uid} deleted user ${userId}`);
return {success: true};
} catch (error) {
console.error(`error deleting user ${userId}:`, error);
throw new functions.https.HttpsError("internal", "Failed to delete");
}
});
Editor is loading...