Select to view content in your preferred language

How to get all named users in ArcGIS Online

3905
11
06-07-2018 05:17 PM
JosephJose
Occasional Contributor

Am trying to find out how I can get list of all named users in ArcGIS Online account using REST request though I know it provides a visual interface in AdminTools for AGOL

Portal provides a community REST service. Is there something similar for AGOL?

0 Kudos
11 Replies
KellyGerrow
Esri Alum

I've fixed the sharing on the script. You can navigate to the link now.

0 Kudos
by Anonymous User
Not applicable

Thanks Kelly, I needed it for Javascript. If anyone interested here is the nodejs code to get the users. Unfortunately ESRI REST Endpoint for users is limited to 100 users max per request (again, esri making it more diffucult rather than returning 1000 or so. It's not geometries !!!)

This is a complete Express.js route. You have to use babel to compile and run the code, but you get the picture from the code. if you provide https://your-api/list-users?f=xsl it will generate the XSL spreadsheet

import { getConfig } from '../../config'
import * as winston from 'winston'

// Get the config instance from the module
let config = getConfig()
let auth
let token
let tokenExpires

// const request = require('request');
const requestPromise = require('request-promise');
const rp = requestPromise.defaults({
  'rejectUnauthorized': false,
  'proxy': '<your proxy if required>'
});

const route = {

  init: () => {
    return new Promise(async (resolve, reject) => {
      try {
        winston.info('Setting up the route for AGOL ...')
        token = await route.getToken();
        if (token.error) {
          token = null;
          resolve('Unable to get the token.')
        }
        tokenExpires = token.expires;
        resolve();
      } catch (err) {
        route.catchErr(err)
        reject(err)
      }
    })
  },

  getToken: async () => {
    const { referer, url, client, username, pwd } = config.agol;
    var options = {
      method: 'POST',
      uri: 'https://www.arcgis.com/sharing/rest/generateToken',
      form: {
        username: username,
        password: pwd,
        client: 'referer',
        referer: referer,
        f: 'json',
        expiration: 21600, // 15-days is max
      },
      timeout: 100000,
      json: true
    };
    return await rp(options);
  },

  listAgolUsers: (req, res) => {
    try {
      console.log(token);

      let func = () => {
        let users = []
        route.getUsers(0, users).then(users => {
          if (!req.query || !req.query.f || req.query.f !== 'xsl') {
            res.status(201).end(JSON.stringify(users, null, 4));
          }
          else {
            // Return XSL
            const excel = require('node-excel-export');
            const specification = {
              username: {
                displayName: 'User Name',
                headerStyle: {},
                width: '50'
              },
              fullName: {
                displayName: 'Full Name',
                headerStyle: {},
                width: '50'
              },
              created: {
                displayName: 'Created',
                headerStyle: {},
                width: '50'
              },
              modified: {
                displayName: 'Last Modified',
                headerStyle: {},
                width: '50'
              },
              level: {
                displayName: 'Level',
                headerStyle: {},
                width: '50'
              },
              userLicenseTypeId:{
                displayName: 'User License Type',
                headerStyle: {},
                width: '50'
              },
              disabled: {
                displayName: 'Disabled',
                headerStyle: {},
                width: '50'
              }
            }
            const report = excel.buildExport([{
              name: 'AGOL-Users-List',
              heading: [],
              specification: specification,
              data: users
            }])
            res.attachment('AGOL-Users-export.xlsx');
            res.send(report);
          }
        }).catch(err => {
          res.status(404).json(err);
        });
      }

      // Check if the token is still valid
      if (!token || !token.token || new Date() > new Date(tokenExpires)) {
        route.getToken().then(result => {
          token = result;
          tokenExpires = result.expires;
          func();
        }).catch(err => {
          console.error('Unable to get the token');
          route.catchErr(err, res);
        });
      }
      else {
        func();
      }
    }
    catch (e) {
      res.reject(e)
    }
  },

  getUsers: async (start, users) => {
   return new Promise((resolve, reject) => {
      const options = {
        method: 'GET',
        uri: config.agol.users.url,
        qs: {
          token: token.token,
          f: 'json',
          num: 100,
          start: start ? start : 1
        },
        json: true
      }

      rp(options).then(results => {
        const total = results.total;
        let current = 1;
        let promises = []
        while (current < total) {
          const opt = {
            method: 'GET',
            uri: config.agol.users.url,
            qs: {
              token: token.token,
              f: 'json',
              num: 100,
              start: current ? current : 1
            },
            json: true
          }
          promises.push(rp(opt));
          current += 100;
        }

        let users = []
        Promise.all(promises).then((xresults) => {
          xresults.forEach((r) => {
            let extract = r.users.map(u => {
              return {
                username: u.username,
                fullName: u.fullName,
                created: (new Date(u.created)).toString(),
                modified: (new Date(u.modified)).toString(),
                level: u.level.toString(),
                userLicenseTypeId: u.userLicenseTypeId,
                disabled: u.disabled
              }
            })
            users = users.concat(extract);
          });
          resolve(users);
        })

      }).catch(err => {
        reject(err);
      })
    });
  },

  catchErr: (err, res) => {
    winston.error(`agol.js: ${ err }`)
    if (res) {
      res.status(404).json('Error')
    }
  }
}

export default route
0 Kudos