Workbook: Reassign Ownership by Email (JavaScript)

View as Markdown

This script transfers ownership of all workbooks from one Sigma user to another using their email addresses.

Each section of the script has inline comments provided.

Refer to the Sigma REST API Recipes QuickStart for step-by-step instructions.

Example script

JavaScript
1// This script transfers ownership of all workbooks from one Sigma user to another using email addresses.
2
3// ---------------------------------------------
4// CONFIGURATION
5// ---------------------------------------------
6// 1: Load environment variables from a specific .env file for configuration
7require('dotenv').config({ path: '../.env' });
8
9// 2: Import the function to obtain a bearer token from the authenticate-bearer module
10const getBearerToken = require('../get-access-token');
11
12// 3: Import Axios for making HTTP requests
13const axios = require('axios');
14
15// 4: Load use-case specific variables from environment variables
16const baseURL = process.env.baseURL; // Your base URL
17
18// Old and new owners
19const OLD_OWNER_EMAIL = process.env.OLD_OWNER_EMAIL;
20const NEW_OWNER_EMAIL = process.env.NEW_OWNER_EMAIL;
21
22// ---------------------------------------------
23// MEMBER LOOKUP
24// ---------------------------------------------
25// Searches for a member by email address and returns their member ID
26async function getMemberIdByEmail(baseUrl, accessToken, email) {
27 try {
28 const url = `${baseUrl}/members?limit=120&search=${encodeURIComponent(email)}`;
29 const headers = {
30 accept: 'application/json',
31 authorization: `Bearer ${accessToken}`,
32 };
33
34 const response = await axios.get(url, { headers });
35 const data = response.data;
36 const entries = data.entries || [];
37
38 if (entries.length > 0) {
39 return entries[0].memberId; // Assuming unique email
40 } else {
41 console.error(`No member found with email: ${email}`);
42 return null;
43 }
44 } catch (error) {
45 console.error(`Failed to fetch member for ${email}`);
46 console.error(error.response ? error.response.data : error.message);
47 return null;
48 }
49}
50
51// ---------------------------------------------
52// LIST OWNED WORKBOOKS
53// ---------------------------------------------
54// Retrieves all workbooks owned by a specific member using pagination
55async function listAllOwnedWorkbooks(baseUrl, accessToken, ownerId) {
56 const ownedWorkbooks = {};
57 let page = 0;
58 const limit = 100;
59 let nextPage = true;
60
61 while (nextPage) {
62 try {
63 const url = `${baseUrl}/members/${ownerId}/files`;
64 const headers = {
65 accept: 'application/json',
66 authorization: `Bearer ${accessToken}`,
67 };
68
69 const response = await axios.get(url, {
70 headers,
71 params: { page, limit, typeFilters: 'workbook' },
72 });
73
74 const data = response.data;
75 const entries = data.entries || [];
76
77 entries.forEach((entry) => {
78 if (entry.ownerId === ownerId) {
79 ownedWorkbooks[entry.id] = {
80 name: entry.name,
81 url: entry.urlId,
82 };
83 }
84 });
85
86 if (data.nextPage) {
87 page += limit;
88 } else {
89 nextPage = false;
90 }
91 } catch (error) {
92 console.error('Failed to fetch workbooks');
93 console.error(error.response ? error.response.data : error.message);
94 break;
95 }
96 }
97
98 return ownedWorkbooks;
99}
100
101// ---------------------------------------------
102// TRANSFER OWNERSHIP
103// ---------------------------------------------
104// Main function that transfers all workbooks from old owner to new owner
105async function transferAllWorkbookOwnership(baseUrl, oldOwnerEmail, newOwnerEmail) {
106 // Get authentication token for API requests
107 const accessToken = await getBearerToken();
108
109
110 if (!accessToken) {
111 throw new Error('Could not obtain access token');
112 }
113
114
115 // Look up member IDs for both email addresses
116 const oldOwnerId = await getMemberIdByEmail(baseUrl, accessToken, oldOwnerEmail);
117 const newOwnerId = await getMemberIdByEmail(baseUrl, accessToken, newOwnerEmail);
118
119 if (!oldOwnerId || !newOwnerId) {
120 throw new Error('Could not obtain member IDs for provided email addresses');
121 }
122
123 // Get all workbooks owned by the old owner
124 const workbooksMap = await listAllOwnedWorkbooks(baseUrl, accessToken, oldOwnerId);
125
126 console.log(workbooksMap);
127 // Transfer ownership of each workbook to the new owner
128 for (const [workbookId, data] of Object.entries(workbooksMap)) {
129 console.log(`Transferring ownership : ${data.name} - ${data.url}`);
130
131 const url = `${baseUrl}/files/${workbookId}`;
132 const payload = { ownerId: newOwnerId };
133 const headers = {
134 accept: 'application/json',
135 'content-type': 'application/json',
136 authorization: `Bearer ${accessToken}`,
137 };
138
139 try {
140 const response = await axios.patch(url, payload, { headers });
141 if ([200, 201].includes(response.status)) {
142 console.log('Done');
143 } else {
144 console.error('Failed to transfer ownership');
145 console.error('Status Code:', response.status);
146 console.error('Response:', response.data);
147 }
148 } catch (error) {
149 console.error('Failed to transfer ownership');
150 console.error(error.response ? error.response.data : error.message);
151 }
152 }
153}
154
155// ---------------------------------------------
156// MAIN
157// ---------------------------------------------
158if (require.main === module) {
159 transferAllWorkbookOwnership(baseURL, OLD_OWNER_EMAIL, NEW_OWNER_EMAIL)
160 .then(() => console.log('\nBulk transfer complete.'))
161 .catch((err) => console.error('Script failed:', err.message));
162}
163
164// Export the main function for reuse in other modules
165module.exports = transferAllWorkbookOwnership;

Endpoints used

  1. Get authentication token getBearerToken function
  2. List members
  3. List files for a member
  4. Update files