繁体   English   中英

使用 Google Admin SDK 中的 google app 脚本自动创建用户

[英]Automate user creation using google app script in Google Admin SDK

我想以管理员身份在谷歌中自动创建用户,我使用应用程序脚本来执行此操作,但是从我正在阅读的文档中,我不太确定我是否做得对,因为我在我的代码,例如在POST之后并且脚本不起作用。

function createUsers() {
  const userjson = {
      "primaryEmail": "atest@example.com",
  "name": {
    "givenName": "afirstName",
    "familyName": "alastName"
  },
  "suspended": false,
  "password": "pass2022",
  "hashFunction": "SHA-1",
  "changePasswordAtNextLogin": true,
  "ipWhitelisted": false,
  "orgUnitPath": "myOrgPath",
  };

  const optionalArgs = {
   customer: 'my_customer',
   orderBy: 'email'
  };

  POST https://admin.googleapis.com/admin/directory/v1/users

  try {
    const response = AdminDirectory.Users.list(optionalArgs);
    const users = response.users;

    //check if user exists
    if (!users || users.length === 0) 
    //create new user
    return AdminDirectory.newUser(userjson);

    // Print user exists
    Logger.log('User Existing');
    
  } catch (err) {
    // TODO (developer)- Handle exception from the Directory API
    Logger.log('Failed with error %s', err.message);
  }
}

根据官方文档,如果您想使用 Google Apps Script 执行此操作,则应按如下方式格式化您的代码:

function createUsers() {
  const userInfo = {
    "primaryEmail": "jvd@domain.com",
    "name": {
      "givenName": "Jackie",
      "familyName": "VanDamme"
    },
    "suspended": false,
    "password": "thisisasupersecret",
    "changePasswordAtNextLogin": true,
    "ipWhitelisted": false
  };
  try{
    AdminDirectory.Users.insert(userInfo);
    console.log("User added");
  } catch(error){
    const {code, message} = error.details;
    if(code === 409 && message === "Entity already exists."){
      console.log("User already exists");
    } else {
      console.log(`${code} - ${message}`);
    }
  }  
}

如果您对如何使用用户资源负载有任何疑问,请参考REST API 的官方文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM