问题
I am refactoring a script that creates new user accounts on google script G-Suite API.
The script works fine, and prepared an email templates, with login credentials--all as expected.
I am not trying to retrieve 8-digit authentication code, and attach it to the email template, since we moved to required 2FA organisation wide.
The crux of the problem is, I can't naturally get the codes if the account has not been created. There seems to be some issue -- some type of delay, where I can't get the codes fast enough? Not entirely sure. I got some help on how to retrieve the codes with this simple variable declaration:
AdminDirectory.VerificationCodes.list('donald.duck@example.com').items[0].verificationCode;
As you can imagine, the problem is donald.duck is not yet a user =)
I am about to give up, and just create another script that send a followup email with the 8-digit codes.
Anyone familiar with this API, this problem?
I have tried setting all types of variables with the above declaration, and placing it at all places within the current script - even right after where the user is created:
user = AdminDirectory.Users.insert(result.user);
But, it always comes back with a "Error Message: Cannot read property '0' of undefined" error. Which I assume is because the user does not exist - yet.
Thanks in advance.
回答1:
Solution:
Verification codes need to be generated first for every created user. Since this is a script, you can use AdminDirectory.VerificationCodes.generate to do this before listing.
Sample:
function generateKeys() {
AdminDirectory.VerificationCodes.generate("dummyemail@dummy.com");
var keys = AdminDirectory.VerificationCodes.list("dummyemail@dummy.com").items[0].verificationCode;
console.log(keys);
}
This should display a numeric key on the execution log instead of undefined.
Reference:
Generate Verification Codes
回答2:
You get that error because the items array is empty. Before grabbing a value that is assumed to be there, first check if the element exists.
// Mock AdminDirectory
const AdminDirectory = {
VerificationCodes: {
list: (userId) => {
const codes = [{
userId: 'user@example.com',
verificationCode: 'code1',
}, {
userId: 'user@example.com',
verificationCode: 'code2',
}];
return { items: codes.filter(c => c.userId === userId) };
},
}
};
const response = AdminDirectory.VerificationCodes.list('user1@example.com');
// Check if the `items` array has anything before accessing the value
const code = response.items.length > 0 ? response.items[0].verificationCode : null;
console.log(code); // null
来源:https://stackoverflow.com/questions/65992312/chicken-and-egg-situation-with-retrieve-8-digit-codes-from-new-created-accounts