How to query and sort on ArcGIS Portal users based on date?

4898
7
Jump to solution
06-12-2018 11:33 AM
AllenGuan2
New Contributor III

I want to retrieve our on-premise Portal or AGOL users based on a query on the lastLogin, for example the users who last logins between two dates, or since a date, or in the last 2 hours, How would I do that? Also I want to sort the results based on lastLogin using the below statement, it does not sort as expected.

users = gis.users.search("*",sort_field="lastLogin",sort_order="desc",max_users=1000). 

Tags (2)
0 Kudos
1 Solution

Accepted Solutions
JoshuaBixby
MVP Esteemed Contributor

I should have caught this earlier.  See UserManager documentation:

search(query=None, sort_field='username', sort_order='asc', max_users=100, outside_org=False, exclude_system=False)

......
sort_fieldOptional string. Valid values can be username (the default) or created.
......

Last login is not a valid sort field.  Interestingly enough, the ArcGIS REST API User Search  documentation states fullname and modified are also valid sort fields.

View solution in original post

7 Replies
JoshuaBixby
MVP Esteemed Contributor

You say "does not sort as expected," what do you expect and what are you getting?  Examples are very helpful to community members.

0 Kudos
AllenGuan2
New Contributor III

Here is the code. I would think the results will be ordered in desc by lastlogin_str column, but they are not.

import pandas as pd
import time
tbl = []
users = gis.users.search("*",sort_field="lastLogin",sort_order="desc",max_users=500)
for user in users:
    grps = ""
    for grp in user.groups:
        try:
            grps += grp.title + ","
        except:
            print("\n")
    grps = grps[:-1]
    created_str = time.strftime('%Y-%m-%d', time.gmtime(user.created/1000.0))
    modified_str = time.strftime('%Y-%m-%d', time.gmtime(user.modified/1000.0))
    lastlogin_str = time.strftime('%Y-%m-%d', time.gmtime(user.lastLogin/1000.0))
    num_items = 0
    #root items
    #print("Items under root:")
    for item in user.items():
        #print("\t" + item.title + " - " + item.type)
        num_items += 1
    # folder items
    for folder in user.folders:
        #print("Items under " + folder['title'] + ":")
        for item in user.items(folder=folder['title']):
            #print("\t" + item.title + " - " + item.type)
            num_items += 1

    tbl.append([user.username,user.fullName,user.role,user.level,user.email,created_str,modified_str,lastlogin_str,grps,str(num_items),str(user.disabled),user.idpUsername,user.userType,user.assignedCredits,user.availableCredits])
    #print(user.username + "\t" + str(user.role) + "\t" + created + "\t" + lastlogin + "\t" + grps)

columns_all = ['User','fullName','Role','Level','Email','Created','lastModified','lastLogin','Groups','Items','Disabled','idpUsername','userType','assignedCredits','availableCredits']
df = pd.DataFrame(data = tbl,columns = columns_all)
columns_show = columns_all
df[columns_show]

0 Kudos
JoshuaBixby
MVP Esteemed Contributor

I should have caught this earlier.  See UserManager documentation:

search(query=None, sort_field='username', sort_order='asc', max_users=100, outside_org=False, exclude_system=False)

......
sort_fieldOptional string. Valid values can be username (the default) or created.
......

Last login is not a valid sort field.  Interestingly enough, the ArcGIS REST API User Search  documentation states fullname and modified are also valid sort fields.

AllenGuan2
New Contributor III

yes, verified created sort is correct. Why not make lastlogin sortable? It is more useful than created.

0 Kudos
JohnYaist1
Esri Contributor

Hi Allen Guan

You can return a list of users sorted by the created or modified attributes as mentioned above like:

org_users = g.users.search(query="NOT fullName: esri*", sort_field="modified", sort_order="desc")

You can then use Python's datetime and calendar modules to inspect lastLogin based on various time values:

from datetime import datetime, timedelta

# create a datetime object for right now
now = datetime.now()
# create a datetime object for 2 hours ago
dt_2hrs_ago = now - timedelta(hours=2)

# convert the datetime object from 2 hrs ago into Unix epoch time in seconds
etime_2hrs_ago = calendar.timegm(dt_2hrs_ago.timetuple())

# use a list comprehension to get list of users who have logged in within the last 2 hrs
usr_within_2hrs = [usr for usr in org_users if usr.lastLogin/1000 > etime_2hrs_ago]
usr_within_2hrs
‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍
JoshuaBixby
MVP Esteemed Contributor

This approach will struggle with larger number of users.  My organization has 8,000+ AGOL users, retrieving all of them to sort by lastLogin isn't practical.

Unlike User Search—ArcGIS REST API: Users, groups, and content | ArcGIS for Developers  under the Community URL, Users—ArcGIS REST API: Users, groups, and content | ArcGIS for Developers  under the Portal URL does support using lastLogin as a sort field.

What would be handy, and may exist but I just haven't found it, is to have part of the Python API for ArcGIS generate the following type of REST call:

https://org.maps.arcgis.com/sharing/rest/portals/self/users?sortField=lastlogin&sortOrder=desc&num=5&f=pjson
0 Kudos
AllenGuan2
New Contributor III

yes, thanks.

0 Kudos