Sunday, January 31, 2016

Liferay User Account Registration Using Custom Portlet

In this example we will see how to create/add user in liferay using liferay mvc custom portlet plugin.
First we will register programmatically and just after user get registered we will logged in that user in portal.

STEPS:
Step 1: Add below property in portal-ext.poperties file.
session.enable.phishing.protection=false
Step2: Create one liferay mvc project name: Registration  of portlet plugin type.  Now create one portlet  inside that project .In this example portlet class/controller name: Register.java
Step 3: Add below lines in liferay-portlet.xml file, just after <icon></icon> tag.
<instanceable>false</instanceable>
<private-session-attributes>false</private-session-attributes>

Complete code of  liferay-portlet.xml
<?xml version="1.0"?>
<!DOCTYPE liferay-portlet-app PUBLIC "-//Liferay//DTD Portlet Application 6.2.0//EN" "http://www.liferay.com/dtd/liferay-portlet-app_6_2_0.dtd">

<liferay-portlet-app>
      
       <portlet>
              <portlet-name>register</portlet-name>
              <icon>/icon.png</icon>
              <instanceable>false</instanceable>
        <private-session-attributes>false</private-session-attributes>
              <header-portlet-css>/css/main.css</header-portlet-css>
              <footer-portlet-javascript>
                     /js/main.js
              </footer-portlet-javascript>
              <css-class-wrapper>register-portlet</css-class-wrapper>
       </portlet>
       <role-mapper>
              <role-name>administrator</role-name>
              <role-link>Administrator</role-link>
       </role-mapper>
       <role-mapper>
              <role-name>guest</role-name>
              <role-link>Guest</role-link>
       </role-mapper>
       <role-mapper>
              <role-name>power-user</role-name>
              <role-link>Power User</role-link>
       </role-mapper>
       <role-mapper>
              <role-name>user</role-name>
              <role-link>User</role-link>
       </role-mapper>
</liferay-portlet-app>
Step 4: Add below code in portlet view.jsp, path: docroot/html/register/view.jsp
<%@include file="init.jsp"%>

<%
String userExistMessage = Validator.isNotNull((String)request.getAttribute("USER_EXIST"))  ? (String)request.getAttribute("USER_EXIST") : null;

PortletURL registerUserURL=renderResponse.createActionURL();
registerUserURL.setParameter(ActionRequest.ACTION_NAME, "registration");
%>

              <%
              if(Validator.isNotNull(userExistMessage)){
              %>
                <div Style="color:red;"><%=userExistMessage%></div>
              <%}%>

<aui:form action="<%=registerUserURL%>" method="post">
                           <aui:input  name="firstName" label="" placeholder="First Name">
                          <aui:validator name="required"/>
                          <aui:validator name="alpha"/>
                </aui:input>                          
      
                           <aui:input  name="lastName"  label="" placeholder="Last Name" >
                                   <aui:validator name="required"/>
                          <aui:validator name="alpha"/>
                         </aui:input>
      
                         <aui:input  name="email" label="" placeholder="E-mail">
                                   <aui:validator name="required"/>
                          <aui:validator name="email"/>
                </aui:input>
      
                           <aui:input type="password"  name="password"  label="" placeholder="Password">
                           <aui:validator name="required"/>
                         </aui:input>
             
                           <aui:input type="password"  name="repass" label="" placeholder="Retype-Password">
                            <aui:validator name="equalTo">'#<portlet:namespace />password'</aui:validator>
                         </aui:input>
                           <aui:button type="submit" value="Register"/>
</aui:form>



Step 5: Create one new jsp name:init.jsp  page inside docroot/html/register/init.jsp
And add below code.
<%@page import="com.liferay.portal.kernel.util.Validator"%>
<%@page import="com.liferay.portal.kernel.util.ParamUtil"%>
<%@page import="javax.portlet.ActionRequest"%>
<%@page import="javax.portlet.PortletURL"%>
<%@ taglib uri="http://alloy.liferay.com/tld/aui" prefix="aui"%>
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects />
Step 6: Add below code in portlet controller, in this example controller name: Regsiter.java
package com.test;

import java.io.IOException;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.PortalClassLoaderUtil;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.model.CompanyConstants;
import com.liferay.portal.model.User;
import com.liferay.portal.service.ServiceContext;
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;


/**
 * Portlet implementation class Register
 */
public class Register extends MVCPortlet {

       public void registration(ActionRequest actionRequest,
                     ActionResponse actionResponse) throws IOException, PortletException, com.liferay.portal.kernel.exception.PortalException, com.liferay.portal.kernel.exception.SystemException {

              String firstName = ParamUtil.getString(actionRequest, "firstName").trim();
              String lastName = ParamUtil.getString(actionRequest, "lastName").trim();
              String email = ParamUtil.getString(actionRequest, "email").trim();
              String password = ParamUtil.getString(actionRequest, "password").trim();
              String confirmPassword = ParamUtil.getString(actionRequest, "repass");
             
              ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
             
              User user = null;
              try {
                         user =  UserLocalServiceUtil.fetchUserByEmailAddress(themeDisplay.getCompanyId(), email);
                         if(Validator.isNotNull(user)){
                            actionRequest.setAttribute("USER_EXIST", " User Exist with entered Email Address.");
                                  actionResponse.setRenderParameter("jspPage", "/html/register/view.jsp");
                         } else{
                            ServiceContext serviceContext = new ServiceContext();
                            HttpServletRequest request = PortalUtil.getHttpServletRequest(actionRequest);
                                  HttpServletResponse response = PortalUtil.getHttpServletResponse(actionResponse);
                                 
                            user = UserLocalServiceUtil.addUser(10198, themeDisplay.getCompanyId(), false, password, confirmPassword, true, null, email, 0L, "", themeDisplay.getLocale(),
                                                firstName, "", lastName, 0, 0, false, 0, 1,1970, "", null, null,null,null, false, serviceContext);
                                 
                                  ClassLoader pcl = PortalClassLoaderUtil.getClassLoader();
                             Class lClass = pcl.loadClass("com.liferay.portlet.login.util.LoginUtil");
                             java.lang.reflect.Method method = lClass.getDeclaredMethod("login", HttpServletRequest.class, HttpServletResponse.class, String.class, String.class, Boolean.TYPE, String.class);
                                 
                                  try{
                                         String portalURL = PortalUtil.getPortalURL(actionRequest);
                                         method.invoke(null, request, response, email, password, false, CompanyConstants.AUTH_TYPE_EA);
                                         actionResponse.sendRedirect(portalURL+"/web/guest/welcome");
                                  }catch(Exception e){
                                        
                                  }
                         }        
              } catch (Exception e) {
                           e.printStackTrace();
              }
       }
      
      

}


