Sunday, 14 December 2014

Forgot Password implementation in Liferay


Hooking  login.jsp  And redirect to forgot password page which is hidden. I created forgot password portlet and added it to forgot password page .

And also removed Create Account link and forgot password link.
I create forgot password button which will redirect to forgot password page where we can enter email-Id  when we send it, it will fetch password from data base and send it to that email-Id .



<%
StringBundler forgotPasswordURL = null;
try{
       forgotPasswordURL = new StringBundler(7); //to create url for forget password page
     
               forgotPasswordURL.append(themeDisplay.getURLPortal()); //http://localhost:8080
forgotPasswordURL.append("/web/guest/forgot-password");
}
      catch(Exception e){
System.out.println("exception1");
}
%>
<a class="button" href="<%= forgotPasswordURL %>">Forgot Password</a>


Create a portlet  forgot password

view.jsp

<%@page import="com.liferay.portal.kernel.util.Validator"%>
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<%@taglib uri="http://liferay.com/tld/aui" prefix="aui" %>
<%@page import="javax.portlet.PortletURL" %>
<%@page import="javax.portlet.ActionRequest" %>
<portlet:defineObjects />

<%
 

  PortletURL forgotPasswordURL = renderResponse.createActionURL();
      forgotPasswordURL.setParameter(ActionRequest.ACTION_NAME,"fetchPassword");
    String userFound = (String)renderRequest.getAttribute("userFound");
   if(Validator.isNotNull(userFound)){
    if(userFound.equalsIgnoreCase("false")){
    %>
    <h3>Please signup, you are not register user.</h3>
    <%
    }
    else{
    %>
    <h3>Please check your mail, password sent to your mail.</h3>
    <%
    }
   }
   
    %>

<aui:form action="<%=forgotPasswordURL %>" method="post">

    <aui:input  name="emailId" id="emailId" lable="Email-Id" type="text" >
  <aui:validator name="required" />
  <aui:validator name="email"/>
    </aui:input>
 
    <aui:button type="submit" value="send" />
</aui:form>

Acion Class

ForgotPassword.java


package com.test;

import java.io.IOException;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import org.apache.log4j.Logger;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;
import com.slayer.model.BusinessUser;
import com.slayer.model.RegCustomer;
import com.slayer.service.BusinessUserLocalServiceUtil;
import com.slayer.service.RegCustomerLocalServiceUtil;

/**
 * Portlet implementation class forgotPassword
 */
public class forgotPassword extends MVCPortlet {
private static final Logger log = Logger.getLogger(forgotPassword.class);

public void fetchPassword(ActionRequest actionRequest, ActionResponse actionResponse)
throws IOException,PortletException
{
RegCustomer regCustomer = null;
BusinessUser businessUser = null;
String userFound = "false";
String emailId= ParamUtil.getString(actionRequest,"emailId");
//log.info("email ID  is "+emailId);
try{
 businessUser = BusinessUserLocalServiceUtil.getBusinessUser(emailId);
 //log.info("Bbuser: "+businessUser);
 userFound = "businessUser";
}
catch(Exception e){
 //log.error(e);
 try{
 regCustomer = RegCustomerLocalServiceUtil.getRegCustomer(emailId);
 //log.info("regCustomer: "+regCustomer);
 userFound = "regCustomer";
 }
 catch (Exception e1) {
 log.error(e1);
 }
}
//log.info("userFound: "+userFound);
if(userFound.equalsIgnoreCase("false")){
actionRequest.setAttribute("userFound", userFound);
}
else if(userFound.equalsIgnoreCase("businessUser")){
actionRequest.setAttribute("userFound", userFound);
log.info("B: pwd: "+businessUser.getPassword());
}
else if(userFound.equalsIgnoreCase("regCustomer")){
actionRequest.setAttribute("userFound", userFound);
log.info("U: pwd: "+regCustomer.getPassword());
}
}
}



I fetch data from two table BusinessUser and  RegCustomer




