Custom Login Portet In Liferay.

Sometimes liferay developer needs create custom login/signin protlet for their requirement. Here share my experience how one can create  custom login portlet in liferay.

Dowload the portlet form github

Step 1: jsp file >>> Replace the view.jsp file with the below code.

<%--
/**
* tariqliferay.blogspot.com
*/
--%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>

<%@ taglib uri="http://liferay.com/tld/aui" prefix="aui" %>
<%@ taglib uri="http://liferay.com/tld/ddm" prefix="liferay-ddm" %>
<%@ taglib uri="http://liferay.com/tld/portlet" prefix="liferay-portlet" %>
<%@ taglib uri="http://liferay.com/tld/security" prefix="liferay-security" %>
<%@ taglib uri="http://liferay.com/tld/theme" prefix="liferay-theme" %>
<%@ taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui" %>
<%@ taglib uri="http://liferay.com/tld/util" prefix="liferay-util" %>

<%@ page import="com.liferay.portal.CookieNotSupportedException" %>
<%@ page import="com.liferay.portal.NoSuchUserException" %>
<%@ page import="com.liferay.portal.PasswordExpiredException" %>
<%@ page import="com.liferay.portal.UserEmailAddressException" %>
<%@ page import="com.liferay.portal.UserLockoutException" %>
<%@ page import="com.liferay.portal.UserPasswordException" %>
<%@ page import="com.liferay.portal.UserScreenNameException" %>
<%@ page import="com.liferay.portal.kernel.language.LanguageUtil" %>
<%@ page import="com.liferay.portal.kernel.util.ClassResolverUtil" %>
<%@ page import="com.liferay.portal.kernel.util.Constants" %>
<%@ page import="com.liferay.portal.kernel.util.GetterUtil" %>
<%@ page import="com.liferay.portal.kernel.util.HtmlUtil" %>
<%@ page import="com.liferay.portal.kernel.util.MethodKey" %>
<%@ page import="com.liferay.portal.kernel.util.ParamUtil" %>
<%@ page import="com.liferay.portal.kernel.util.PortalClassInvoker" %>
<%@ page import="com.liferay.portal.kernel.util.PropsUtil" %>
<%@ page import="com.liferay.portal.model.Company" %>
<%@ page import="com.liferay.portal.util.PortalUtil"%>
<%@ page import="com.liferay.portal.util.PortletKeys"%>
<%@ page import="com.liferay.portal.kernel.util.CalendarUtil"%>
<%@ page import="com.liferay.portal.security.auth.AuthException" %>
<%@page import="com.liferay.portal.kernel.portlet.LiferayWindowState"%>
<%@page import="com.liferay.portlet.PortletURLFactoryUtil"%>

<%@
page import="javax.portlet.MimeResponse" %><%@
page import="javax.portlet.PortletConfig" %><%@
page import="javax.portlet.PortletContext" %><%@
page import="javax.portlet.PortletException" %><%@
page import="javax.portlet.PortletMode" %><%@
page import="javax.portlet.PortletPreferences" %><%@
page import="javax.portlet.PortletRequest" %><%@
page import="javax.portlet.PortletResponse" %><%@
page import="javax.portlet.PortletURL" %><%@
page import="javax.portlet.ResourceURL" %><%@
page import="javax.portlet.UnavailableException" %><%@
page import="javax.portlet.ValidatorException" %><%@
page import="javax.portlet.WindowState" %><%@
page import="java.util.*" %><%@
page import="java.text.*" %><%@
page contentType="text/html; charset=UTF-8" %>

<portlet:defineObjects />
<liferay-theme:defineObjects />

<script type="text/javascript" src="<%= request.getContextPath()%>/js/jquery.min.js"></script>


<%
    themeDisplay.setIncludePortletCssJs(true);
    themeDisplay.setThemeJsFastLoad(true);
    themeDisplay.setThemeCssFastLoad(true);
    themeDisplay.setThemeImagesFastLoad(true);
    themeDisplay.setThemeJsBarebone(true);
%>

<%
    String addStatus = ParamUtil.getString(request, "addStatus");
    String backURL = ParamUtil.getString(request, "backURL");
    if(addStatus==null){
        addStatus="";
    }
%>

<portlet:actionURL var="customloginURL" name="customlogin"/>

<liferay-ui:error key="authentication-failed"  message="authentication-failed"/> 

<c:set var="isSign" value="<%= themeDisplay.isSignedIn() %>"/>

<c:choose>
<c:when test="<%= themeDisplay.isSignedIn() %>">
    <%
    String signedInAs = user.getFullName();
    if (themeDisplay.isShowMyAccountIcon()) {
    signedInAs = "<a href=\"" + themeDisplay.getURLMyAccount().toString() + "\">" + signedInAs + "</a>";
    }
    %>

