Execute an action / run a trigger every time a User logs in to Salesforce

Is there any way to consistently execute a piece of Apex code whenever a User logs in to Salesforce? Posts such as this one seem to suggest that triggers on updates to the User object’s ‘LastLoginDate’ field do not consistently execute.

Workflow would be okay too — except that you cannot make workflow rules on the User object.

Is there any way to get a trigger to execute whenever a Salesforce user logs in?

Here is what I’ve currently done, both with the trigger saved in API v12 and API v25, with NO success. I have a Login_Events__c Long Textarea field that I’m trying to update based on some details of the User login event, but no such updates are taking place:

trigger User on User (before update) {

    if (Trigger.isBefore && Trigger.isUpdate) {

        for (User u : Trigger.new) {

            // Make sure there's at least something in the Login Events field
            if (u.login_events__c == null) u.login_events__c = '';

            // Add in the current login events change
            u.login_events__c +=
               '\n User Id: ' 
               + u.Id
               + ', Username: ' + u.Username 
               + ', Last Login Date: ' 
               + u.LastLoginDate 
               + ', Session Id: ' +  UserInfo.getSessionId() 
               + '\n';     
        }

    }

}

Answer

Couple of options to consider:

  1. Throw a Visualforce page into the sidebar component and either update the user record (or directly perform the logic you need to capture “login” event.
  2. Have a VF page and set that as the default page for the default App. Everytime the user logs in this page will get executed and then you can redirect to the tab/page that you want the user to go.

With #1, since Reports &Admin setup pages don’t get the side bar, this might not work in those pages. So if a user had bookmarked a setup page, side bar component will never get executed.

With#2, if a user bookmarks a page, the default app/page is not used and hence the VF page will not be run.

What are you trying to achieve with this trigger? Given you are concatenating Session Id (which is temporary) not really sure what you are aiming to do.

Perhaps a use cae would help to provide better answers.

Attribution
Source : Link , Question Author : zachelrath , Answer Author : Anand Narasimhan

Leave a Comment