Python中如何判断谷歌账号为普通账号或Google Workspace关联账号?
问题背景与解决方案
现有应用流程
- 通过Google OAuth(集成Auth0登录)完成用户登录
- 展示Google Sheets列表链接,登录用户可点击打开
- 用户点击链接后跳转至iframe展示页面
- 通过Python的
gspread模块(服务账号认证)获取表格共享权限列表,若登录用户在列表内则展示iframe,否则显示错误提示
新需求问题
允许平台特定用户通过gspread.share()共享Google Sheets,但仅支持分享给普通谷歌账号,禁止分享给关联任意组织的Google Workspace账号。目前Google Admin SDK仅能检查同一Workspace下的用户,需实现判断任意给定账号类型的Python方案。
可行实现方案
可以借助Google People API判断账号类型:普通谷歌账号的个人资料中无关联的官方组织信息,而Workspace账号会包含所属组织的域名等条目。
步骤1:启用API并配置凭据
在Google Cloud Console中启用People API,使用与gspread相同的服务账号密钥(保持认证体系一致),并为服务账号添加https://www.googleapis.com/auth/contacts.readonly权限范围。
步骤2:Python代码实现
使用google-api-python-client模块调用API查询账号信息,解析返回结果判断类型:
from google.oauth2 import service_account from googleapiclient.discovery import build # 替换为你的服务账号密钥路径 SERVICE_ACCOUNT_KEY = 'service-account-key.json' SCOPES = ['https://www.googleapis.com/auth/contacts.readonly'] def is_regular_google_account(email): # 初始化People API客户端 creds = service_account.Credentials.from_service_account_file( SERVICE_ACCOUNT_KEY, scopes=SCOPES) people_service = build('people', 'v1', credentials=creds) try: # 获取账号的组织信息 person_data = people_service.people().get( resourceName=f'people/{email}', personFields='organizations' ).execute() # 检查是否存在带域名的官方组织(Workspace账号特征) organizations = person_data.get('organizations', []) has_workspace_org = any(org.get('domain') for org in organizations) return not has_workspace_org except Exception as e: # 处理账号不存在或查询失败的情况 print(f"账号查询异常: {str(e)}") return False # 使用示例 target_email = 'user@gmail.com' if is_regular_google_account(target_email): # 执行gspread共享操作 # gspread_client.open("目标表格").share(target_email, perm_type='user', role='reader') print("允许共享:普通谷歌账号") else: print("禁止共享:该账号为Google Workspace账号或无效账号")
关键说明
- 仅需
contacts.readonly权限即可获取组织信息,无需过度授权。 - 通过
domain字段过滤自定义组织:普通用户手动添加的组织通常无域名,只有Workspace账号的官方组织会包含所属域的域名。 - 异常处理需覆盖账号不存在、API调用失败等场景,避免流程中断。
内容的提问来源于stack exchange,提问作者Pranav N
相关产品推荐
相关产品推荐