</c:when>
<c:otherwise>
    <%
    MethodKey methodKey = new MethodKey(ClassResolverUtil.resolveByPortalClassLoader("com.liferay.portlet.login.util.LoginUtil"), "getLogin", HttpServletRequest.class, String.class, Company.class);
    String login = GetterUtil.getString((String)PortalClassInvoker.invoke(false, methodKey, request, "login", company));
    boolean rememberMe = ParamUtil.getBoolean(request, "rememberMe");
    %>
   
    <aui:form action="<%= customloginURL %>" method="post" name="signinform" cssClass="form-signin" id="signinform">
        <aui:input name="saveLastPath" type="hidden" value="<%= false %>" />
        <aui:input name="<%= Constants.CMD %>" type="hidden" value="<%= Constants.UPDATE %>" />
        <aui:input name="rememberMe" type="hidden" value="<%= rememberMe %>" />
        <liferay-ui:error exception="<%= AuthException.class %>" message="authentication-failed" />
        <liferay-ui:error exception="<%= CookieNotSupportedException.class %>" message="authentication-failed-please-enable-browser-cookies" />
        <liferay-ui:error exception="<%= NoSuchUserException.class %>" message="please-enter-a-valid-login" />
        <liferay-ui:error exception="<%= PasswordExpiredException.class %>" message="your-password-has-expired" />
        <liferay-ui:error exception="<%= UserEmailAddressException.class %>" message="please-enter-a-valid-login" />
        <liferay-ui:error exception="<%= UserLockoutException.class %>" message="this-account-has-been-locked" />
        <liferay-ui:error exception="<%= UserPasswordException.class %>" message="please-enter-a-valid-password" />
        <liferay-ui:error exception="<%= UserScreenNameException.class %>" message="please-enter-a-valid-screen-name" />
        <input type="text" name="<portlet:namespace/>login" class="input-block-level" placeholder="<liferay-ui:message key="your-email-address" />" required>
        <input type="password" name="<portlet:namespace/>password" class="input-block-level signpwd" placeholder="<liferay-ui:message key="your-password" />" required>
       
        <br/>
        <a onclick="document.getElementById('<portlet:namespace/>signinform').submit();" class="parent" href="#">
            <div class="child1">
                <span class="pull-right" style="padding-top: 7px;color: #bd1e51;text-decoration: none; "><liferay-ui:message key="sign-in"/></span>
            </div>
        </a>
        <br/>
    </aui:form>

</c:otherwise>
</c:choose>

<style type="text/css">
      body {
        padding-top: 40px;
        padding-bottom: 40px;
        background-color: #f5f5f5;
      }

      .form-signin {
        max-width: 300px;
        padding: 19px 29px 29px;
        margin: 0 auto 20px;
        background-color: #fff;
      }
      .form-signin .form-signin-heading,
      .form-signin .checkbox {
        margin-bottom: 10px;
      }
      .form-signin input[type="text"], .form-signin input[type="password"] {
        font-size: 16px;
        height: auto;
        padding: 7px 9px;
        border: none;
        background: #F0F0F0;
        margin: 0;
      }
      .signpwd {
        border-top: 1px solid #A3A3A3 !important;
        margin-bottom: 20px !important;
      }
      .form-signin h2.form-signin-heading {
        font-size: 25px;
        margin-bottom: 20px;
        text-transform: uppercase;
      }
     
      .container-fluid a, .container-fluid a:HOVER, .lfr-discussion-posted-on a, .lfr-discussion-posted-on a:HOVER{
        color: #bd1e51;
        text-decoration: none;
     }

    </style>
   
<script type="text/javascript">

    $("input").keypress(function(event) {
        if (event.which == 13) {
            event.preventDefault();
            document.getElementById('<portlet:namespace/>signinform').submit();
        }
    });
   
</script>

Step 2: Portlet Class File>>>>







/**
 *
 */
package tariqliferay.blogspot.com;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletConfig;
import javax.portlet.PortletException;
import javax.portlet.ProcessAction;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.servlet.http.HttpServletRequest;

import com.liferay.portal.kernel.dao.orm.Criterion;
import com.liferay.portal.kernel.dao.orm.DynamicQuery;
import com.liferay.portal.kernel.dao.orm.DynamicQueryFactoryUtil;
import com.liferay.portal.kernel.dao.orm.RestrictionsFactoryUtil;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.portlet.LiferayPortletConfig;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.servlet.SessionMessages;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.JavaConstants;
import com.liferay.portal.kernel.util.MapUtil;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.PortalClassLoaderUtil;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.model.Company;
import com.liferay.portal.model.User;
import com.liferay.portal.security.auth.AuthException;
import com.liferay.portal.security.auth.Authenticator;
import com.liferay.portal.service.UserLocalServiceUtil;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.portal.util.PortalUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;

/**
 * @author tariqliferay.blogspot.com
 *
 */
public class CustomLogin extends MVCPortlet{
   
    @Override
    public void doView(RenderRequest renderRequest,
            RenderResponse renderResponse) throws IOException, PortletException {
        // TODO Auto-generated method stub
        super.doView(renderRequest, renderResponse);
    }
   
