Skip to content

Instantly share code, notes, and snippets.

@ctoestreich
Created January 8, 2025 15:48
Show Gist options
  • Save ctoestreich/8f919a9177b7d83bd2c3511253a27285 to your computer and use it in GitHub Desktop.
Save ctoestreich/8f919a9177b7d83bd2c3511253a27285 to your computer and use it in GitHub Desktop.
Adding webhook to auto-approve new child teams

Here’s a Node.js implementation for a GitHub webhook listener that automates child team approval when a new team is added to a hierarchy:

Prerequisites

  1. Install Node.js.
  2. Use express to create the server and axios for HTTP requests.
  3. Install required packages:
    npm install express body-parser axios

Webhook Listener in Node.js

const express = require('express');
const bodyParser = require('body-parser');
const axios = require('axios');

const app = express();
const PORT = 5000;

const GITHUB_TOKEN = "your_github_token";
const GITHUB_API_URL = "https://api.github.com/graphql";

app.use(bodyParser.json());

// Webhook endpoint
app.post('/webhook', async (req, res) => {
    const payload = req.body;

    if (payload.action === 'created') {
        const teamSlug = payload.team.slug;
        const organization = payload.organization.login;
        const parentTeamSlug = payload.team.parent?.slug;

        if (parentTeamSlug) {
            try {
                await approveChildTeam(organization, teamSlug, parentTeamSlug);
                console.log(`Successfully approved child team: ${teamSlug}`);
            } catch (error) {
                console.error(`Failed to approve child team: ${teamSlug}`, error.response?.data || error.message);
            }
        }
    }

    res.status(200).send('Webhook received and processed.');
});

// Function to approve child team relationship
async function approveChildTeam(organization, childTeamSlug, parentTeamSlug) {
    const mutation = `
    mutation AddTeamToParent($organization: String!, $parentSlug: String!, $childSlug: String!) {
        updateTeamParent(input: {
            organization: $organization,
            parentTeamSlug: $parentSlug,
            teamSlug: $childSlug
        }) {
            team {
                id
                name
                parentTeam {
                    id
                    name
                }
            }
        }
    }`;

    const variables = {
        organization,
        parentSlug: parentTeamSlug,
        childSlug: childTeamSlug,
    };

    const headers = {
        Authorization: `Bearer ${GITHUB_TOKEN}`,
        'Content-Type': 'application/json',
    };

    const response = await axios.post(
        GITHUB_API_URL,
        { query: mutation, variables },
        { headers }
    );

    return response.data;
}

// Start the server
app.listen(PORT, () => {
    console.log(`Webhook listener is running on port ${PORT}`);
});

Steps to Use

  1. Set Up Webhook in GitHub:

    • Go to your Organization Settings > Webhooks.
    • Add a new webhook with the URL http://your-server-ip-or-domain:5000/webhook.
    • Choose application/json as the content type.
    • Select the team event.
  2. Run the Script: Start the Node.js server:

    node index.js
  3. Add a New Team: When a new team is created and set as a child of another team, the webhook will automatically attempt to approve the relationship.


Notes:

  • Ensure the GitHub token has admin:org permissions.
  • Deploy this script to a production-grade server if it needs to handle live events.
  • Add logging or error-handling mechanisms for better debugging and monitoring.
  • If deploying to a public server, set up proper security measures (e.g., validating the webhook secret).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment