This article is continuation of email registration, login articles, So please read the previous articles to know how to setup the project. Email is main identification in user account registration, So whenever user forgot his password, its mandatory to verify email again. Find below for flow of the program

Program Flow 

  1. User Enter Required details (Email ) and submits request to Server
  2. Email Id exists go to step 4, else go to step 3
  3. Inform the user that email is not exists , go to step 1
  4. Update user's status as "InResetPassword", create verification hash code
  5. Send Verification Link with hash code to Registered Email
  6. Get the hash code from database. Check this hash code with User submitted hash code
  7. If hash code matches go to step , else go to step 8 
  8. Increment verification attempts by 1
  9. If verification attempts equal to 20, Create New Hash Code and go to step 5, else go to END
  10. Update User Account status as "active" and show change password screen to user
  11. User Enter required details ( New Password, Confirm Password)
  12. Generate hash code for the password and update it as users's current password

HTML Code

System will take below highlighted field as input 
<form class="form-horizontal" id="formForgotPassword" data-toggle="validator" role="form">
    <input name="inputEmail" type="email" class="form-control" id="inputEmail" placeholder="Enter Email" data-error="Enter valid Email" required>
</form>

ForgotPassword Servlet Code

This servlet is responsible for taking email from user, generating hash code and sending verification link. Find below for post  method of ForgotPassword servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // take email from user input
    String inputEmail = request.getParameter("inputEmail");
    StatusPojo sp = new StatusPojo(); 
    try {
        // get user details for given email
        UserPojo up = UserDAO.selectUSERbyEmail(inputEmail); 
        if(up!=null) {
            // create verification code
            String hash = Utils.prepareRandomString(30);
            // update verification code in database 
            UserDAO.updateEmailVerificationHashForResetPassword(inputEmail, BCrypt.hashpw(hash,GlobalConstants.SALT));
            // send email to user with verification link
            MailUtil.sendResetPasswordLink(up.getUSER_ID()+"", inputEmail, hash);
            sp.setCode(0);
            sp.setMessage("We have sent reset password link to your email");
        } else {
            sp.setCode(-1);
            sp.setMessage("This email doesn't exist");
        }
    } catch (DBException | MessagingException e) {
        LOGGER.debug(e.getMessage());
        sp.setCode(-1);
        sp.setMessage(e.getMessage());
    }
    PrintWriter pw = response.getWriter();
    pw.write(Utils.toJson(sp));
    pw.flush();
    pw.close();
}

VerifyRegisteredEmailHash Servlet Code

This servlet is responsible for verification of email. Whenever user clicks on activation link, it will redirect to this servlet get method. Find below for get method code
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // get user Id and email verification code Hash code  
    Integer userId = Integer.parseInt(request.getParameter("userId"));
    String hash = BCrypt.hashpw(request.getParameter("hash"), GlobalConstants.SALT);
    String scope = request.getParameter("scope");
    String message = null;
    try {
        // verify with database
        if(UserDAO.verifyEmailHash(userId.toString(), hash) && scope.equals(GlobalConstants.RESET_PASSWORD)) {
           //update status as active
           UserDAO.updateStaus(userId.toString(), "active");
           //put some session for user
           request.getSession().setAttribute(GlobalConstants.USER, userId);
           request.getSession().setAttribute(GlobalConstants.IS_RESET_PASSWORD_VERIFIED, GlobalConstants.YES);
           //forward request to reset password html page
           request.getRequestDispatcher("/WEB-INF/resetPassword.html").forward(request, response);  
        } else {
           //now increment verification attempts 
           int attempts = UserDAO.incrementVerificationAttempts(userId.toString());
           if(attempts == 20) {
               // reset verification code if attempts equal to 20 
               String hashcode = Utils.prepareRandomString(30);
               UserDAO.updateEmailVerificationHash(userId.toString(), BCrypt.hashpw(hashcode, GlobalConstants.SALT));
               UserPojo up = UserDAO.selectUSER(userId.toString());
               MailUtil.sendEmailRegistrationLink(userId.toString(), up.getEMAIL(), hashcode);
               message = "20 times Wrong Email Validation Input Given. So we are sent new activation link to your Email";
           } else {
               message = "Wrong Email Validation Input";   
           }
        }
    } catch (DBException e) {
        LOGGER.debug(e.getMessage());
        message = e.getMessage();
    } catch (AddressException e) {
        message = e.getMessage();
        LOGGER.debug(e.getMessage());
    } catch (MessagingException e) {
        message = e.getMessage();
        LOGGER.debug(e.getMessage());
    }
    if(message!=null) {
        request.setAttribute(GlobalConstants.MESSAGE, message);
        request.getRequestDispatcher("/messageToUser.jsp").forward(request, response);  
    } 
}