    @Override
    public void render(RenderRequest request, RenderResponse response)
            throws PortletException, IOException {
        // TODO Auto-generated method stub
        super.render(request, response);
    }
   
    /**
     * @author tariqliferay.blogspot.com
     */
    @ProcessAction(name="customlogin")
    public void customlogin(ActionRequest actionRequest,
            ActionResponse actionResponse) throws IOException, PortletException {
        ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
        PortletConfig portletConfig = (PortletConfig)actionRequest.getAttribute(JavaConstants.JAVAX_PORTLET_CONFIG);
        LiferayPortletConfig liferayPortletConfig = (LiferayPortletConfig) portletConfig;
        SessionMessages.add(actionRequest, liferayPortletConfig.getPortletId() + SessionMessages.KEY_SUFFIX_HIDE_DEFAULT_ERROR_MESSAGE);
        try {
           
            boolean isAuthenticated=false;
            String login = ParamUtil.getString(actionRequest, "login");
            String password = ParamUtil.getString(actionRequest, "password");
           
            long userId= -1;
            userId=    getAuthenticatedUserId(themeDisplay.getRequest(), login, password);
           
            List<User> userList= getUsersByEmailAddress(login);
            if(userList!=null&&userList.size()>0&&userId>=0){
               
                for(User user:userList){
                    if(userId==user.getUserId()){
                        if(user.getPasswordReset()){
                            user.setPasswordModifiedDate(new Date());
                            user.setPasswordModified(true);
                            user.setPasswordReset(false);
                            UserLocalServiceUtil.updateUser(user);
                        }
                        isAuthenticated=true;
                    }
                }
               
            }

            if(isAuthenticated){
               
                String rememberMe = ParamUtil.getString(actionRequest, "rememberMe");   
                String redirecturl=PortalUtil.getPortalURL(themeDisplay)+themeDisplay.getLayout().getFriendlyURL();

                String redirect = PortalUtil.getPathMain() + "/portal/login?login="+ login + "&password=" + password + "&rememberMe="+ rememberMe+"&redirect="+redirecturl;
                actionResponse.sendRedirect(redirect);
               
            }
           
       
        }catch (Exception e) {
            // TODO Auto-generated catch block
            System.out.println("Login Error"+e.toString());
            SessionErrors.add(actionRequest, "authentication-failed");
        }
   

    }
   
    /**
     * @author tariqliferay.blogspot.com
     */
    public  long getAuthenticatedUserId(HttpServletRequest request, String login, String password)
        throws PortalException, SystemException {

        long userId = GetterUtil.getLong(login);

        Company company = PortalUtil.getCompany(request);

        String requestURI = request.getRequestURI();

        String contextPath = PortalUtil.getPathContext();

        if (requestURI.startsWith(contextPath.concat("/api/liferay"))) {
            throw new AuthException();
        }
        else {
            Map<String, String[]> headerMap = new HashMap<String, String[]>();

            Enumeration<String> enu1 = request.getHeaderNames();

            while (enu1.hasMoreElements()) {
                String name = enu1.nextElement();

                Enumeration<String> enu2 = request.getHeaders(name);

                List<String> headers = new ArrayList<String>();

                while (enu2.hasMoreElements()) {
                    String value = enu2.nextElement();

                    headers.add(value);
                }

                headerMap.put(
                    name, headers.toArray(new String[headers.size()]));
            }

            Map<String, String[]> parameterMap = request.getParameterMap();
            Map<String, Object> resultsMap = new HashMap<String, Object>();

            int authResult = Authenticator.FAILURE;

       
            authResult = UserLocalServiceUtil.authenticateByEmailAddress(
                company.getCompanyId(), login, password, headerMap,
                parameterMap, resultsMap);

            userId = MapUtil.getLong(resultsMap, "userId", userId);
           
       

            if (authResult != Authenticator.SUCCESS) {
                throw new AuthException();
            }
        }

        return userId;
    }
   
    /**
     * @author tariqliferay.blogspot.com
     * @param emailAddress
     * @return
     */
    private List<User> getUsersByEmailAddress(String emailAddress) {
       
        try {
            DynamicQuery userQuery = DynamicQueryFactoryUtil.forClass(User.class,PortalClassLoaderUtil.getClassLoader());
            Criterion criterion = RestrictionsFactoryUtil.eq("emailAddress",emailAddress);
            userQuery.add(criterion);
            List<User> userList = UserLocalServiceUtil.dynamicQuery(userQuery);
            return userList;
    } catch (SystemException e) {
        // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    private static Log _log = LogFactoryUtil.getLog(CustomLogin.class);

}

Enjoy....

Comments

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. Useful post

    This is working for me , But request is sent as GET type , username nd password is visible .. I want to send it as POST request . Need suggestion ?

    ReplyDelete

Post a Comment

Popular posts from this blog

How to run ofbiz as ubuntu Service.

JPA vs Spring JPA vs Spring Data JPA vs Hibernate

Java Array Interview Questions for Entry-Level Developers Part 01