lundi 28 septembre 2015

How to verify user email adress Using JSF/Hibernate/Spring


How to verify your new users email addresses after sending a mail to their in-box containing a specific link which holds a key identifying the user to be verified.






The Approach :
- Checking if the URL contains parameter Generated Key to invoke the Verification method in the Managed Bean
- Rendering the verification page depending on passed parameter in URL
- Checking with database if any user have the validation generated key [1]
- Update user account status to not require any more validation

The Tool box :

- JSF 2.2 [User Interface Management]
- Spring 2.4.0.Release [Layers Management]
- Hibernate 4.0.1.Final [Database Management]

- Apache Tomcat 8.0 [Server Instance]

  • We are assuming that you know how to setup a Spring/Hibernate/JSF project, otherwise you can check this link before starting.
  • We are assuming that you already have a method sending to user a mail with a generated key in URL (linksample.xhtml?key=123&name=Alaa&lname=Chaibi) [2]

UserModel.java :
  1. package project.model;
  2. import java.io.Serializable;
  3. import java.util.Date;
  4. import javax.persistence.CascadeType;
  5. import javax.persistence.Entity;
  6. import javax.persistence.GeneratedValue;
  7. import javax.persistence.GenerationType;
  8. import javax.persistence.Id;
  9. import javax.persistence.JoinTable;
  10. import javax.persistence.OneToOne;
  11. import javax.persistence.Table;
  12. import javax.persistence.JoinColumn;
  13. @Entity(name="UserModel")
  14. @Table(name="USER")
  15. public class UserModel implements Serializable {
  16.     private static final long serialVersionUID = GENERATE A KEY;
  17.     @Id
  18.     @GeneratedValue(strategy=GenerationType.AUTO)
  19.     int iduser;
  20.     String password;
  21.     int accountstatus;
  22.     String nomprofile;
  23.     String prenprofile;
  24.     String mailprofile;
  25.     String validation;
  26.    
  27.     public int getIduser() {return iduser;}
  28.     public void setIduser(int iduser) {this.iduser = iduser;}

  29.     public String getPassword() {return password;}
  30.     public void setPassword(String password) {this.password = password;}
  31.     public int getAccountstatus() {return accountstatus;}
  32.     public void setAccountstatus(int accountstatus) {this.accountstatus = accountstatus;}
  33.    
  34.     public String getNomprofile() {return nomprofile;}
  35.     public void setNomprofile(String nomprofile) {this.nomprofile = nomprofile;}
  36.     public String getPrenprofile() {return prenprofile;}
  37.     public void setPrenprofile(String prenprofile) {this.prenprofile = prenprofile;}
  38.     public String getMailprofile() {return mailprofile;}
  39.     public void setMailprofile(String mailprofile) {this.mailprofile = mailprofile;}

  40.     public String getValidation() {return validation;}
  41.     public void setValidation(String validation) {this.validation = validation;}

UserServiceImpl.java :


  1. package project.service;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.stereotype.Service;
  4. import org.springframework.transaction.annotation.Transactional;
  5. import project.dao.UserDAO;
  6. import project.model.UserModel;
  7. import java.util.List;
  8. @Service("UserService")
  9. @Transactional(readOnly = true)
  10. public class UserServiceImpl implements UserService {
  11.     @Autowired
  12.     UserDAO userDAO;
  13.     public UserDAO getUserDAO() {return userDAO;}
  14.     public void setUserDAO(UserDAO userDAO) {this.userDAO = userDAO;}
  15.     public UserModel getVerification(String verification){
  16.         return getUserDAO().getVerification(verification);
  17.        
  18.     }
  19.     @Transactional(readOnly = false)
  20.     public boolean updateVerification(int iduser){
  21.         return getUserDAO().updateVerification(iduser);
  22.     }
  23. }

UserService.java :


  1. package project.service;
  2. import java.util.List;
  3. import project.dao.UserDAO;
  4. import project.model.UserModel;
  5. public interface UserService {
  6. public UserDAO getUserDAO();
  7. public void setUserDAO(UserDAO userDAO);
  8. public UserModel getVerification(String verification);
  9. public boolean updateVerification(int iduser);
  10. }
UserDAOImpl.java :


  1. package project.dao;
  2. import java.util.List;
  3. import org.hibernate.Query;
  4. import org.hibernate.SessionFactory;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Repository;
  7. import project.model.UserModel;
  8. @Repository
  9. public class UserDAOImpl implements UserDAO {
  10.     public @interface ComponentScan {
  11.     }
  12.     @Autowired
  13.     private SessionFactory sessionFactory;
  14.     public SessionFactory getSessionFactory() {return sessionFactory;}
  15.     public void setSessionFactory(SessionFactory sessionFactory) {this.sessionFactory = sessionFactory;} 
  16. public UserModel getVerification(String verification) {
  17.         UserModel userModel = new UserModel();
  18.         Query query = getSessionFactory().getCurrentSession()
  19.                 .createQuery("from UserModel u where u.validation = :Verification");
  20.         query.setParameter("Verification", verification);
  21.         userModel = (UserModel) query.uniqueResult();
  22.         return userModel ;
  23.     }
  24.    
  25.     public boolean updateVerification(int iduser){
  26.         int query = (int) getSessionFactory().getCurrentSession()
  27.                 .createSQLQuery("UPDATE user u Set u.AccountStatus = 1 WHERE u.iduser = :Iduser").setParameter("Iduser", iduser).executeUpdate();
  28.         if (query == 0){return false;}
  29.         else{return true;}
  30.      }
  31.    
  32. }
 UserDAO.java :
  1. package project.dao;
  2. import java.util.List;
  3. import project.model.UserModel;
  4. public interface UserDAO {
  5.     public UserModel getVerification(String verification);
  6.     public boolean updateVerification(int iduser);
  7. }
UserManagedBean.java :
  1. package project.managedbean;
  2. import java.io.Serializable;
  3. import javax.faces.application.FacesMessage;
  4. import javax.faces.bean.ManagedBean;
  5. import javax.faces.bean.ManagedProperty;
  6. import javax.faces.bean.RequestScoped;
  7. import javax.faces.context.FacesContext;
  8. import project.model.UserModel;
  9. import project.service.UserService;
  10. @ManagedBean(name = "userMB")
  11. @RequestScoped
  12. public class UserManagedBean implements Serializable {
  13. private static final long serialVersionUID = GENERATE A KEY;
  14.     @ManagedProperty(value = "#{UserService}")
  15.     UserService userService; 
  16.     UserModel userObject;
  17.     public UserService getUserService() {
  18.         return userService;
  19.     }
  20.     public void setUserService (UserService userService) {
  21.         this.userService= userService;
  22.     }
  23.     public void verify(String code) {
  24.         FacesContext context = FacesContext.getCurrentInstance();
  25.         if (getUsertoverify(code) != null) {
  26.         // With this condition we put data (User row where code is found) into userObject
  27.             if (userObject.getAccountstatus() == 0) {
  28.             // Test if user status require verification with user id from received data userObject
  29.                 if (getUserService().updateVerification(userObject.getIduser()) == true) {
  30.                     context.addMessage("verify", new FacesMessage(FacesMessage.SEVERITY_INFO, "Success: ",
  31.                             "Verification completed successfully"));
  32.                 } else {
  33.                     context.addMessage("verify", new FacesMessage(FacesMessage.SEVERITY_WARN, "Error: ",
  34.                             "An error happened when updating this user account."));
  35.                 }
  36.             } else {
  37.                 context.addMessage("verify", new FacesMessage(FacesMessage.SEVERITY_INFO, "Account Status : ",
  38.                         "Verification is not needed for this user"));
  39.             }
  40.         } else {
  41.         context.addMessage("verify",
  42.                 new FacesMessage(FacesMessage.SEVERITY_WARN, "Wrong code : ", "Incorrect passed code"));
  43.         }
  44.     }
  45.    
  46.     public UserModel getUsertoverify(String code) {
  47.         if (userObject== null) {
  48.             userObject= new UseModel();
  49.             userObject= getUsermanagerService().getVerification(code);
  50.         }
  51.         return userData;
  52.     }
  53. }
Verification.xhtml :
  1. <html xmlns="http://www.w3.org/1999/xhtml"
  2.     xmlns:h="http://java.sun.com/jsf/html"
  3.     xmlns:f="http://java.sun.com/jsf/core"
  4.     xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
  5. <h:head>
  6.  
  7. <f:metadata>
  8.         <f:viewAction action="#{userMB.verify(param['key'])}" if="#{not empty param['key']}"/> 
  9. </f:metadata>
  10.  
  11. </h:head>
  12.  
  13. <h:body>
  14.  <h:panelGroup rendered="#{empty param['key']}">
  15.  Show a message, a page or anything when no "key" parameter.
  16.  </h:panelGroup>
  17. <h:panelGroup rendered="#{not empty param['key']}"> 
  18. Verification for #{param['key']} 
  19. <p:messages id="verify" for="verify" showDetail="true"
  20.                                 closable="true" />
  21.  </h:panelGroup>
  22. </h:body>
[1] : We can use only one query to update the user directly, but we made a test before in order to manage testing account status by selecting the user before updating it.
[2] : Consider making the generated key surely unique by adding exact server time with seconds and id of user. In a personal point of view, I would generate a base64 key of the entered mail adress and use it as a generated key after verifying that the entered mail is never used in user table.

Aucun commentaire:

Enregistrer un commentaire