|
| 1 | +from collections.abc import Generator |
| 2 | + |
| 3 | +from office365.sharepoint.client_context import ClientContext # type: ignore[import-untyped] |
| 4 | + |
| 5 | +from ee.onyx.db.external_perm import ExternalUserGroup |
| 6 | +from ee.onyx.external_permissions.sharepoint.permission_utils import ( |
| 7 | + get_sharepoint_external_groups, |
| 8 | +) |
| 9 | +from onyx.connectors.sharepoint.connector import acquire_token_for_rest |
| 10 | +from onyx.connectors.sharepoint.connector import SharepointConnector |
| 11 | +from onyx.db.models import ConnectorCredentialPair |
| 12 | +from onyx.utils.logger import setup_logger |
| 13 | + |
| 14 | +logger = setup_logger() |
| 15 | + |
| 16 | + |
| 17 | +def sharepoint_group_sync( |
| 18 | + tenant_id: str, |
| 19 | + cc_pair: ConnectorCredentialPair, |
| 20 | +) -> Generator[ExternalUserGroup, None, None]: |
| 21 | + """Sync SharePoint groups and their members""" |
| 22 | + |
| 23 | + # Get site URLs from connector config |
| 24 | + connector_config = cc_pair.connector.connector_specific_config |
| 25 | + |
| 26 | + # Create SharePoint connector instance and load credentials |
| 27 | + connector = SharepointConnector(**connector_config) |
| 28 | + connector.load_credentials(cc_pair.credential.credential_json) |
| 29 | + |
| 30 | + if not connector.msal_app: |
| 31 | + raise RuntimeError("MSAL app not initialized in connector") |
| 32 | + |
| 33 | + if not connector.sp_tenant_domain: |
| 34 | + raise RuntimeError("Tenant domain not initialized in connector") |
| 35 | + |
| 36 | + # Get site descriptors from connector (either configured sites or all sites) |
| 37 | + site_descriptors = connector.site_descriptors or connector.fetch_sites() |
| 38 | + |
| 39 | + if not site_descriptors: |
| 40 | + raise RuntimeError("No SharePoint sites found for group sync") |
| 41 | + |
| 42 | + logger.info(f"Processing {len(site_descriptors)} sites for group sync") |
| 43 | + |
| 44 | + msal_app = connector.msal_app |
| 45 | + sp_tenant_domain = connector.sp_tenant_domain |
| 46 | + # Process each site |
| 47 | + for site_descriptor in site_descriptors: |
| 48 | + logger.debug(f"Processing site: {site_descriptor.url}") |
| 49 | + |
| 50 | + # Create client context for the site using connector's MSAL app |
| 51 | + ctx = ClientContext(site_descriptor.url).with_access_token( |
| 52 | + lambda: acquire_token_for_rest(msal_app, sp_tenant_domain) |
| 53 | + ) |
| 54 | + |
| 55 | + # Get external groups for this site |
| 56 | + external_groups = get_sharepoint_external_groups(ctx, connector.graph_client) |
| 57 | + |
| 58 | + # Yield each group |
| 59 | + for group in external_groups: |
| 60 | + logger.debug( |
| 61 | + f"Found group: {group.id} with {len(group.user_emails)} members" |
| 62 | + ) |
| 63 | + yield group |
0 commit comments