3👍
✅
As discussed in the comments above, you can adapt the code contained in the "How to create an Admin module for managing Firebase users access and roles" article.
In your case the users "can register on the platform freely (like Facebook for example)" so you don’t need to check that the Callable Cloud function caller is an admin.
Here is the adapted code for the Cloud Function:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const FieldValue = require('firebase-admin').firestore.FieldValue;
admin.initializeApp();
class InvalidRoleError extends Error {
constructor(message) {
super(message);
this.message = message;
this.type = 'InvalidRoleError';
}
}
function roleIsValid(role) {
const validRoles = ['editor', 'author']; //To be adapted with your own list of roles
return validRoles.includes(role);
}
exports.createUser = functions.https.onCall(async (data, context) => {
try {
//Checking that the new user role is valid
const role = data.role;
if (!roleIsValid(role)) {
throw new InvalidRoleError('The "' + role + '" role is not a valid role');
}
const userCreationRequest = {
userDetails: data,
status: 'Pending',
createdOn: FieldValue.serverTimestamp()
}
const userCreationRequestRef = await admin.firestore().collection("userCreationRequests").add(userCreationRequest);
const newUser = {
email: data.email,
emailVerified: false,
password: data.password,
displayName: data.firstName + ' ' + data.lastName,
disabled: false
}
const userRecord = await admin
.auth()
.createUser(newUser);
const userId = userRecord.uid;
const claims = {};
claims[role] = true;
await admin.auth().setCustomUserClaims(userId, claims);
await admin.firestore().collection("users").doc(userId).set(data);
await userCreationRequestRef.update({ status: 'Treated' });
return { result: 'The new user has been successfully created.' };
} catch (error) {
if (error.type === 'InvalidRoleError') {
throw new functions.https.HttpsError('failed-precondition', error.message);
} else {
throw new functions.https.HttpsError('internal', error.message);
}
}
});
Source:stackexchange.com