Friday, 12 December 2014

How to remove default success message in liferay

Add the shaded code in your portlet.xml file

<portlet>
<portlet-name>forgotpassword</portlet-name>
<display-name>forgot Password</display-name>
<portlet-class>com.test.forgotPassword</portlet-class>
<init-param>
<name>view-template</name>
<value>/html/forgotpassword/view.jsp</value>

</init-param>
<init-param>
                   <name>add-process-action-success-action</name>
                   <value>false</value>
             </init-param>
<expiration-cache>0</expiration-cache>
<supports>
<mime-type>text/html</mime-type>
<portlet-mode>view</portlet-mode>
</supports>

<portlet-info>
<title>forgot Password</title>
<short-title>forgot Password</short-title>

<keywords></keywords>
</portlet-info>
<security-role-ref>
<role-name>administrator</role-name>
</security-role-ref>
<security-role-ref>
<role-name>guest</role-name>
</security-role-ref>
<security-role-ref>
<role-name>power-user</role-name>
</security-role-ref>
<security-role-ref>
<role-name>user</role-name>
</security-role-ref>
</portlet>

you can also change session message through action class

SessionMessages.add(actionRequest, "request_processed", "your msg will be here");

addProcessActionSuccessMessage= false;

Wednesday, 10 December 2014

what are the thing we can customize in portal-ext.properties file

##
## Company
##

#
# This sets the default web id. Omniadmin users must belong to the company
# with this web id.
#
company.default.web.id=liferay.com

#
# The portal can authenticate users based on their email address, screen
# name, or user id.
#
company.security.auth.type=emailAddress
#company.security.auth.type=screenName
#company.security.auth.type=userId

#
# Set this to true to ensure users login with https.
#
company.security.auth.requires.https=false

#
# Set the following to true to allow users to select the "remember me"
# feature to automatically login to the portal.
#
company.security.auto.login=true

#
# Set the following to the maximum age (in number of seconds) of the browser
# cookie that enables the "remember me" feature. A value of 31536000
# signifies a lifespan of one year. A value of -1 signifies a lifespan of a
# browser session.
#
# Rather than setting this to 0, set the property
# "company.security.auto.login" to false to disable the "remember me"
# feature.
#
company.security.auto.login.max.age=31536000

#
# Set the following to true to allow users to ask the portal to send them
# their password.
#
company.security.send.password=true

#
# Set the following to true to allow strangers to create accounts and
# register themselves on the portal.
#
company.security.strangers=true

#
# Set the following to true if strangers can create accounts with email
# addresses that match the company mail suffix. This property is not used
# unless "company.security.strangers" is also set to true.
#
company.security.strangers.with.mx=true

#
# Set the following to true if strangers who create accounts need to be
# verified via email.
#
company.security.strangers.verify=false

#
# Set the following to true to allow community administrators to use their
# own logo instead of the enterprise logo.
#
company.security.community.logo=true

Monday, 8 December 2014

Ajax Call Country Region


<%@page import="javax.portlet.ActionResponse"%>
<%@ include file="/html/reg/init.jsp" %>
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<%@taglib uri="http://liferay.com/tld/aui" prefix="aui" %>
<%@page import="com.liferay.portal.model.Country"%>
<%@page import="com.liferay.portal.service.CountryServiceUtil"%>

<portlet:defineObjects />

<%
  PortletURL formURL=renderResponse.createActionURL();
  formURL.setParameter(ActionRequest.ACTION_NAME, RegConstants.ACTION_FORM );
 
            /*Edit regestration form */
 
  REGForm regForm = new REGFormImpl();
  long regId =ParamUtil.getLong(request, "bookId");
 
  if (regId > 01){
   regForm = REGFormLocalServiceUtil.fetchREGForm(regId);
  }
%>


