#168 - Save Trusted Devices v0.1

Save trusted devices to extend user sessions and reduce repeated logins on your sites.

View demo

<!-- 💙 MEMBERSCRIPT #168 v0.1 💙 - SAVE TRUSTED DEVICE -->
<script>
(function() {
    const TRUST_EXPIRY_DAYS = 90;
    const MAX_TRUSTED_DEVICES = 5;
    const EXTENDED_SESSION_DAYS = 30;
  
    function generateDeviceIdentifier() {
      let id = localStorage.getItem('ms_device_id');
      if (id) return id;
      const info = {
        ua: navigator.userAgent,
        w: screen.width,
        h: screen.height,
        tz: Intl.DateTimeFormat().resolvedOptions().timeZone,
        plat: navigator.platform
      };
      id = btoa(JSON.stringify(info)).slice(0, 32);
      localStorage.setItem('ms_device_id', id);
      return id;
    }
  
    async function getTrustedDevices() {
      const ms = window.$memberstackDom;
      const memberJson = await ms.getMemberJSON();
      return Array.isArray(memberJson?.data?.trustedDevices) ? memberJson.data.trustedDevices : [];
    }
  
    async function saveTrustedDevices(devices) {
      const ms = window.$memberstackDom;
      const memberJson = await ms.getMemberJSON();
      memberJson.data = memberJson.data || {};
      memberJson.data.trustedDevices = devices;
      await ms.updateMemberJSON({ json: memberJson });
    }
  
    async function addTrustedDevice(id, name) {
      const now = new Date();
      const expires = new Date(now.getTime() + TRUST_EXPIRY_DAYS * 864e5).toISOString();
      const devices = await getTrustedDevices();
      const existing = devices.find(d => d.id === id);
  
      if (existing) {
        existing.trustedAt = now.toISOString();
        existing.expiresAt = expires;
      } else {
        if (devices.length >= MAX_TRUSTED_DEVICES) devices.shift();
        devices.push({
          id,
          trustedAt: now.toISOString(),
          expiresAt: expires,
          ua: navigator.userAgent.slice(0, 100),
          name: name
        });
      }
  
      await saveTrustedDevices(devices);
    }
  
    function getDeviceName() {
      const ua = navigator.userAgent;
      if (ua.includes('iPhone')) return 'iPhone';
      if (ua.includes('iPad')) return 'iPad';
      if (ua.includes('Android')) return 'Android';
      if (ua.includes('Mac')) return 'Mac';
      if (ua.includes('Windows')) return 'Windows';
      return 'Device';
    }
  
    function setExtendedSession() {
      const exp = new Date();
      exp.setDate(exp.getDate() + EXTENDED_SESSION_DAYS);
      document.cookie = `trustedDevice=true; expires=${exp.toUTCString()}; path=/; SameSite=Strict`;
    }
  
    function showNotice() {
      const el = document.querySelector('[data-ms-code="trust-device-notice"]');
      if (!el) return;
      el.style.display = 'block';
      sessionStorage.setItem('ms_new_device_detected', '1');
      sessionStorage.removeItem('ms_device_trusted');
    }
  
    function hideNotice() {
      const el = document.querySelector('[data-ms-code="trust-device-notice"]');
      if (el) el.style.display = 'none';
      sessionStorage.removeItem('ms_new_device_detected');
      sessionStorage.setItem('ms_device_trusted', '1');
    }
  
    function setupTrustBtn() {
      document.addEventListener('click', async e => {
        const btn = e.target.closest('[data-ms-code="trust-device-btn"]');
        if (!btn) return;
        e.preventDefault();
        btn.disabled = true;
        btn.innerText = 'Trusting Device...';
  
        const member = await window.$memberstackDom.getCurrentMember();
        if (!member?.data) {
          alert('Please log in first.');
          btn.disabled = false;
          btn.innerText = 'Trust This Device';
          return;
        }
  
        const id = generateDeviceIdentifier();
        const name = getDeviceName();
        await addTrustedDevice(id, name);
        setExtendedSession();
  
        btn.innerText = 'Device Trusted!';
        setTimeout(hideNotice, 1000);
      });
    }
  
    async function checkTrust() {
      const member = await window.$memberstackDom.getCurrentMember();
      if (!member) {
        hideNotice();
        return;
      }

      const id = generateDeviceIdentifier();
      const devices = await getTrustedDevices();
      
      // Check if current device is trusted
      const trusted = devices.some(d => {
        // Check if device ID matches and hasn't expired
        if (d.id === id && new Date(d.expiresAt) > new Date()) {
          return true;
        }
        // Also check by user agent for better matching
        if (d.ua && d.ua.includes(navigator.userAgent.slice(0, 50)) && new Date(d.expiresAt) > new Date()) {
          return true;
        }
        return false;
      });

      if (trusted) {
        hideNotice();
        setExtendedSession();
        // Also store in sessionStorage to prevent showing on refresh
        sessionStorage.setItem('ms_device_trusted', '1');
      } else {
        // Check if we already showed the notice in this session or have the cookie
        if (sessionStorage.getItem('ms_device_trusted') === '1' || 
            document.cookie.includes('trustedDevice=true')) {
          hideNotice();
        } else {
          showNotice();
        }
      }
    }
  
    function preventRedirect() {
      window.addEventListener('ms:member:will-redirect', e => {
        if (sessionStorage.getItem('ms_new_device_detected') === '1') {
          e.preventDefault();
        }
      });
    }
  
    function init() {
      // Immediately hide notice if device is already trusted in this session
      if (sessionStorage.getItem('ms_device_trusted') === '1' || 
          document.cookie.includes('trustedDevice=true')) {
        hideNotice();
      }
      
      if (window.$memberstackDom?.getCurrentMember) {
        setupTrustBtn();
        preventRedirect();
        window.addEventListener('ms:member:login', () => setTimeout(checkTrust, 1000));
        window.addEventListener('ms:member:info-changed', checkTrust);
        checkTrust();
      } else {
        setTimeout(init, 500);
      }
    }
  
    document.addEventListener('DOMContentLoaded', init);
  })();
