0

Trying to add aliases to users using post request to Directory (Admin SDK). I know that the JS client libraries is still in beta, but it's the simplest solution for what I have to do.

The below returns a 401 error. My credentials are just fine on Console.

    <script>
  var apiKey = "my_key";
  var clientId = "my_client_id";
  var scopes = "https://www.googleapis.com/auth/admin.directory.user.alias";
  var users = {}; // external JSON file

  function load() {
    gapi.client.setApiKey(apiKey);
    gapi.auth.authorize({
      client_id: clientId,
      scope: scopes,
      immediate: true
    },

    function(){
      for (var i = 0; i < users.length; i++) {
        var thisUser = users[i]["emailAddress"];
        var thisAlias = users[i]["secondaryEmail"];
        var thisURL = "https://www.googleapis.com/admin/directory/v1/users/" + thisUser + "/aliases"

        $.post(thisURL, {alias: thisAlias});
      }
    });
  }
</script>
<script src="https://apis.google.com/js/client.js?onload=load"></script>
friendofdog
  • 79
  • 12

1 Answers1

0

You can try following the Sample code in the JavaScript Quickstart:

// Your Client ID can be retrieved from your project in the Google
// Developer Console, https://console.developers.google.com
var CLIENT_ID = '<YOUR_CLIENT_ID>';

var SCOPES = ['https://www.googleapis.com/auth/admin.directory.user.readonly'];

/**
* Check if current user has authorized this application.
*/
function checkAuth() {
gapi.auth.authorize(
{
'client_id': CLIENT_ID,
'scope': SCOPES.join(' '),
'immediate': true
}, handleAuthResult);
}

/**
* Handle response from authorization server.
*
* @param {Object} authResult Authorization result.
*/
function handleAuthResult(authResult) {
var authorizeDiv = document.getElementById('authorize-div');
if (authResult && !authResult.error) {
// Hide auth UI, then load client library.
authorizeDiv.style.display = 'none';
loadDirectoryApi();
} else {
// Show auth UI, allowing the user to initiate authorization by
// clicking authorize button.
authorizeDiv.style.display = 'inline';
}
}

Try changing the format of your code to this and I think that will work.

Mr.Rebot
  • 6,703
  • 2
  • 16
  • 91
  • Pardon the late reply, and thanks for posting. This more or less worked. I'm having other unrelated complications but this much answers my question. – friendofdog Jul 04 '16 at 08:50