Skip to main content

Power Pages Update Last Successful Login Using JavaScript and Power Pages API

 Recently while working on a Power Pages implementation for a client, I had the requirement to show the last time a user logged in on their profile page.  I thought this would be easy to do as there is already a field on the contact record for "Last Successful Login" (      adx_identity_lastsuccessfullogin).  This use to update when a user logged in, but it appears Microsoft has removed that automation.

While searching I came across a few different ways of achieving this task.  One used application insights in Azure and another one used an HTTP endpoint setup in Power Automate.  I thought, this needs to be simpler.  What I came up with is to use Liquid with JavaScript to tell if a user is logged in or not.  Then use the new Power Pages api to update the logged in users contact record to mark the last time they logged in.

Here is the approach I setup:

1) Make sure you turn on the api for contact in Site Settings.

1) Link to Microsoft Doc On How to turn on the api

2) Make sure you include "adx_identity_lastsuccessfullogin" in the list of fields to return.

2) I tested my process on the home page.  On the home page add two JavaScript Functions.  The first function (CheckIfUserJustLoggedIn) uses Liquid to tell if the user is logged in.  If they are not, it deletes our value from session memory.  If the user is logged in we check session memory to see if there is already a key in there with the date and time the user logged in.  If there is, we don't do anything else.  If there isn't then we create it and we update the contact record for the user via the Power Pages API.  The second function is Microsoft's wrapper function that handles the Ajax call and handles the authentication piece to make sure the user is authorized to perform the option.

1:  function CheckIfUserJustLoggedIn()  
2:  {  
3:    var sessionLastLogin = "sessionLastLogin";  
4:    var isLoggedIn = "{% if user %}true{% else %}false{% endif %}";  
5:    if (isLoggedIn == 'true')  
6:    {  
7:      var userId = "{{}}";  
8:      userId = userId.replace('{', '').replace('}', '');  
9:      var lastLogin = sessionStorage.getItem(sessionLastLogin);  
10:      if (lastLogin == null)  
11:      {  
12:        var dateTimestamp = new Date();  
13:        sessionStorage.setItem(sessionLastLogin, dateTimestamp);  
14:        webapi.safeAjax({  
15:          type: "PATCH",  
16:          url: "/_api/contacts(" + userId + ")",  
17:          contentType: "application/json",  
18:          data: JSON.stringify({  
19:            "adx_identity_lastsuccessfullogin": dateTimestamp  
20:          }),  
21:          success: function (res) {  
22:            console.log(res);  
23:          }  
24:        });  
25:      }  
26:    }  
27:    else  
28:    {  
29:      sessionStorage.removeItem(sessionLastLogin);  
30:    }  
31:  }  

1:  (function(webapi, $){  
2:    function safeAjax(ajaxOptions) {  
3:        var deferredAjax = $.Deferred();  
4:        shell.getTokenDeferred().done(function (token) {  
5:            // add headers for AJAX  
6:            if (!ajaxOptions.headers) {  
7:                $.extend(ajaxOptions, {  
8:                    headers: {  
9:                        "__RequestVerificationToken": token  
10:                    }  
11:                });  
12:            } else {  
13:                ajaxOptions.headers["__RequestVerificationToken"] = token;  
14:            }  
15:            $.ajax(ajaxOptions)  
16:                .done(function(data, textStatus, jqXHR) {  
17:                    validateLoginSession(data, textStatus, jqXHR, deferredAjax.resolve);  
18:                }).fail(deferredAjax.reject); //AJAX  
19:        }).fail(function () {  
20:            deferredAjax.rejectWith(this, arguments); // on token failure pass the token AJAX and args  
21:        });  
22:        return deferredAjax.promise();  
23:    }  
24:    webapi.safeAjax = safeAjax;  
25:  })(window.webapi = window.webapi || {}, jQuery)  

If you run into issues for permissions check your Power Pages Web Roles table and make sure the user has the correct permissions for the contact table.


Popular posts from this blog

Validating User Input In CRM Portals With JavaScript

When we are setting up CRM Portals to allow customers to update their information, open cases, fill out an applications, etc. We want to make sure that we are validating their input before it is committed to CRM.  This way we ensure that our data is clean and meaningful to us and the customer. CRM Portals already has a lot validation checks built into it. But, on occasion we need to add our own.  To do this we will use JavaScript to run the validation and also to output a message to the user to tell them there is an issue they need to fix. Before we can do any JavaScript, we need to check and see if we are using JavaScript on an Entity Form or Web Page.  This is because the JavaScript, while similar, will be different.  First, we will go over the JavaScript for Entity Forms.  Then, we will go over the JavaScript for Web Pages.  Finally, we will look at the notification JavaScript. Entity Form: if (window.jQuery) { (function ($) { if (typeof (entityFormClientVali

Dynamics Set IFrame URL - D365 v8 vs. D365 v9

While doing client work, I came across a problem with setting an IFrame URL dynamically.  The underlying issue was that the sandbox instance is on v8 of Dynamics 365 and production is on v9 of Dynamics 365.  The reason for this was because this client was setup around the time that Microsoft rolled out v9.  Anyways, JavaScript that I wrote to dynamically set the URL of the IFrame wasn't working in the v9 instance.  This was because of changes that Microsoft made to how IFrames are loaded on the form and also changes to JavaScript. Here is my v8 setup: JavaScript runs OnLoad of contact form.  This works because of how IFrames are loaded in v8.  You can also run it on either a tab change (hide / show) or OnReadyStateComplete event of the IFrame.  Depending on your setup you will need to choose which is best for you.  For me in this case it was the OnLoad event. Here is the JavaScript: function OnLoad() { //Get memberid var value =

Navigating Microsoft Dynamics 365 Customization: Plugins vs. Azure Functions

Embarking on the Microsoft Dynamics 365 customization journey offers numerous opportunities to enhance your business processes. However, deciding between the available options, such as Plugins and Azure Functions, can be challenging. This engaging post will serve as your trusty guide, helping you choose the best option for your Dynamics 365 customization needs! The Two Customization Pathfinders: Plugin and Azure Function The Agile Plugin ­čĆâ‍♂️ Reference: Microsoft Docs - Write a plug-in Plugins are like the swift trail runners of the Dynamics 365 customization world. They're the go-to choice for quick, real-time (synchronous), or background (asynchronous) operations that occur within the platform. They can intercept events and modify data before it's saved or displayed to the user. Choose Plugins when: You need real-time processing (synchronous) or background processing (asynchronous). You want to ensure data integrity. You need tight integration with Dynamics 365. Plugins mig