Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiate an Admin SDK Directory service object with NodeJS

Following the instructions on how to Perform G Suite Domain-Wide Delegation of Authority as see here https://developers.google.com/admin-sdk/directory/v1/guides/delegation I accomplished all of the steps, but now I am stuck on implementing an SDK Directory service Object in my app, I am using Angular 7 on the frontened and NodeJs(Firebase cloud functions) for my backend but the code given here only supports Java, Python and Go. Can anyone show me how I would convert this into NodeJS?

like image 914
Claudio Teles Avatar asked Sep 18 '25 09:09

Claudio Teles


2 Answers

Hopefully you have an answer to this by now, but here you go:

const keys = require('<Path to your privateKey.json file>');
const { JWT } = require('google-auth-library');    

async function main() {
        const client = new JWT({
            email: keys.client_email,
            key: keys.private_key,
            subject: "<email address of user with admin acceess on G Suite>",
            scopes: [<put your scopes here>],
        });
        const url = `<Your HTTP request>`;
        const res = await client.request({ url });
        return(res.data);
    }

    main().catch(console.error);

This is a good example of how your code should look like: https://github.com/googleapis/google-auth-library-nodejs/blob/master/samples/jwt.js

The only missing thing in google's sample is subject parameter. This parameter is a must as you are trying to access API that is only accessible to G Suite admins, therefore you need to impersonate an admin account.

like image 187
kamilestu Avatar answered Sep 21 '25 02:09

kamilestu


Sequel to kamilestu answer

This works with google api

const client = new JWT({
  email: privatekey.client_email,
  key: privatekey.private_key,
  subject: "<email address of user with admin acceess on G Suite>",
  scopes: SCOPES,
});

async function getUser(email) {
  try {
    const admin = await google.admin({
      version: "directory_v1",
      auth: client,
    });
    //get all users
    const users = await admin.users.get({
      userKey: email,
    });
    console.log(users, "users");
  } catch (error) {
    console.log(
      error.response ? error.response.data : error.message,
      "error",
      error.message ? error.errors : ""
    );
  }
}

getUser("<email address of user with admin acceess on G Suite>");
like image 38
olawalejuwonm Avatar answered Sep 21 '25 02:09

olawalejuwonm