</script>

Creating the Make.com Scenario

1. Download the JSON blueprint below to get stated.

2. Navigate to Make.com and Create a New Scenario...

3. Click the small box with 3 dots and then Import Blueprint...

4. Upload your file and voila! You're ready to link your own accounts.

Need help with this MemberScript?

All Memberstack customers can ask for assistance in the 2.0 Slack. Please note that these are not official features and support cannot be guaranteed.

Join the 2.0 Slack
Version notes
Attributes
Description
Attribute
No items found.
Guides / Tutorials
No items found.
Tutorial
What is Memberstack?

Auth & payments for Webflow sites

Add logins, subscriptions, gated content, and more to your Webflow site - easy, and fully customizable.

Learn more

"We've been using Memberstack for a long time, and it has helped us achieve things we would have never thought possible using Webflow. It's allowed us to build platforms with great depth and functionality and the team behind it has always been super helpful and receptive to feedback"

Jamie Debnam
39 Digital

"Been building a membership site with Memberstack and Jetboost for a client. Feels like magic building with these tools. As someone who’s worked in an agency where some of these apps were coded from scratch, I finally get the hype now. This is a lot faster and a lot cheaper."

Félix Meens
Webflix Studio

"One of the best products to start a membership site - I like the ease of use of Memberstack. I was able to my membership site up and running within a day. Doesn't get easier than that. Also provides the functionality I need to make the user experience more custom."

Eric McQuesten
Health Tech Nerds
Off World Depot

"My business wouldn't be what it is without Memberstack. If you think $30/month is expensive, try hiring a developer to integrate custom recommendations into your site for that price. Incredibly flexible set of tools for those willing to put in some minimal efforts to watch their well put together documentation."

Riley Brown
Off World Depot

"The Slack community is one of the most active I've seen and fellow customers are willing to jump in to answer questions and offer solutions. I've done in-depth evaluations of alternative tools and we always come back to Memberstack - save yourself the time and give it a shot."

Abbey Burtis
Health Tech Nerds
Slack

Need help with this MemberScript? Join our Slack community!

Join the Memberstack community Slack and ask away! Expect a prompt reply from a team member, a Memberstack expert, or a fellow community member.

Join our Slack