Session Management in Site using Apex

Session Management in Site using Apex


Overview

Salesforce Sites provide built-in registration and login logic. Default Lightning Platform-branded VisualForce pages are associated with registration, login, forgot password, and password changes. You can modify these pages or replace them with your own.Create your custom login page in VisualForce, and associate it with your site. You can also create custom VisualForce pages for password, forgot password, and self-registration, check hb controls. You can add these login pages to your site regardless of the template.

Steps:

  1. Create A custom object with fields: Go to the setup and type Custom object into the Quick Find and click on the custom object and fill the details of the custom objects and the name as Login that has two fields: User Name & Password.

Login Custom Object

2.Create a visual-force login page (Login_Page.vfp): Go to the developer console. Click on the File->New->VisualForce Page. Give the name of the VisualForce page and save it.
Copy this code into your VisualForce page and save it. click now.
<apex:page standardStylesheets=”true” sidebar=”false” applyBodyTag=”false” showHeader=”false” >
<h2> Welcome to the Page. </h2>
</apex:page>

3.Create an Apex class controller for login page (Login_Page_Controller.apxc): Go to the developer console. Click on the File->New->Apex Class. Give a name of the class and save it.
Copy this code into your VisualForce page and save it.
public class Login_Page_Controller {
}

4.Create a site: Go to the setup and type site in the quick find/search and click on the site:

  • Click on the New button.
  • Feed your details into the site details.

On the Active Site Home Page, select your VisualForce page.

Active Site Home Page

5.Public Access Setting: Go to the setup and type site in the quick find/search and click on the site:

Click on the name of the site.

Active site-3

  • Click on the Public Access Setting from the top of the page.

active site-4

  • Go to the Enabled Apex Class Access section and click on the edit button and add your class into the Enabled Apex Classes section.
  • Go to the Enabled VisualForce Page Access section and click on the edit button and add your VF pages into the Enabled VisualForce Pages section.

6.Access/Permission: Go to the setup and type site in the quick find/search and click on the site:
Click on the name of the site.

Active site-5

Click on the Public Access Setting from the top of the page.

Active site-6

  • Click on the Edit button.
  • Go to the under Custom Object Permission section.
  • Check true for Login object and save it.

Object Permission-7

7.Platform Cache: Go to the setup and type Platform Cache in the quick find/search and click on the Platform Cache:

Platform Cache-8

Click on the New Platform Cache Partition button.

active site-9

8.Update the code: Open the developer console and open the visual-force page Login_Page.vfp and their controller Login_Page_Controller.apxc update the code that has been given.

Add Code Here : Login_Page_Controller.apxc :

Code Snippet

public class Login_Page_Controller {

    private static  String sessionId = ‘Person’;

    private Cache.OrgPartition part;

    String partitionName = ‘local.myPartition’;

    public Login_Page_Controller () {

        Cache.OrgPartition newpart = Cache.Org.getPartition(partitionName);

        part = newpart;

    }

    @AuraEnabled

    public static Boolean clearSession_Apex() {

        try {

            String sessionId = (String)Cache.Org.get(‘sessionId’);

            if (sessionId != null) {

                Cache.Org.remove(‘sessionId’);

                return true;

            }

            return false;

        } catch (Exception e) {

            System.debug(‘Get exception on line number ‘ + e.getLineNumber() + ‘   due to following method ‘ + e.getMessage());

            throw new AuraHandledException(‘Oops! Something went wrong: ‘ + e.getMessage() + e.getLineNumber());

        }

    }

    @AuraEnabled

    public static String isSessionAvailable_Apex() {

        try {

            String sessionId = (String)Cache.Org.get(‘sessionId’);

            if (sessionId != null) {

                return (String)Cache.Org.get(‘sessionId’);

            } 

            return null;

        } catch (Exception e) {

            System.debug(‘Get exception on line number ‘ + e.getLineNumber() + ‘   due to following method ‘ + e.getMessage());

            throw new AuraHandledException(‘Oops! Something went wrong: ‘ + e.getMessage() + e.getLineNumber());

        }

    }

    @AuraEnabled

