import logging import requests logger = logging.getLogger("authentik") # Ensure flow is only run during oauth logins via Github if context["source"].provider_type != "github": debug("Not a GitHub login attempt, skipping organization check") return True logger.debug(f"Source: {context['source']}") # The organization that users must be a member of accepted_org = "GridPane-Dev" try: # Get the user-source connection object from the context, and get the access token if "goauthentik.io/sources/connection" not in context: logger.error("No source connection found in context") return False connection = context["goauthentik.io/sources/connection"] access_token = connection.access_token # We also access the user info authentik already retrieved, to get the correct username if "oauth_userinfo" not in context: logger.error("No oauth_userinfo found in context") return False github_userinfo = context["oauth_userinfo"] logger.debug(f"GitHub user info: {github_userinfo}") if "login" not in github_userinfo: logger.error("No login found in GitHub user info") return False # GitHub API request to get user's organizations orgs_response = requests.get( "https://api.github.com/user/orgs", headers={ "Authorization": f"Bearer {access_token}", "Accept": "application/vnd.github.v3+json" } ) if orgs_response.status_code != 200: logger.error(f"GitHub API error: {orgs_response.status_code} - {orgs_response.text}") ak_message(f"Failed to verify GitHub organization membership. Please contact support.") return False orgs = orgs_response.json() logger.debug(f"Organizations: {orgs}") # Check if user is a member of the accepted organization user_matched = any(org['login'] == accepted_org for org in orgs) if not user_matched: logger.info(f"User '{github_userinfo['login']}' is not a member of organization '{accepted_org}'") ak_message(f"Access denied: You are not a member of the '{accepted_org}' GitHub organization.") return False logger.info(f"User '{github_userinfo['login']}' is a member of organization '{accepted_org}', allowing login") return True except Exception as e: logger.exception(f"Error checking GitHub organization membership: {e}") ak_message("An error occurred while verifying your GitHub organization membership. Please contact support.") return False