I want to automate user creation in google as an Admin where I use app script to do it, however from the documentation I'm reading I'm not quite sure if I'm doing it right since I'm getting some errors in my code, like after POST and the Script not working.
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);
}
}
As per the official documentation, if you want to do it with Google Apps Script, you should format your code as follows:
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}`);
}
}
}
If you have any doubts about how to use the user resource payload, please refer to the official documentation of the REST API.