    public static Login__c getLogin_Apex(String testUserName, String testPassword) {

        try {

            List<Login__c> login_list = new List<Login__c>();

            login_list = [SELECT Id, User_Name__c, Password__c FROM Login__c WHERE User_Name__c =: testUserName AND Password__c =: testPassword LIMIT 1];

            if(login_list.size() > 0) {

                String conId = login_list[0].Id;

                system.debug(‘conId–‘+conId);

                //if (!Cache.Session.contains(‘sessionId’)) {

                    //Cache.Session.put(sessionId, conId); 

                    //Cookie cook = new Cookie(‘value’, conId, null, -1, false);

                    // Pagereference pr = new Pagereference(‘/Login_Page’);

                    //Cookie cook = new Cookie(‘value’, conId, null, -1, false);

                    // pr.setCookies(new Cookie[] {cook});

                //}

                Cache.Org.put(‘sessionId’, conId);

                return login_list[0];

            } else { 

                return null;

            }

        } catch (Exception e) {

            System.debug(‘Get exception on line number ‘ + e.getLineNumber() + ‘   due to following method ‘ + e.getMessage());

            throw new AuraHandledException(‘Oops! Something went wrong: ‘ + e.getMessage() + e.getLineNumber());

        }

    }

}

Login_Page_Controller.txt

Displaying Login_Page_Controller.txt.

9.Create an application (login_form_App.app): Go to the developer console and create a lightning application with the name of login_form_App.
Add Code Here : login_form_App.app

Code Snippet

<aura:application extends=”ltng:outApp” access=”GLOBAL” implements=”ltng:allowGuestAccess”>

</aura:application>

10.Create a component (login_form.cmp): Go to the developer console and create a lightning component with the name of login_form.
Add Code Here : login_form.cmp

Code Snippet

<aura:component description=”login_form” controller=”Login_Page_Controller” access=”GLOBAL” implements=”force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction”>
<aura:attribute
name=”isLoginSuccess” type=”Boolean” default=”false” />
<aura:attribute name=”Spinner” type=”Boolean” default=”false” />
<aura:attribute name=”message” type=”String” default=”” />
<aura:handler name=”init” value=”{!this}” action=”{!c.doInit}”/>

<aura:handler event=”aura:waiting” action=”{!c.showSpinner}”/>
<aura:handler event=”aura:doneWaiting” action=”{!c.hideSpinner}”/>

<!– For Lightning Spinner Start Code –>
<aura:if isTrue=”{!v.Spinner}”>
<div aura:id=”spinnerId”>
<div role=”alert”>
<span>Loading</span>
<div></div>
<div></div>
</div>
</div>
</aura:if>
<!– For Lightning Spinner End Code –>

<div>
<aura:if isTrue=”{!v.isLoginSuccess}”>
<!– For Login Page Success :: Start Code –>
<div style=”background-color: currentColor”>
<div>
&nbsp;
</div>
<div>
&nbsp;
</div>
<div>
<lightning:button label=”Sign Out” title=”Neutral action” onclick=”{! c.outFromHere }”/>
</div>
</div>
<div>
<div>
<h2> Login Successfully! </h2>
</div>
</div>
<!– For Login Page Success :: End Code –>
<aura:set attribute=”else”>
<!– For Login Page Start Code –>
<div id=”login_Cmp”>
<form>
<div>
<img src=”data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAMAAACahl6sAAABNVB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ccWurxedWy4cclpFU34u2qaYGdGkSf1CCyiVC3JYCcOXIheWddpmaYuNaSBaZdswbwgQxjue9QNOO3YA7N7JhSNgaTLgmRKgmkbTtcstgT0rK4Q4ACNOC3pygXRDFTDB7YN5t61EUjLsZc2IthZt6akbBtOwd00qQSlvagSEB0+deATs9UF5QlkMDWLxpwEZEBSt+uCIBtpOVU+VZSqy3JpBipGA59uNVKmIaecEnwvC6rOpootB254YVdpIJK50EhKAPXIA9vpyro0kBpZ9NvkiwQEsHRZLpVkU0LFLWGQU1PuOvAFuSTYgqxhEB0KqWlVohGhmNWki+og25CcLnxb7gpVAd3aMGXHxu9AWHm8iU9DcZGCnK7hyEXjwjB5s4pAGrZ7hxCQKtiITUCygmTYQkmzJcPJNgypVIX6oBVtYo66bUgDvSoZAjrlDFKa7VwZkq3BF0CNpiRBTYFP9KpeMqQrohG4hVHKFiXJaAwc+LZtX8CBU9UFQ2qZyJ87wsrjNThdNbtFuIsMWjVOJWPACy3dtAVQc6Orw7MkfwuRQs4GqX7h82Rdl0HvJphnSjM1jefBDWnLi3UZf5jV+JQGng0cv47meeGcJru/4RP4NKvrznycXi6aWXy3lHtruBLdOsujr8IB/lk8np+fRs+AmlGE76VwKWQ0oYnvYIeA3FDmFu2XLNTX23gaapz8p7SiQW/NriuNkNqKnwZO5tpt9Op9uoG0K12SBrcf9PCUhpiXtdt5WLDt47XbeENb2cpWtrKVrWxlK1vZyla2spWtbGUrW/kZ5X/3jOELD3AYhAAAAABJRU5ErkJggg==” alt=”Avatar” />
</div>
<div>
<aura:if isTrue=”{!not(empty(v.message))}”>
<h2 aura:id=”messageFontColor”> {!v.message} </h2>
</aura:if>
<lightning:input name=”input1″ aura:id=”username” label=”User Name” />
<lightning:input type=”password” aura:id=”password” label=”Password” name=”input1″ />
<lightning:button label=”Log In” variant=”brand” title=”Log In” onclick=”{! c.validateJS }”/>
<label>
<input type=”checkbox” checked=”checked” name=”remember” /> Remember me
</label>
</div>
</form>
</div>
<!– For Login Page End Code –>
</aura:set>
</aura:if>
</div>
</aura:component>

11.Create a controller (login_formController.js): Add this code into the controller.js and save it.
Add Code Here: login_formController.js

Code Snippet

({
doInit : function(c, e, h) {
h.doInit_helper(c, e, h);
},
validateJS : function(c, e, h) {
var testLastName = c.find(‘username’).get(‘v.value’);
var testPassword = c.find(‘password’).get(‘v.value’);
if(!$A.util.isEmpty(testLastName) && (!$A.util.isEmpty(testPassword))) {
testLastName = testLastName.trim();
testPassword = testPassword.trim();
c.set(‘v.message’, ”);
h.validateJS_helper(c, e, h, testLastName, testPassword);
} else {
c.set(‘v.message’, ‘Please enter a valid Username & Password!’);
}

},
outFromHere : function(c, e, h) {
h.outFromHere_helper(c, e, h);
},
clearBtn : function(c, e, h) {
h.clearBtn_helper(c, e, h);
},
showSpinner: function(c, e, h) {
h.showSpinner_helper(c, e, h);
},
hideSpinner : function(c, e, h){
h.hideSpinner_helper(c, e, h);
},
})

12.Create a helper (login_formHelper.js): Add this code into the controller.js and save it.
Add Code Here: login_formHelper.js

Code Snippet

({

    doInit_helper : function(c, e, h) {

        try {

            h.showSpinner_helper(c, e, h);

            var action = c.get(“c.isSessionAvailable_Apex”);

            action.setCallback(this, function(response){

                var state = response.getState();

                if(state === ‘SUCCESS’){

                    var resp = response.getReturnValue();

                    //console.log(‘resp–>> ‘+JSON.stringify(resp));

                    if(!$A.util.isEmpty(resp) && resp != undefined) {

                        c.set(‘v.isLoginSuccess’, true);

                    }

                    h.hideSpinner_helper(c, e, h);

                }else if (state === ‘ERROR’){

                    var errors = response.getError();

                    if (errors) {

                        if (errors[0] && errors[0].message) {

                            console.log(“Error message: ” +

                                        errors[0].message);

                        }

                    } else {

                        console.log(“Unknown error”);

                    }

                }else{

                    console.log(‘Something went wrong, Please check with your admin’);

                }

            });

            $A.enqueueAction(action);

        } catch(ex){

            console.log(ex);

        }

    },

    validateJS_helper : function(c, e, h, testLastName, testPassword) {

        try {

            h.showSpinner_helper(c, e, h);

            var action = c.get(“c.getLogin_Apex”);

            action.setParams({

                testUserName : testLastName,

                testPassword : testPassword

            });

            action.setCallback(this, function(response){

                var state = response.getState();

                if(state === ‘SUCCESS’){

                    var resp = response.getReturnValue();

                    if(!$A.util.isEmpty(resp) && resp != undefined && !$A.util.isEmpty(resp.Id)) {

                        c.set(‘v.isLoginSuccess’, true);

                        c.set(‘v.message’, ”);

                    } else {

                        c.set(‘v.message’, ‘Please enter a valid Username & Password!’);

                    }

                    h.hideSpinner_helper(c, e, h);

                }else if (state === ‘ERROR’){

                    var errors = response.getError();

                    if (errors) {

                        if (errors[0] && errors[0].message) {

                            console.log(“Error message: ” +

                                        errors[0].message);

                        }

                    } else {

                        console.log(“Unknown error”);

                    }

                }else{

                    console.log(‘Something went wrong, Please check with your admin’);

                }

            });

            $A.enqueueAction(action);

        } catch(ex){

            console.log(ex);

        }

    },

    

    outFromHere_helper : function(c, e, h) {

        try {

            h.showSpinner_helper(c, e, h);

            var action = c.get(“c.clearSession_Apex”);

            action.setCallback(this, function(response){

                var state = response.getState();

                if(state === ‘SUCCESS’){

                    var resp = response.getReturnValue();

                    console.log(‘resp–>> ‘+JSON.stringify(resp));

                    if(!$A.util.isEmpty(resp) && resp != undefined && resp == true) {

                        c.set(‘v.isLoginSuccess’, false);

                    }

                    h.hideSpinner_helper(c, e, h);

                }else if (state === ‘ERROR’){

                    var errors = response.getError();

                    if (errors) {

                        if (errors[0] && errors[0].message) {

                            console.log(“Error message: ” +

                                        errors[0].message);

                        }

                    } else {

                        console.log(“Unknown error”);

                    }

                }else{

                    console.log(‘Something went wrong, Please check with your admin’);

                }

            });

            $A.enqueueAction(action);

        } catch(ex){

            console.log(ex);

        }

    },

    clearBtn_helper: function(c, e, h) {

        c.find(‘username’).set(‘v.value’, ”);

        c.find(‘password’).set(‘v.value’, ”);

    },

    showSpinner_helper: function(c, e, h) {

        c.set(“v.Spinner”, true); 

    },

    hideSpinner_helper : function(c, e, h){

       c.set(“v.Spinner”, false);

    },

})

13.Create a style (login_form.css): Add this code into the controller.js and save it.
Add Code Here: login_form.css

Code Snippet

.THIS {
}
.THIS body {font-family: Arial, Helvetica, sans-serif;}
/* Set a style for all buttons */
.THIS #login_Cmp button {
color: white;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
}

.THIS #login_Cmp button:hover {
opacity: 0.8;
}

/* Extra styles for the cancel button */
.THIS #login_Cmp .cancelbtn {
width: auto;
padding: 10px 18px;
background-color: #f44336;
}

/* Center the image and position the close button */
.THIS #login_Cmp .imgcontainer {
text-align: center;
margin: 24px 0 12px 0;
position: relative;
}

.THIS #login_Cmp img.avatar {
width: 30%;
border-radius: 50%;
}

.THIS #login_Cmp .container {
padding: 16px;
}

.THIS #login_Cmp>span.psw {
float: right;
padding-top: 16px;
}

/* The Modal (background) */
.THIS #login_Cmp .modal {
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
padding-top: 60px;
}

/* Modal Content/Box */
.THIS #login_Cmp .modal-content {
background-color: #fefefe;
margin: 5% auto 15% auto;
border: 1px solid #888;
width: 25%;
}

/* Add Zoom Animation */
.THIS #login_Cmp .animate {
-webkit-animation: animatezoom 0.6s;
animation: animatezoom 0.6s
}

14.Output video:

URL: https://embed.vidyard.com/share/9rvnh6cvtPgEfTbaZY7L3E?

If you need assistance with your Salesforce customization, integration, data migration, or implementation or Apex solutions, Cloud Analogy — one of the world’s leading Salesforce Development Companies — would be the right choice for you.


Leave a Reply

Close Menu
× How can I help you?