Skip to content

Commit

Permalink
Merge pull request #69 from github/primetheus/bugfix
Browse files Browse the repository at this point in the history
Fix multi-installation bug
  • Loading branch information
Jared Murrell authored Mar 25, 2021
2 parents ff43e8c + 227c4a5 commit 6b8f735
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 28 deletions.
72 changes: 51 additions & 21 deletions app.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import atexit
import os
import time
import json
from distutils.util import strtobool
from pprint import pprint

from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
Expand Down Expand Up @@ -46,11 +46,17 @@ def sync_team(client=None, owner=None, team_id=None, slug=None):
:param slug:
:return:
"""
print("-------------------------------")
print(f"Processing Team: {slug}")
org = client.organization(owner)
team = org.team(team_id)
custom_map = load_custom_map()
directory_group = custom_map[slug] if slug in custom_map else slug
directory_members = directory_group_members(group=directory_group)
try:
directory_group = custom_map[slug] if slug in custom_map else slug
directory_members = directory_group_members(group=directory_group)
except Exception as e:
directory_members = []
print(e)
team_members = github_team_members(
client=client, owner=owner, team_id=team_id, attribute="username"
)
Expand All @@ -59,7 +65,7 @@ def sync_team(client=None, owner=None, team_id=None, slug=None):
)
if TEST_MODE:
print("Skipping execution due to TEST_MODE...")
pprint(compare)
print(json.dumps(compare, indent=2))
else:
try:
execute_sync(org=org, team=team, slug=slug, state=compare)
Expand All @@ -79,8 +85,12 @@ def directory_group_members(group=None):
:return: group_members
:rtype: list
"""
members = directory.get_group_members(group_name=group)
group_members = [member for member in members]
try:
members = directory.get_group_members(group_name=group)
group_members = [member for member in members]
except Exception as e:
group_members = []
print(e)
return group_members


Expand Down Expand Up @@ -171,13 +181,13 @@ def execute_sync(org, team, slug, state):
for user in state["action"]["add"]:
# Validate that user is in org
if org.is_member(user):
pprint(f"Adding {user} to {slug}")
print(f"Adding {user} to {slug}")
team.add_or_update_membership(user)
else:
pprint(f"Skipping {user} as they are not part of the org")
print(f"Skipping {user} as they are not part of the org")

for user in state["action"]["remove"]:
pprint(f"Removing {user} from {slug}")
print(f"Removing {user} from {slug}")
team.revoke_membership(user)


Expand Down Expand Up @@ -220,6 +230,18 @@ def load_custom_map(file="syncmap.yml"):
return syncmap


def get_app_installations():
"""
Get a list of installations for this app
:return:
"""
with app.app_context() as ctx:
c = ctx.push()
gh = GitHubApp(c)
installations = gh.app_client.app_installations
return installations


@scheduler.scheduled_job(
trigger=CronTrigger.from_crontab(CRON_INTERVAL), id="sync_all_teams"
)
Expand All @@ -228,22 +250,30 @@ def sync_all_teams():
Lookup teams in a GitHub org and synchronize all teams with your user directory
:return:
"""
pprint(f'Syncing all teams: {time.strftime("%A, %d. %B %Y %I:%M:%S %p")}')
with app.app_context() as ctx:
c = ctx.push()
gh = GitHubApp(c)
installations = gh.app_client.app_installations
for i in installations():
print(f'Syncing all teams: {time.strftime("%A, %d. %B %Y %I:%M:%S %p")}')
installations = get_app_installations()
for i in installations():
print("========================================================")
print(f"## Processing Organization: {i.account['login']}")
print("========================================================")
try:
gh = GitHubApp(app.app_context().push())
client = gh.app_installation(installation_id=i.id)
org = client.organization(i.account["login"])
for team in org.teams():
sync_team(
client=client,
owner=i.account["login"],
team_id=team.id,
slug=team.slug,
)
try:
sync_team(
client=client, owner=org.login, team_id=team.id, slug=team.slug,
)
except Exception as e:
print(f"Organization: {org.login}")
print(f"Unable to sync team: {team.slug}")
print(f"DEBUG: {e}")
except Exception as e:
print(f"DEBUG: {e}")


sync_all_teams()

if __name__ == "__main__":
sync_all_teams()
Expand Down
17 changes: 10 additions & 7 deletions githubapp/azuread.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def get_access_token(self):
result = app.acquire_token_for_client(scopes=self.AZURE_APP_SCOPE)

if "access_token" in result:
print("Successfully authenticated!")
# print("Successfully authenticated!")
return result["access_token"]

else:
Expand All @@ -64,7 +64,7 @@ def get_group_members(self, token=None, group_name=None):
"""
Get a list of members for a given group
:param token:
:param group:
:param group_name:
:return:
"""
token = self.get_access_token() if not token else token
Expand All @@ -75,11 +75,14 @@ def get_group_members(self, token=None, group_name=None):
headers={"Authorization": f"Bearer {token}"},
).json()
# print("Graph API call result: %s" % json.dumps(graph_data, indent=2))
group_info = json.loads(json.dumps(graph_data, indent=2))["value"][0]
members = requests.get(
f'{self.AZURE_API_ENDPOINT}/groups/{group_info["id"]}/members',
headers={"Authorization": f"Bearer {token}"},
).json()["value"]
try:
group_info = json.loads(json.dumps(graph_data, indent=2))["value"][0]
members = requests.get(
f'{self.AZURE_API_ENDPOINT}/groups/{group_info["id"]}/members',
headers={"Authorization": f"Bearer {token}"},
).json()["value"]
except IndexError as e:
members = []
for member in members:
user_info = self.get_user_info(token=token, user=member["id"])
if self.AZURE_USER_IS_UPN:
Expand Down

0 comments on commit 6b8f735

Please sign in to comment.