8

Because User Mode database operations don't work for the Automated Process User, I need to litter my code with checks to see if the current user is such a user.

I've previously got an automated process user ID with the following:

return [SELECT Id FROM User WHERE IsActive = TRUE AND UserType = 'AutomatedProcess' AND Username LIKE '%autoproc%' LIMIT 1].Id;

I don't know if there can be more than one such user, but I'm going to change to use something like this:

Boolean isAutoProc = [SELECT Id
                      FROM User
                      WHERE Id = : UserInfo.getUserId()
                      AND Usertype = 'AutomatedProcess'].size() > 0;

Of course, rather than litter my code I'll likely refactor to put a wrapper around all database operations (queries and DML ops), but what I want to check is whether this approach is legitimate or whether I'm missing some key piece of information?

2 Answers 2

9

You can get the user type without a query:

Boolean isAutomatedUser = UserInfo.getUserType() == 'automatedprocess';

I'd probably use a static variable to control that:

static AccessLevel access = UserInfo.getUserType() == 'automatedprocess'
  ? AccessLevel.SYSTEM_MODE
  : AccessLevel.USER_MODE;

That way, I could just refer to the variable:

Database.update(someRecords, Utils.access);
2
  • 1
    Gah, I didn't look at those methods. Had it in my head I'd looked for that before and not seen it. The static option makes a lot of sense. Thanks, and Happy New Year mate.
    – Matt Lacey
    Commented Jan 3 at 15:42
  • 1
    @MattLacey That's why, even with nearly two decades experience in Apex, I still check the docs on a regular basis. Hard to keep up with all the changes 😅.
    – sfdcfox
    Commented Jan 4 at 11:58
3

In the question, you mention that "I don't know if there can be more than one such user".

There definitely can be more than one user with a UserType=AutomatedProcess.

In a scratch org, you get two:

  • Automated Process
  • Data.com Clean

Brian's answer to your question of detecting whether or not the current user is automated is spot-on and the best way of doing it.

But to answer your side-question, and if anyone is thinking of querying for "Automated Process" (i.e. the default user for Platform Events et al.), then the way to do that is to query like this:

Id automatedProcessUserId = [
       SELECT Id
       FROM User
       WHERE UserType = 'AutomatedProcess'
       AND Username = : 'autoproc@' + UserInfo.getOrganizationId()
       LIMIT 1].Id;

The username of Automated Process User is defined to be autoproc@<org-id>.

1
  • Thanks mate, that coffee will be on me when we manage it!
    – Matt Lacey
    Commented Mar 25 at 13:49

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .