May 30, 2021

Lightning Web Component to find whether impersonated as a user using "Log in to Experience as User" in Salesforce Experience Cloud?

 

 
Sample LWC Code:
Apex Class:
public with sharing class LoggedInUserCheckController {
    
    @AuraEnabled( cacheable = true )    
    public static Boolean loggedInAsUserCheck() {
    
        Boolean loggedInAsUserBool = false;        
        Map < String, String > currentSessionInfo = Auth.SessionManagement.getCurrentSession();
        
        if ( currentSessionInfo.get( 'LoginHistoryId' ) == null &&
           currentSessionInfo.get( 'LoginType' ) == 'Unknown' &&
           currentSessionInfo.get( 'LogoutUrl' ) == null ) {
               
           loggedInAsUserBool = true;
           
       }

       return loggedInAsUserBool;
        
    }

}


LWC:
HTML:

<template>
    <lightning-card>
        Loggged in as Community User? {loggedInAsUserBool}
    </lightning-card>
</template>

JavaScript:
import { LightningElement, wire } from 'lwc';
import loggedInAsUserCheck from '@salesforce/apex/LoggedInUserCheckController.loggedInAsUserCheck';

export default class LoggedInUserCheck extends LightningElement {

    loggedInAsUserBool;

    @wire( loggedInAsUserCheck )  
    wiredData( value ) {

        const { data, error } = value;

        if ( data || data === false ) {
                            
            console.log( 'Data received from Apex ' + JSON.stringify( data ) );
            this.loggedInAsUserBool = data;

        } else if ( error ) {

            console.error( JSON.stringify( error ) );

        }

    }

}

js-meta.xml:
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>51.0</apiVersion>
    <isExposed>true</isExposed><targets>
    <target>lightningCommunity__Page</target>
</targets>
</LightningComponentBundle>
 
Output:
 
Admin Not Logged in as any user(without impersonation):
 
 
Admin when Logged in as an Experience Cloud User(with impersonation):


No comments:

Post a Comment