error uploading an app using a js module.

abbas izadipour 205 Reputation points
2024-07-31T16:52:42.3266667+00:00

I am working on a Microsoft bot project, a multi-tenant solution we'll call Project A. The project is functioning well in all intended aspects. Currently, I am adding a new module to this project. This module is designed to be called by an API in my index.js file and should perform the following actions:

  1. Receive a tenantId, a UPN, and a teamName.
  2. Create a new team within the given tenantId named teamName with the user identified by the provided UPN as the owner and only member.
  3. Upload an application using the application's ID from the app catalog.

Here is the code I have written for this purpose:

require('dotenv').config({ path: '.env.local' }); // Load environment variables from .env.local
const authenticate = require('./auth');
const fetch = require('node-fetch');
async function createTeamAndInstallApp(tenantId, teamName, userUPN) {
    console.log('Someone called me to create a team and install an app');
    try {
        const token = await authenticate(tenantId);
        const headers = {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
        };
        // Step 1: Create a new team
        const createTeamUrl = `https://graph.microsoft.com/v1.0/teams`;
        const createTeamBody = JSON.stringify({
            "template@odata.bind": "https://graph.microsoft.com/v1.0/teamsTemplates('standard')",
            "displayName": teamName,
            "description": `Team created for ${teamName}`,
            "members": [
                {
                    "@odata.type": "#microsoft.graph.aadUserConversationMember",
                    "roles": ["owner"],
                    "user@odata.bind": `https://graph.microsoft.com/v1.0/users/${userUPN}`
                }
            ]
        });
        const createTeamResponse = await fetch(createTeamUrl, {
            method: 'POST',
            headers: headers,
            body: createTeamBody
        });
        if (createTeamResponse.status !== 202) {
            const errorText = await createTeamResponse.text();
            throw new Error(`Error creating team: ${createTeamResponse.statusText}, ${errorText}`);
        }
        console.log("addNewTeamjs: Here is create team response header: \n", createTeamResponse.headers);
        const locationUrl = createTeamResponse.headers.get('location');
        console.log("addNewTeamjs: Here is the location URL: ", locationUrl);
        if (!locationUrl) {
            throw new Error('No location header found in the response');
        }
        // Extract the teamId from the location URL
        const teamIdMatch = locationUrl.match(/teams\('(.+?)'\)/);
        if (!teamIdMatch) {
            throw new Error('Could not extract teamId from location URL');
        }
        const teamId = teamIdMatch[1];
        console.log('Extracted teamId:', teamId);
        // Step 2: Install the app to the team
        const appId = process.env.BOT_ID; // Use appId from environment variables
        console.log("here is the appId: ", appId);
        const installAppUrl = `https://graph.microsoft.com/v1.0/teams/${teamId}/installedApps`;
        const installAppBody = JSON.stringify({
            "teamsApp@odata.bind": `https://graph.microsoft.com/v1.0/appCatalogs/teamsApps/${appId}`
        });
        const installAppResponse = await fetch(installAppUrl, {
            method: 'POST',
            headers: headers,
            body: installAppBody
        });
        const installAppResponseText = await installAppResponse.text();
        if (!installAppResponse.ok) {
            throw new Error(`Error installing app: ${installAppResponse.statusText}, ${installAppResponseText}`);
        }
        let installAppData;
        try {
            installAppData = installAppResponseText ? JSON.parse(installAppResponseText) : {};
        } catch (err) {
            throw new Error(`Failed to parse response as JSON: ${installAppResponseText}`);
        }
        console.log('App installed:', installAppData);
        return {
            teamId,
            appId: installAppData.id
        };
    } catch (err) {
        console.error('Error creating team and installing app:', err);
        throw err;
    }
}
module.exports = createTeamAndInstallApp;


Testing the Module and Results:

I am using my Microsoft developer account as the testing environment. I have registered Project A in my developer account, and all my tests are conducted within this account. To test the new module and API, I select an existing application from the app catalog via my admin team and use its appId in my module. The module successfully creates a new team and installs the application without any issues.

Before proceeding to the next step of testing, I want to emphasize that Project A has been tested multiple times by manually uploading the manifest zip package to various teams within my developer account.

Now, I upload Project A's manifest zip package file through the Teams admin center using "Teams app," "Manage apps," and then use Project A's app ID as the appId in the module. Upon calling the API, the module creates the new team but returns the following error:

Error creating team and installing app: Error: Error installing app: Bad Request, {"error":{"code":"BadRequest","message":"The required permissions have not been consented to by the caller.","innerError":{"code":"InvalidRequest","message":"The required permissions have not been consented to by the caller.","details":[],"date":"2024-07-31T16:17:32","request-id":"91630db4-47d2-44f1-b9bd-59713687220c","client-request-id":"91630db4-47d2-44f1-b9bd-59713687220c"}}}


Question:

My understanding of this error is that the app’s permission to upload an application has not been consented to by the admin. However, the permissions are consented, and the app can upload other existing apps without any issues. Could someone help me understand why this error is occurring and how to resolve it?

Thank you in advance for your assistance!

Microsoft Teams Development
Microsoft Teams Development
Microsoft Teams: A Microsoft customizable chat-based workspace.Development: The process of researching, productizing, and refining new or existing technologies.
3,086 questions
{count} votes