From 7dfbe0f363a434cfda5f9be996d194f03c36879c Mon Sep 17 00:00:00 2001 From: Biswakalyan Bhuyan Date: Wed, 31 Jul 2024 12:16:49 +0530 Subject: new project --- backend/functions/index.js | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 backend/functions/index.js (limited to 'backend/functions/index.js') diff --git a/backend/functions/index.js b/backend/functions/index.js new file mode 100644 index 0000000..c6dabaa --- /dev/null +++ b/backend/functions/index.js @@ -0,0 +1,43 @@ +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 }); + } + }); +}); -- cgit v1.2.3-59-g8ed1b