<aui:form name="fm" method="POST" action="<%=formURL.toString()%>">
<%-- <aui:input name="redirectURL" type="hidden"
    value="<%=renderResponse.createRenderURL().toString()%>"/> --%>
   
  <aui:input name="regId" type="hidden" value="<%=regForm.getRegId() %>"/>
 
  <aui:input name="userName" label="User Name" value="<%=regForm.getUserName()%>">
          <aui:validator name="required"/>      
   </aui:input>
 
   <aui:input name="email" label="Email Id" value="<%=regForm.getEmail() %>">
         <aui:validator name="required"/>
         <aui:validator name="email"/>
   </aui:input>
 
   <aui:input name="dob" label="Date Of Birth" id="dob"  value="<%=regForm.getDob()%>" >
          <aui:validator name="date"/>
   </aui:input>      
   <aui:input name="contact" label="Contact No" value="<%=regForm.getContact() %>">
             <aui:validator name="number"/>
             <aui:validator name="minLength">10</aui:validator>
              <aui:validator name="maxLength">10</aui:validator>
   </aui:input>
   <aui:select name="countryId" id="countryId" label="country"
                onChange="javascript:listRegions(this)"/>
   <aui:select  name="regionId" id="regionId" label="City" />
     

 
  <%--   <aui:input type="file" name="uploadResume" size="75"/>  --%>
 
   <aui:button type="submit" value="Submit"/>
</aui:form>

 <aui:script>
     Liferay.Util.focusFormField(
          document.<portlet:namespace/>fm.<portlet:namespace/>userName);
         
 </aui:script>
 <aui:script>
AUI().ready(function(A){
var frm = document.<portlet:namespace/>fm;
var countries = frm.<portlet:namespace/>countryId;

Liferay.Service(
'/country/get-countries',
{ active: true },
function(obj) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var name = obj[key].name;
var countryId = obj[key].countryId;
countries.options[key] = new Option(name,countryId);
}
}
}
);
});

function listRegions(country) {
var frm = document.<portlet:namespace/>fm;
var regions = frm.<portlet:namespace/>regionId;

var _countryId = country.value;

regions.disabled = (_countryId <= 0);

if (_countryId <= 0) {
regions.selectedIndex = 0;
} else {
// calling regions of this country
var payload = {
countryId: _countryId,
active: true
};

Liferay.Service.Portal.Region.getRegions(payload,
function(data) {

regions.options.length = data.length;
for (var i=0; i<(data.length-1); i++) {
var rgn = data[i];
regions.options[i] =
new Option(rgn.name, rgn.regionId);
}

}
);
}
}
</aui:script>


<%
    PortletURL listRegsURL=renderResponse.createRenderURL();
    listRegsURL.setParameter("jspPage","/html/reg/list.jsp");
%>
   &nbsp;|&nbsp;
   <a href="<%= listRegsURL.toString()%>">Show All Register Detail &raquo;</a>

Saturday, 8 November 2014

How to reuse (instanceable) my custom portlet more than one time in my page

Way to get more than one instance of a portlet

 Open liferay-portlet.xml file

 edit the file

<portlet>
<portlet-name>AddOnDirectory</portlet-name>
<icon>/icon.png</icon>

<instanceable>false</instanceable> --- modified this to 

<instanceable>true</instanceable>

 Then deploy to server. After that add your portlet instance as many you want on a page.

hook


Saturday, 1 November 2014

How to customize create user in liferay using Hook

In post this we will customize  Liferay Create account functionality using Liferay hooks.



In this page we have to add a field. We will add a field  named as "Social Security Number"



Step 1: Creation of custom Field 

   We are customizing  user registration. Therefore we are going to create a new custom field for the Entity User. Create the custom field from control panel as below. Our key is ssn.



we have to set appropriate permission for the custom field. Because the guest user i.e., at the time of creating new account this field will be viewed and updated.Set the permission as shown in the screen shot



Step 2: Create language hook in our example-hook project. The key should be ssn in the language file .



   Put ssn=Social Security Number  in language_en.properties file

    
      Before deploy language hook



     After deploy language hook