After deploying portlet.


OUTPUT: 

Change Liferay User Account Password Example 2

In this example we will see how to change/update liferay user account password.
In this approach we will match user account database password which is stored is database with user input current password which user will provide user as a currentPassword using liferay API. PasswordTrackerLocalServiceUtil

STEPS:
Step1: Create one liferay mvc project name: Passwordchanger  of portlet plugin type.  Now create one portlet  inside that project .In this example portlet class/controller name: ChangePassword.java
Step 2: Add below code in portlet view.jsp, path: docroot/html/changepassword/view.jsp
<%@ include file="init.jsp" %>

<portlet:defineObjects />


<%
PortletURL  updateUserPasswordURL = renderResponse.createActionURL();
updateUserPasswordURL.setParameter(actionRequest.ACTION_NAME, "changingMyPassword");
%>

<aui:form method="post" action="<%=updateUserPasswordURL%>">
  <liferay-ui:error key="currentPassNotMatched-key" message="Current Password is Not Matched."></liferay-ui:error>
  <liferay-ui:error key="currentPassMatched-key" message="New Password should be different from current password."></liferay-ui:error>
 
       <aui:fieldset cssClass="lfr-portrait-editor">
              <aui:input autoFocus="<%= true %>" type="password" label="Current Password" value="" name="currentPassword" autocomplete="off">
                       <aui:validator name="required" />
              </aui:input>
              <aui:input label="New Password" name="newPassword" size="30" type="password" value="">
                       <aui:validator name="required" />
              </aui:input>
              <aui:input label="Enter Again" name="confirmPassword" size="30" type="password" value="">
                       <aui:validator name="required" />
                            <aui:validator name="equalTo">
                                  '#<portlet:namespace />newPassword'
                            </aui:validator>
              </aui:input>
              <aui:button-row><aui:button type="submit"/></aui:button-row>
       </aui:fieldset>
</aui:form>


Step 5: Create one new jsp name:init.jsp  page inside docroot/html/changepassword/init.jsp
And add below code.
<%@page import="javax.portlet.PortletURL"%>
<%@page import="com.liferay.portal.kernel.util.WebKeys"%>
<%@page import="com.liferay.portal.theme.ThemeDisplay"%>
<%@ taglib uri="http://liferay.com/tld/aui" prefix="aui"%>
<%@ taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui" %>
<%@page import="com.liferay.portal.service.UserLocalServiceUtil"%>
<%@page import="com.liferay.portal.model.User"%>
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
Step 6: Add below code in portlet controller, in this example controller name: ChangePassword.java
package com.test;

import java.io.IOException;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;

import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.servlet.SessionMessages;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.service.PasswordTrackerLocalServiceUtil;
import com.liferay.portal.service.UserLocalServiceUtil;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.util.bridges.mvc.MVCPortlet;

/**
 * Portlet implementation class ChangePassword
 */
public class ChangePassword extends MVCPortlet {

       public void changingMyPassword(ActionRequest actionRequest,
                     ActionResponse actionResponse) throws IOException, PortletException {
             
              ThemeDisplay themeDisplay = (ThemeDisplay)actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
             
              String userInputcurrentPassword = (String) actionRequest.getParameter("currentPassword").trim();
              String newPass = (String) actionRequest.getParameter("newPassword").trim();
              String confirmPass = (String) actionRequest.getParameter("confirmPassword").trim();
             
              try {
                     boolean  userInputcurrentPassDatapassMatched =  PasswordTrackerLocalServiceUtil.isSameAsCurrentPassword(themeDisplay.getUserId(), userInputcurrentPassword);
                     if(!userInputcurrentPassDatapassMatched){
                            SessionErrors.add(actionRequest, "currentPassNotMatched-key", "Sorry, Current Password Not Matched");
                            actionResponse.setRenderParameter("jspPage", "/html/changepassword/view.jsp");
                     } else if(userInputcurrentPassword.equals(newPass) || userInputcurrentPassword.equals(confirmPass) ){
                            SessionErrors.add(actionRequest, "currentPassMatched-key", "Sorry, New Password should be different from current password");
                            actionResponse.setRenderParameter("jspPage", "/html/changepassword/view.jsp");
                     } else if (userInputcurrentPassDatapassMatched && newPass.equals(confirmPass)){
                           UserLocalServiceUtil.updatePassword(themeDisplay.getUserId(), newPass,confirmPass, false);
                           SessionMessages.add(actionRequest, "request_processed", "User Account Password updated successfully.");
                           actionResponse.setRenderParameter("jspPage", "/html/changepassword/view.jsp");
                     }
              } catch (PortalException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
              } catch (SystemException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
              }
       }
}


After deploying portlet.

OUTPUT:

Login using your account credential,
Example :
Password: test