Any help would be GREATLY appreciated!!

329 views
Skip to first unread message

Scott Croskey

unread,
May 4, 2016, 11:35:41 AM5/4/16
to nodejs
I have the following code in Nodejs.  I am trying to create a user.  I have the auth token saved to a file on my local computer  I have the json file saved in the same location.  Testing has gotten the id to be written to the same directory as well.  Now when I try to actually create the user in google I get  an error.  Here is the error followed by the code.  Again any help would be greatly appreciated!!!!!

Error and console output:

C:\Google>node quickstart.js
{ Classification: 'Certified',
  District_Email: 'jho...@mcspresidents.org',
  Prefix: 'Mr.',
  First: 'Jimmy',
  Middle: '',
  Last: 'Hoffa',
  First_Preference: '',
  Last_Preference: '',
  Maiden: '',
  Primary_Affiliation: 'Harding',
  General_Assignment: 'Aide',
  Assignment: '1 on 1 Aide' }
Jimmy
Hoffa
{ Error: Invalid Given/Family Name: FamilyName
    at Request._callback (C:\Google\node_modules\google-auth-library\lib\transpo
rters.js:82:15)
    at Request.self.callback (C:\Google\node_modules\google-auth-library\node_mo
dules\request\request.js:198:22)
    at emitTwo (events.js:106:13)
    at Request.emit (events.js:191:7)
    at Request.<anonymous> (C:\Google\node_modules\google-auth-library\node_modu
les\request\request.js:1057:14)
    at emitOne (events.js:101:20)
    at Request.emit (events.js:188:7)
    at IncomingMessage.<anonymous> (C:\Google\node_modules\google-auth-library\n
ode_modules\request\request.js:1003:12)
    at emitNone (events.js:91:20)
    at IncomingMessage.emit (events.js:185:7)
  code: 400,
  errors:
   [ { domain: 'global',
       reason: 'invalid',
       message: 'Invalid Given/Family Name: FamilyName' } ] }

C:\Google>




Code:

var fs = require('fs');
var readline = require('readline');
var google = require('googleapis');
var googleAuth = require('google-auth-library');

// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/admin-directory_v1-nodejs-quickstart.json
var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
    process.env.USERPROFILE) + '/.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'admin-directory_v1-nodejs-quickstart.json';

// Load client secrets from a local file.
fs.readFile('client_secret.json', function processClientSecrets(err, content) {
  if (err) {
    console.log('Error loading client secret file: ' + err);
    return;
  }
  // Authorize a client with the loaded credentials, then call the
  // Directory API.
  authorize(JSON.parse(content), listUsers);
});

/**
 * Create an OAuth2 client with the given credentials, and then execute the
 * given callback function.
 *
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
 */
function authorize(credentials, callback) {
  var clientSecret = credentials.installed.client_secret;
  var clientId = credentials.installed.client_id;
  var redirectUrl = credentials.installed.redirect_uris[0];
  var auth = new googleAuth();
  var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);

  // Check if we have previously stored a token.
  fs.readFile(TOKEN_PATH, function(err, token) {
    if (err) {
      getNewToken(oauth2Client, callback);
    } else {
      oauth2Client.credentials = JSON.parse(token);
      callback(oauth2Client);
    }
  });
}

/**
 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 *
 * @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback to call with the authorized
 *     client.
 */
function getNewToken(oauth2Client, callback) {
  var authUrl = oauth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES
  });
  console.log('Authorize this app by visiting this url: ', authUrl);
  var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });
  rl.question('Enter the code from that page here: ', function(code) {
    rl.close();
    oauth2Client.getToken(code, function(err, token) {
      if (err) {
        console.log('Error while trying to retrieve access token', err);
        return;
      }
      oauth2Client.credentials = token;
      storeToken(token);
      callback(oauth2Client);
    });
  });
}

/**
 * Store token to disk be used in later program executions.
 *
 * @param {Object} token The token to store to disk.
 */