Step 3: Create JSP hook 


Open create_account.jsp and add this code

 <div class="exp-ctrl-holder">
    <liferay-ui:custom-attribute
        className="<%= User.class.getName() %>"
        classPK="<%= 0 %>"
        editable="<%= true %>"
        label="<%= true %>"
        name="ssn"
    /> 
 </div>

The above code will render one input box with label Social Security Number.

   

 The name attribute in the above code we have given the same key ssn as we entered in the control panel in the Step 1. The benefit of this tag is that we don’t need to do any other thing to persist the data. Once the form is submitted the data entered in the expando field will be also saved in the expando column in the database.

Step 4: Validation of the newly added field 

We have added the field and now we are able to persist the data also. But we need to do some server side validation also. Say SSN should be always numeric. To achieve this we can override struts action by hook.

Creating Struts action



Open  CustomCreateAccountAction.java file and put this code

package com.proliferay.demo;
 
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletConfig;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
 
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.struts.BaseStrutsPortletAction;
import com.liferay.portal.kernel.struts.StrutsPortletAction;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.util.PortalUtil;
import com.liferay.portlet.expando.model.ExpandoColumnConstants;
 
/**
 *
 * @author Hamidul Islam
 *
 * Discover more in
 * www.proliferay.com
 *
 */
 
public class CustomCreateAccountAction extends BaseStrutsPortletAction{
 
    /**
     * This is the custom process action
     *
     * In this process action we are reading custom field which is entered from create account form
     *
     * After reading the custom field we are calling the original process action
     */
    public void processAction(
            StrutsPortletAction originalStrutsPortletAction,
            PortletConfig portletConfig, ActionRequest actionRequest,
            ActionResponse actionResponse)
        throws Exception {
         
         
        String ssnValue = (String)PortalUtil.getExpandoValue(actionRequest, "ExpandoAttribute--" + "ssn" + "--", ExpandoColumnConstants.STRING, ExpandoColumnConstants.PROPERTY_DISPLAY_TYPE_TEXT_BOX);
        System.out.println("##################ssnValue###########################################"+ssnValue);
        if(!Validator.isNumber(ssnValue)){
            SessionErrors.add(actionRequest,"wrong-ssn");
            return;
        }
         
         
        originalStrutsPortletAction.processAction(
            originalStrutsPortletAction, portletConfig, actionRequest,
            actionResponse);
    }
     
     
    /**
     * After process action this method is invoked
     *
     * From inside of this method we are again calling the original render method
     */
    public String render(
            StrutsPortletAction originalStrutsPortletAction,
            PortletConfig portletConfig, RenderRequest renderRequest,
            RenderResponse renderResponse)
        throws Exception {
 
        return originalStrutsPortletAction.render(
                originalStrutsPortletAction, portletConfig, renderRequest, renderResponse);
 
    }
 
}


Note 1: We overridden  struts /login/create_account
Note 2: To read custom attribute value we have used  PortalUtil.getExpandoValue
Note 3: Our custom field key is ssn. When its rendered by liferay-ui:custom-attribute the                name of the field would be like this ExpandoAttribute–ssn–

Note 4: We have added the below code in create_account.jsp for displaying error message

<liferay-ui:error key=”wrong-ssn” message=”The SSN number is not correct”/>



The final liferay-hook.xml

<?xml version="1.0"?>
<!DOCTYPE hook PUBLIC "-//Liferay//DTD Hook 6.2.0//EN" "http://www.liferay.com/dtd/liferay-hook_6_2_0.dtd">
 
<hook>
    <language-properties>
        content/language.properties
    </language-properties>
    <custom-jsp-dir>/custom_jsps</custom-jsp-dir>
    <struts-action>
        <struts-action-path>/login/create_account</struts-action-path>
        <struts-action-impl>com.proliferay.demo.CustomCreateAccountAction</struts-action-impl>
    </struts-action>
</hook>