Now Change Password  

Once email verification successfully done, user will be asked for enter new password and it will be updated to database. Find below for post method of ChangePassword servlet. This code is responsible for updating new password
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // get new password from input and hash it 
    String inputPassword = null;
    if(request.getParameter("inputPassword")!=null) {
        inputPassword = BCrypt.hashpw(request.getParameter("inputPassword"), GlobalConstants.SALT); 
    };
    
    // get user id from session
    Integer userId = (Integer) request.getSession().getAttribute(GlobalConstants.USER);
    String isResetPasswordVerified = (String) request.getSession().getAttribute(GlobalConstants.IS_RESET_PASSWORD_VERIFIED);
    StatusPojo sp = new StatusPojo();
    
    try {
        if(userId!=null && isResetPasswordVerified != null) {
            // update password if the status is in reset password or forgot password
            UserDAO.updatePassword(userId.toString(), inputPassword);
            sp.setCode(0);
            sp.setMessage("Password changed successfully");
        } else {
            sp.setCode(-1);
            sp.setMessage("Invalid input");
        }
    } catch (DBException e) {
        LOGGER.debug(e.getMessage());
        sp.setCode(-1);
        sp.setMessage(e.getMessage());
    }
    PrintWriter pw = response.getWriter();
    pw.write(Utils.toJson(sp));
    pw.flush();
    pw.close();
}

Required MySQL Queries

// to update status of user
update DEMO_USER set STATUS = ? where USER_ID = ?

// to increment email verification attempts
update DEMO_USER set EMAIL_VERIFICATION_ATTEMPTS = EMAIL_VERIFICATION_ATTEMPTS + 1 where USER_ID = ?

// to select email verification attempts
SELECT EMAIL_VERIFICATION_ATTEMPTS from DEMO_USER

// to update email verification hash code
update DEMO_USER set EMAIL_VERIFICATION_HASH = ?, EMAIL_VERIFICATION_ATTEMPTS = ? where USER_ID = ?

// to update password
update DEMO_USER set PASSWORD = ? where USER_ID = ?

13 comments:

  1. Hello, nice post but i am continuously getting an exception an exception saying "Excepion while accessing database", I have create db by seeing DAO class.Please help me out to get proper output.

    ReplyDelete
  2. i am continuously getting an exception an exception saying "Local address contains control or whitespace".

    ReplyDelete
    Replies
    1. Check whether you entered correct values in Setup.java, If you still having this issue contact me on facebook and share your project and screenshots

      Delete
  3. While sending register the new account i got this error.
    Error: 534-5.7.14 Please log in via your web browser and 534-5.7.14 then try again. 534-5.7.14 Learn more at 534 5.7.14 https://support.google.com/mail/answer/78754 ut6sm15367291pac.37 - gsmtp

    can u help me.

    ReplyDelete
    Replies
    1. are you trying to send email through gmail?. Gmail wont allow login from java mail API, Try to use other mail service

      Delete
  4. Error: 530-5.5.1 Authentication Required. Learn more at 530 5.5.1 https://support.google.com/mail/answer/14257 m1sm4971208pab.46 - gsmtp
    Now i got this error .I add the java mail api jar files and activation jar files in library.help me..

    ReplyDelete
  5. Bro please mail me video tutorial of this at bimalsajan@gmail.com pleaseeeeeeeeeee

    ReplyDelete
  6. Business management application or software has risen to importance in recent years as a procedure of improving output the in the place of work or simply evaluating with an outlook to recognizing ways enhances it in the upcoming days. In this post, we will look over the main areas that business management software can help a business in moving further and becoming as competent as probable.
    visit site

    ReplyDelete
  7. Hello, nice post but i am continuously getting an exception an exception saying "Excepion while accessing database", I have create db by seeing DAO class.Please help me out to get proper output.

    DEBUG 2016-11-16 14:27:34,217 [http-bio-8080-exec-3] com.sl.dao.UserDAO - Field 'EMAIL_VERIFICATION_ATTEMPTS' doesn't have a default value
    DEBUG 2016-11-16 14:27:34,220 [http-bio-8080-exec-3] com.sl.emailRegistration.RegisterEmail - Excepion while accessing database

    ReplyDelete
    Replies
    1. This looks like db mismatch. Try to change queries in UserDAO.java to make it work

      Delete
  8. Couldn't connect to host, port: smtp password here, 587; timeout -1

    this type of error occure

    ReplyDelete
    Replies
    1. Looks like its unable to send emails. Check your mail server configuration

      Delete
  9. problem to stare data in db ,when we store data in DB as password , in table show hash code how we can solve this problem

    ReplyDelete

Blogroll

Follow this blog by Email

Popular Posts