Skip to content

Commit

Permalink
Re-sync GitHub (RemoteRepository and RemoteOrganization) on webhook
Browse files Browse the repository at this point in the history
Add `member` event when creating the Read the Docs' webhook on each repository
imported under Read the Docs.

This webhook will communicate back to us when a collaborator was
added/removed/changed from that repository in particular. This allow us to
trigger the re-sync method for the GitHub service on that user and
create/delete/change `RemoteRepository` objects for that user.

Examples,

* user is removed from having access to a repository -> remove RemoteRepository
* user is added access to a repository -> create RemoteRepository
* user is removed admin access but keep read access -> `.admin=False`
  • Loading branch information
humitos committed Oct 21, 2021
1 parent b08f6a5 commit 97495ba
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
14 changes: 14 additions & 0 deletions readthedocs/api/v2/views/integrations.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@
import logging
import re

from allauth.socialaccount.providers.github.provider import GitHubProvider
from allauth.socialaccount.models import SocialAccount

from django.shortcuts import get_object_or_404
from rest_framework import permissions, status
from rest_framework.exceptions import NotFound, ParseError
Expand Down Expand Up @@ -33,6 +36,7 @@

GITHUB_EVENT_HEADER = 'HTTP_X_GITHUB_EVENT'
GITHUB_SIGNATURE_HEADER = 'HTTP_X_HUB_SIGNATURE'
GITHUB_MEMBER = 'member'
GITHUB_PUSH = 'push'
GITHUB_PULL_REQUEST = 'pull_request'
GITHUB_PULL_REQUEST_OPENED = 'opened'
Expand Down Expand Up @@ -452,6 +456,16 @@ def handle_webhook(self):
except KeyError:
raise ParseError('Parameter "ref" is required')

# Re-sync repositories for the user if any permission has changed
if event == GITHUB_MEMBER:
uid = self.data.get('member').get('id')
socialaccount = SocialAccount.objects.get(
provider=GitHubProvider.id,
uid=uid,
)
service = GitHubService(user=socialaccount.user, account=socialaccount)
service.sync()

return None

def _normalize_ref(self, ref):
Expand Down
2 changes: 1 addition & 1 deletion readthedocs/oauth/services/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ def get_webhook_data(self, project, integration):
'secret': integration.secret,
'content_type': 'json',
},
'events': ['push', 'pull_request', 'create', 'delete'],
'events': ['push', 'pull_request', 'create', 'delete', 'member'],
})

def get_provider_data(self, project, integration):
Expand Down

0 comments on commit 97495ba

Please sign in to comment.