aboutsummaryrefslogtreecommitdiffstats
path: root/backend/functions/index.js
blob: c6dabaaf372b353c291ed161197ac8535693ebcf (plain) (blame)
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
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 });
    }
  });
});