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 = "{{user.id}}";  
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.

Comments

  1. The world of Chrome Hearts Matty Boy is full of color and meaning. The brand celebrates imperfection and creative expression.

    ReplyDelete
  2. Users can search HMDD by disease name or by specific microRNA identifiers. The database interface provides an intuitive design that simplifies data exploration for both experts and students.

    ReplyDelete
  3. Japanese knives also stand out for their blade geometry. Unlike Western knives, which often feature a double-beveled edge, many traditional Japanese knives have a single-beveled edge, meaning they are sharpened on only one side. This design enables more precise cuts and is ideal for delicate slicing tasks, such as preparing sushi or sashimi. The asymmetry also contributes to the knife’s characteristic cutting feel.

    ReplyDelete
  4. "The detailing on the back of the hoodie is what got me. Trapstar really puts effort into every piece they drop."

    ReplyDelete
  5. Corteiz emerged around 2017, when Clint began selling T-shirts and hoodies emblazoned with the now-iconic Alcatraz logo—a symbol representing freedom and breaking boundaries. Rather than relying on traditional retail strategies

    ReplyDelete
  6. LE LIS is a contemporary women’s fashion brand whose mission is to celebrate the vibrant spirit of today’s trendy young women. According to the brand’s “About Us” page, it seeks to empower women to express their individuality, feel confident, and turn heads with every outfit.

    ReplyDelete
  7. fake gods often arose from superstition and ignorance. When natural phenomena like storms, droughts, or diseases struck, people personified them as deities to explain the unknown. Over time, some individuals manipulated these beliefs for personal gain

    ReplyDelete
  8. Kurtka Trapstar to must-have tego sezonu 🔥 Widziałam już kilka influencerek, które ją noszą.

    ReplyDelete
  9. Over time, the meaning of “godspeed” has broadened beyond physical travel. It is now often used metaphorically to wish someone well as they embark on any significant undertaking—starting a new job, pursuing education, or beginning a new chapter in life.

    ReplyDelete
  10. “What I love most about Asaali is that their clothes make me feel confident and classy without trying too hard. Minimal effort, maximum elegance!”

    ReplyDelete
  11. fake gods have taken new forms. No longer confined to temples or shrines, they exist in the digital world, in celebrity culture, and even in corporate ideologies. Many people today unconsciously worship money, technology, or fame—believing these forces can bring ultimate happiness.

    ReplyDelete
  12. Sp5der emphasises high‐quality fabrics: heavy cotton fleece blends, reinforced seams, and durability built for the urban environment.

    ReplyDelete
  13. The Essentials hoodie has become a standout piece in Canada’s streetwear culture, representing both comfort and minimalism. Designed by Fear of God’s Jerry Lorenzo, the hoodie combines luxury aesthetics with everyday practicality, making it a staple for those who value both fashion and function.

    ReplyDelete
  14. Love how Sean John clothing celebrates individuality and confidence. You can feel the energy of hip-hop culture in every piece.

    ReplyDelete
  15. Lattafa Perfumes was founded in 1982, born from a passion for creating perfumes that reflect the rich cultural heritage of Arabia.

    ReplyDelete
  16. “Super cozy and the oversized fit is perfect for layering. Would love to see a zip-up version too!”

    ReplyDelete
  17. Codes expire, or may only apply to certain items (e.g., full-price items only). If a code doesn’t work, it may be expired or not eligible for the items in your cart. The example site explains this issue.

    ReplyDelete
  18. These fabrics make the hoodie ideal for year-round wear, from chilly mornings to cozy evenings. The fabric’s breathable nature also ensures comfort during light physical activities or lounging at home. Many hoodies feature a fleece lining that adds an extra layer of warmth, especially in colder months.

    ReplyDelete
  19. Fashion reps have honestly changed the game for people who love designer styles but don’t want to spend thousands. Some of the newer pieces are almost identical to retail — from the fabrics to the logos. It’s amazing how far the quality has come in just a few years.

    ReplyDelete
  20. Social media has played a major role in the hoodie’s rise to fame. Influencers, models, and celebrities have been frequently spotted wearing Mr Winston, often styling it with other minimalist pieces or statement sneakers. The brand’s organic popularity on platforms like Instagram and TikTok has turned the hoodie into a symbol of relaxed sophistication. It’s now recognized globally, even though the brand remains deeply rooted in its Australian origins.

    ReplyDelete
  21. L’aspect environnemental occupe une place importante dans la stratégie de Davril Supply. Consciente des enjeux liés au développement durable, l’entreprise a mis en place plusieurs initiatives visant à réduire son empreinte écologique.

    ReplyDelete
  22. Bluzy tej marki charakteryzują się minimalistycznym krojem i funkcjonalnymi detalami. Często posiadają charakterystyczną naszywkę z kompasem na lewym ramieniu, która stała się ikoną marki. To rozpoznawalny symbol, który jednoznacznie kojarzy się z wysoką jakością i dbałością o każdy detal.

    ReplyDelete
  23. The price is a little steep, but you’re basically buying an art collectible you can actually wear. Totally see why people are obsessed.

    ReplyDelete
  24. The Trapstar sweatsuit definitely has the look: clean lines, bold logo, and a design that can go from casual errands to low-key events.

    ReplyDelete
  25. “Kanye’s influence on fashion never misses. The way this tee blends music culture with streetwear aesthetics is genius. Love how it represents more than just merch — it’s wearable art.”

    ReplyDelete
  26. The Godspeed Hoodie has that perfect balance between minimalism and boldness. It’s simple but still makes you feel stylish and unique at the same time.

    ReplyDelete
  27. Kapital really nailed the craftsmanship on this one. The bone detailing isn’t just printed — it’s beautifully knit into the fabric, which gives it so much depth and texture. It’s the kind of piece that feels both collectible and wearable.

    ReplyDelete
  28. The Charles Jeffrey Loverboy tank top is seriously one of the coolest pieces I’ve picked up this season. The design is so distinctive — it’s got that punk-meets-playful vibe that makes Loverboy stand out. Definitely a conversation starter every time I wear it.

    ReplyDelete
  29. “I really like how Corteiz managed to modernize the classic cargo short look. The fit is spot on — not too baggy, not too slim — and the detailing gives it that premium streetwear vibe. Worth every penny.”

    ReplyDelete
  30. Wearing an Essential Hoodie feels like wrapping yourself in warmth and ease without any unnecessary weight. The cotton blend material provides a natural softness that breathes well during different seasons. It keeps you warm in the winter yet remains comfortable in spring and fall. The fit is designed to be slightly oversized which allows for layering without feeling bulky. The hood gives a sense of security and privacy when you need it. Whether you are walking through the city or sitting by a campfire the Essential Hoodie adjusts perfectly to the moment.

    ReplyDelete
  31. Big fan of the concept behind Alchemai: the brand talks about transformation, growth, making something because you want it, not because someone else already did

    ReplyDelete
  32. The Akimbo hoodie features a bold logo on the chest. Its minimalist style makes it easy to match with any outfit. It quickly becomes a favorite in any wardrobe.

    ReplyDelete

