🔍 Code Extractor

function main_v34

Maturity: 44

Interactive CLI helper function that generates and displays instructions for granting SharePoint app permissions to an Azure AD application.

File:
/tf/active/vicechatdev/SPFCsync/grant_sharepoint_access.py
Lines:
24 - 85
Complexity:
moderate

Purpose

This function serves as a guided wizard to help administrators grant SharePoint permissions to an Azure AD app. It loads configuration, parses SharePoint site URLs, extracts tenant information, and provides step-by-step instructions with the necessary URLs and XML configuration for granting app-only permissions at the site collection level. It offers both the direct appinv.aspx method and an alternative Admin Center approach.

Source Code

def main():
    """Generate the app permission grant URL."""
    print("SharePoint App Permission Grant Helper")
    print("=" * 50)
    
    config = load_config()
    if not config:
        print("❌ Could not load configuration")
        return 1
    
    site_url = config.get('SHAREPOINT_SITE_URL', '')
    client_id = config.get('AZURE_CLIENT_ID', '')
    
    if not site_url or not client_id:
        print("❌ Missing SHAREPOINT_SITE_URL or AZURE_CLIENT_ID in configuration")
        return 1
    
    # Extract site components
    if '.sharepoint.com/sites/' in site_url:
        base_url = site_url.split('/sites/')[0]
        site_name = site_url.split('/sites/')[-1]
        tenant = base_url.split('https://')[-1].split('.sharepoint.com')[0]
    else:
        print("❌ Cannot parse SharePoint site URL")
        return 1
    
    print(f"Site URL: {site_url}")
    print(f"Tenant: {tenant}")
    print(f"Client ID: {client_id}")
    print()
    
    # Generate the app permission grant URL
    app_grant_url = f"{base_url}/_layouts/15/appinv.aspx"
    
    print("🔗 SharePoint App Permission Grant")
    print("-" * 30)
    print(f"1. Open this URL in your browser: {app_grant_url}")
    print()
    print("2. Fill in the form with these values:")
    print(f"   App Id: {client_id}")
    print("   App Domain: (leave blank)")
    print("   App Redirect URL: (leave blank)")
    print()
    print("3. Click 'Generate' to auto-fill the Title and App Domain")
    print()
    print("4. In the Permission Request XML field, paste this:")
    print()
    print("""<AppPermissionRequests AllowAppOnlyPolicy="true">
  <AppPermissionRequest Scope="http://sharepoint/content/sitecollection" Right="Read" />
</AppPermissionRequests>""")
    print()
    print("5. Click 'Create' and then 'Trust It' when prompted")
    print()
    print("📋 Alternative Method: Admin Center")
    print("-" * 30)
    print("If the above doesn't work, try this:")
    print(f"1. Go to SharePoint Admin Center")
    print(f"2. Navigate to More features → Apps → App Catalog")
    print(f"3. Add your app with Client ID: {client_id}")
    print()
    print("After granting permissions, test again with:")
    print("python test_connections.py")

Return Value

Returns an integer exit code: 1 if configuration loading fails, missing required settings, or URL parsing fails; implicitly returns None (0) on successful execution. The return value indicates whether the helper completed successfully.

Required Imports

import os

Usage Example

# Assuming load_config() function exists and returns proper config
# Example config.py or .env should contain:
# SHAREPOINT_SITE_URL=https://contoso.sharepoint.com/sites/mysite
# AZURE_CLIENT_ID=12345678-1234-1234-1234-123456789abc

if __name__ == '__main__':
    exit_code = main()
    if exit_code:
        print('Failed to generate permission grant instructions')
    else:
        print('Instructions displayed successfully')

Best Practices

  • Ensure load_config() function is implemented before calling main()
  • The SharePoint site URL must follow the exact format: https://{tenant}.sharepoint.com/sites/{sitename}
  • User must have SharePoint administrator privileges to grant app permissions
  • The function is designed for interactive terminal use and prints directly to stdout
  • Should be called as the entry point of a script (if __name__ == '__main__')
  • The generated permission XML grants Read access at site collection scope - modify if different permissions are needed
  • After running this helper, users should execute test_connections.py to verify permissions were granted successfully

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function provide_admin_instructions 75.7% similar

    Displays comprehensive administrative instructions for fixing SharePoint app-only authentication issues by loading configuration and presenting multiple resolution options.

    From: /tf/active/vicechatdev/SPFCsync/check_tenant_config.py
  • function main_v47 71.8% similar

    Entry point function that runs a SharePoint permission diagnostic tool, testing different authentication scopes and providing troubleshooting guidance.

    From: /tf/active/vicechatdev/SPFCsync/diagnose_permissions.py
  • function test_tenant_admin_center_approach 67.4% similar

    Displays detailed troubleshooting instructions for resolving SharePoint 'Unsupported app only token' errors by providing three alternative configuration approaches through tenant admin center.

    From: /tf/active/vicechatdev/SPFCsync/diagnose_permissions.py
  • function main_v43 67.0% similar

    Orchestrates a comprehensive SharePoint connection diagnostic tool that validates Azure AD authentication and SharePoint access by running multiple tests and reporting results.

    From: /tf/active/vicechatdev/SPFCsync/diagnose_sharepoint.py
  • function main_v44 65.0% similar

    Diagnostic function that tests SharePoint tenant configuration by checking Microsoft Graph API access and provides recommendations based on the results.

    From: /tf/active/vicechatdev/SPFCsync/check_tenant_config.py
← Back to Browse