Skip to content

谷歌云子账号 API

web 控制台

谷歌云子账号的创建与授权在控制台页面上分属两块区域:

python sdk 代码示例

创建用户

python
def get_user(email):
    project = 'test-xxx'
    ga = GoogleAPI(project)
    scopes = ['https://www.googleapis.com/auth/admin.directory.user']
    service = ga.discovery_build('admin', 'directory_v1', scopes)
    try:
        res = service.users().get(userKey=email).execute()
        return res
    except Exception as e:
        if 'Resource Not Found' in str(e):
            return None
        raise Exception('获取用户异常')
python
def create_user_or_update(email, name, password):
    """创建或更新用户
    更新时 email 作为唯一标识符
    name 为中文姓名
    """
    project = 'test-xxx'
    ga = GoogleAPI(project)
    scopes = ['https://www.googleapis.com/auth/admin.directory.user']
    service = ga.discovery_build('admin', 'directory_v1', scopes)

    info = {
      'primaryEmail': email,
      'password': password,
      'changePasswordAtNextLogin': False,
      'name': {
          'familyName': name[0],
          'givenName': name[1:],
          'fullName': name,
          'displayName': name
      },
    }
    user = get_user(email)
    if user is None:
        res = service.users().insert(body=info).execute()
        action = 'create'
        logger.info(f'用户 {email} 创建成功')
    else:
        res = service.users().update(userKey=email, body=info).execute()
        action = 'update'
        logger.info(f'用户 {email} 更新成功')
    logger.info(res)
    return action
python
import httplib2
import google_auth_httplib2

from googleapiclient import discovery
from google.oauth2 import service_account
from sanic import Sanic


class GoogleAPI():
    def __init__(self, project):
        self.app = Sanic.get_app()
        self.project = project

    def _get_proxy_http(self):
        http = httplib2.Http(proxy_info=httplib2.ProxyInfo(
            httplib2.socks.PROXY_TYPE_HTTP,
            self.app.config.GOOGLE_HTTP_PROXY_IP,
            self.app.config.GOOGLE_HTTP_PROXY_PORT
        ))
        return http

    def _get_credentials(self, scopes):
        if scopes is None:
            scopes = ['https://www.googleapis.com/auth/cloud-platform']
        google_sa_key = f'google_sa_{self.project}'.upper()
        info = self.app.config[google_sa_key]
        credentials = service_account.Credentials.from_service_account_info(
            info, scopes=scopes)
        if 'admin.directory' in scopes[0]:
            credentials = credentials.with_subject('op@xxx.com')
        return credentials

    def discovery_build(self, product_code, product_version, scopes=None):
        credentials = self._get_credentials(scopes)
        http = self._get_proxy_http()
        authorized_http = google_auth_httplib2.AuthorizedHttp(
            credentials, http=http)
        service = discovery.build(
            product_code, product_version,
            # "compute", "v1",
            http=authorized_http,
        )
        # response = service.instances().list(
        #     project='test-xxx', zone='us-east4-c').execute()
        return service
  • 用户的管理是在管理页面进行管理
  • 用户操作是在 admin api 域中进行
  • scopes 必须指定为 ['https://www.googleapis.com/auth/admin.directory.user']
  • 新建用户时先检测用户是否已存在,不存在就新建,存在则更新
  • admin api 域的调用还需要进行一个操作:将全网域授权委派给服务帐号;上述 GoogleAPI 代码中已集成此操作

分配权限

python
def get_iam_policy(project):
    """获取指定项目的 iam 用户&权限信息"""
    ga = GoogleAPI(project)
    service = ga.discovery_build('cloudresourcemanager', 'v1')
    res = service.projects().getIamPolicy(resource=project).execute()
    return res
python
def iam_add_member_to_roles(project, roles, member):
    """往指定的角色组中添加成员
    其实就是为用户添加权限
    role: 'roles/viewer'
    member: 'user:xxx@xxx.com'
    """
    ga = GoogleAPI(project)
    service = ga.discovery_build('cloudresourcemanager', 'v1')
    policy = get_iam_policy(project)
    for binding in policy['bindings']:
        if binding['role'] in roles:
            binding['members'].append(member)
    policy = service.projects().setIamPolicy(
        resource=project,
        body={'policy': policy}
    ).execute()
    logger.debug(policy)
    logger.info(f'IAM 用户 {member} 添加成功')
  • 用户权限是在 IAM 页面进行管理
  • IAM 策略操作是在 cloudresourcemanager api 域中进行
  • 谷歌云中给用户添加权限是将用户添加到指定的策略角色中,比如只读权限就是将用户添加到 roles/viewer 角色中