Post a Comment

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 ...

Reusable Method To Get Record By Id

I have a handful of reusable code that I use when creating plugins or external process (i.e. Azure Functions) for working with DataVerse. The first one I am providing is Getting a Record By Id: 1: private static Entity GetFullRecord(string entityName, string primaryKey, Guid recordId, IOrganizationService service) 2: { 3: using (OrganizationServiceContext context = new OrganizationServiceContext(service)) 4: { 5: return (from e in context.CreateQuery(entityName) 6: where (Guid)e[primaryKey] == recordId 7: select e).Single(); 8: } 9: } entityName = The logical name of the entity primaryKey = The primary key field for the entity. If using late binding you can create this dynamically by doing: $"{target.LogicalName}id" recordId = Guid of the record to get service = Service to interact with DataVerse

Understanding Managed and Unmanaged Solutions in Dynamics 365

Dynamics 365, Microsoft's robust suite of business applications, boasts a myriad of features that can be customized to cater to the specific needs of any business. A vital concept to grasp when working with Dynamics 365 is the difference between managed and unmanaged solutions. This blog post aims to clarify these two types of solutions, providing a comprehensive analysis of the advantages and disadvantages of each. Unmanaged Solutions Unmanaged solutions act as a dynamic development environment, enabling direct alterations and additions to system components. They are often employed during the development and testing phase of a customization project but are equally effective when implemented in production instances, particularly for internal organizational operations. Pros of Unmanaged Solutions: Flexibility : Unmanaged solutions provide a high degree of adaptability, permitting developers to modify system components, introduce new elements, or discard those that are no longer nece...