You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
2.3 KiB

  1. import requests
  2. from django.conf import settings
  3. from social_core.backends.azuread_tenant import AzureADTenantOAuth2
  4. from social_core.backends.github import GithubOAuth2
  5. # noinspection PyUnusedLocal
  6. def fetch_github_permissions(strategy, details, user=None, is_new=False, *args, **kwargs):
  7. org_name = getattr(settings, 'GITHUB_ADMIN_ORG_NAME', '')
  8. team_name = getattr(settings, 'GITHUB_ADMIN_TEAM_NAME', '')
  9. if not user or not isinstance(kwargs['backend'], GithubOAuth2) or not org_name or not team_name:
  10. return
  11. response = requests.post(
  12. url='https://api.github.com/graphql',
  13. headers={
  14. 'Authorization': 'Bearer {}'.format(kwargs['response']['access_token']),
  15. },
  16. json={
  17. 'query': '''
  18. query($userName: String!, $orgName: String!, $teamName: String!) {
  19. organization(login: $orgName) {
  20. teams(query: $teamName, userLogins: [$userName], first: 1) {
  21. nodes {
  22. name
  23. }
  24. }
  25. }
  26. }
  27. ''',
  28. 'variables': {
  29. 'userName': details['username'],
  30. 'orgName': org_name,
  31. 'teamName': team_name,
  32. }
  33. }
  34. )
  35. response.raise_for_status()
  36. response = response.json()
  37. is_superuser = {'name': team_name} in response['data']['organization']['teams']['nodes']
  38. if user.is_superuser != is_superuser:
  39. user.is_superuser = is_superuser
  40. user.save()
  41. # noinspection PyUnusedLocal
  42. def fetch_azuread_permissions(strategy, details, user=None, is_new=False, *args, **kwargs):
  43. group_id = getattr(settings, 'AZUREAD_ADMIN_GROUP_ID', '')
  44. if not user or not isinstance(kwargs['backend'], AzureADTenantOAuth2) or not group_id:
  45. return
  46. response = requests.post(
  47. url='https://graph.microsoft.com/v1.0/me/checkMemberGroups',
  48. headers={
  49. 'Authorization': 'Bearer {}'.format(kwargs['response']['access_token']),
  50. },
  51. json={
  52. 'groupIds': [group_id]
  53. }
  54. )
  55. response.raise_for_status()
  56. response = response.json()
  57. is_superuser = group_id in response['value']
  58. if user.is_superuser != is_superuser:
  59. user.is_superuser = is_superuser
  60. user.save()