function storeToken(token) {
  try {
    fs.mkdirSync(TOKEN_DIR);
  } catch (err) {
    if (err.code != 'EEXIST') {
      throw err;
    }
  }
  fs.writeFile(TOKEN_PATH, JSON.stringify(token));
  console.log('Token stored to ' + TOKEN_PATH);
}

/**
 * Lists the first 10 users in the domain.
 *
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */

function listUsers(auth){
  fs.readFile('user.json', function processClientSecrets(err, content) {
  if (err) {
    console.log('Error loading client secret file: ' + err);
    return;
  }
  var newUser = JSON.parse(content);
  console.log(newUser);
  console.log(newUser.First);
  console.log(newUser.Last);
  var createUser =  {
    auth: auth,
 customer: 'my_customer',
    "name": {
        
        "givenName": newUser.First,
        "familyName": newUser.Last
    },
    "password": "mcs12345",
    "primaryEmail": newUser.District_Email,
    "changePasswordAtNextLogin": false,
    "orgUnitPath": "/Staff"
};
  var admin = google.admin( "directory_v1");
  var id = admin.users.insert(createUser).id;
  // Authorize a client with the loaded credentials, then call the
  // Directory API.

  fs.writeFile("gid.txt", "mcs" + id);
});
}


PLEASE NOTE: This message and any response to it may constitute a public record, and therefore may be available upon request in accordance with Ohio public records law.  (ORC 149.43)

Christopher Mina

unread,
May 5, 2016, 12:04:34 AM5/5/16
to nodejs
Hi.  

I'm not familiar with the library, but your code generally look ok.  

Check out this StackOverflow post, maybe it's as simple as setting the header ContentType to application/json?  Would be an improper error message if so, but hey, stranger things have happened:


-Chris

Scott Croskey

unread,
May 5, 2016, 9:43:31 PM5/5/16
to nodejs
I saw that post, but did not know how to do that. 


On Thursday, May 5, 2016 at 12:04:34 AM UTC-4, Christopher Mina wrote:
Hi.  

I'm not familiar with the library, but your code generally look ok.  

Check out this StackOverflow post, maybe it's as simple as setting the header ContentType to application/json?  Would be an improper error message if so, but hey, stranger things have happened:


-Chris


Christopher Mina

unread,
May 6, 2016, 1:43:34 PM5/6/16
to nodejs
If you take a look at the code:

you can see the directory-v1 -> users object and the insert() method.  It takes a "params" argument.  This params argument gets wrapped as a larger "parameters" argument and sent to the "createApiRequest" method, which is found here:  


In the createApiRequest, you can see that it pulls optional user supplied headers out of the parameters.params.headers object.  To construct this, see below for some modifications to your code.  

var createUser =  {
    auth: auth,
    headers: {
        'Content-Type': 'application/json'
    },
    customer: 'my_customer',
    "name": {    
        "givenName": newUser.First,
        "familyName": newUser.Last
    },
    "password": "mcs12345",
    "primaryEmail": newUser.District_Email,
    "changePasswordAtNextLogin": false,
    "orgUnitPath": "/Staff"
};
  var admin = google.admin( "directory_v1");
  var id = admin.users.insert(createUser).id;
  // Authorize a client with the loaded credentials, then call the
  // Directory API.

  fs.writeFile("gid.txt", "mcs" + id);
});


Hopefully this works for you. 

Chris

Ulion

unread,
May 18, 2016, 11:51:44 PM5/18/16
to nodejs
var createUser =  {
  auth: auth,
  "resource": {
    "name": {    
        "givenName": newUser.First,
        "familyName": newUser.Last
    },
    "password": "mcs12345",
    "primaryEmail": newUser.District_Email,
    "changePasswordAtNextLogin": false,
    "orgUnitPath": "/Staff"
  }
};

Reply all
Reply to author
Forward
0 new messages