blob: c6dabaaf372b353c291ed161197ac8535693ebcf (
plain) (
tree)
|
|
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const cors = require('cors')({ origin: true });
admin.initializeApp();
// Function to add or update user roles
exports.addUserRole = functions.https.onCall(async (data, context) => {
// Verify that the request is made by an authenticated admin user
if (!context.auth || !context.auth.token.admin) {
throw new functions.https.HttpsError('permission-denied', 'Only admins can add user roles.');
}
const email = data.email;
const role = data.role;
try {
const user = await admin.auth().getUserByEmail(email);
await admin.auth().setCustomUserClaims(user.uid, { role: role });
return { message: `Success! ${email} has been made an ${role}` };
} catch (error) {
return { error: error.message };
}
});
// Function to get user roles
exports.getUserRoles = functions.https.onRequest(async (req, res) => {
cors(req, res, async () => {
const users = [];
try {
const listUsersResult = await admin.auth().listUsers();
listUsersResult.users.forEach((userRecord) => {
users.push({
email: userRecord.email,
role: userRecord.customClaims ? userRecord.customClaims.role : 'user'
});
});
res.status(200).send(users);
} catch (error) {
res.status(500).send({ error: error.message });
}
});
});
|