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
- User Enter Required details (Email ) and submits request to Server
- Email Id exists go to step 4, else go to step 3
- Inform the user that email is not exists , go to step 1
- Update user's status as "InResetPassword", create verification hash code
- Send Verification Link with hash code to Registered Email
- Get the hash code from database. Check this hash code with User submitted hash code
- If hash code matches go to step , else go to step 8
- Increment verification attempts by 1
- If verification attempts equal to 20, Create New Hash Code and go to step 5, else go to END
- Update User Account status as "active" and show change password screen to user
- User Enter required details ( New Password, Confirm Password)
- 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 = ?
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.
ReplyDeletei am continuously getting an exception an exception saying "Local address contains control or whitespace".
ReplyDeleteCheck whether you entered correct values in Setup.java, If you still having this issue contact me on facebook and share your project and screenshots
DeleteWhile sending register the new account i got this error.
ReplyDeleteError: 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.
are you trying to send email through gmail?. Gmail wont allow login from java mail API, Try to use other mail service
DeleteError: 530-5.5.1 Authentication Required. Learn more at 530 5.5.1 https://support.google.com/mail/answer/14257 m1sm4971208pab.46 - gsmtp
ReplyDeleteNow i got this error .I add the java mail api jar files and activation jar files in library.help me..
Bro please mail me video tutorial of this at bimalsajan@gmail.com pleaseeeeeeeeeee
ReplyDeleteBusiness 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.
ReplyDeletevisit site
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.
ReplyDeleteDEBUG 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
This looks like db mismatch. Try to change queries in UserDAO.java to make it work
DeleteCouldn't connect to host, port: smtp password here, 587; timeout -1
ReplyDeletethis type of error occure
Looks like its unable to send emails. Check your mail server configuration
Deleteproblem to stare data in db ,when we store data in DB as password , in table show hash code how we can solve this problem
ReplyDeleteIf you are using unix and getting this error Excepion while accessing database Tomcat logs[DEBUG 2017-07-16 21:40:51,582 [http-nio-8181-exec-2] com.sl.dao.UserDAO - Table 'demos.DEMO_USER' doesn't exist], then the database engine is case sensitive..
ReplyDeleteHi, excellent post. Which are the libraries that you use in the project ...
ReplyDeleteCan you share database & tables.
ReplyDeleteCan you share jar files name
Thus, it allows you to create a database solution that runs on all the major platforms including UNIX, Windows and Linux.https://www.dbdesigner.net
ReplyDeleteI want you to thank for your time of this wonderful read!!! I definately enjoy every little bit of it and I have you bookmarked to check out new stuff of your blog a must read blog! Digitogy
ReplyDeleteIt's the best time to make some plans for the future and it's time to be happy. I have read this post and if I could I wish to suggest you few interesting things or advice. Perhaps you could write next articles referring to this article. I wish to read more things about it! I thought about this: The A - Z Of Encryption Software & 7 Ways To How To Encrypt A Password For Free In 60 Minutes.
ReplyDeleteyour article is very good and very helpful. every one can use and know that how Creating Custom Animations for Use in Tableau. if you want to gif covert to image than check it you can easily understand that how to Use GIF Converter to Get Images for Marketing
ReplyDeleteYou guys are writing some Amazing tips. Thanks for sharing this. Totally Awesome Post Please Keep Posting Regularly.
ReplyDeleteechobeat earbuds review, chargeboost reviews, liporing review , doc socks, livewave antenna review
Thanks for sharing an article like this. The information which you have provided is better than another blog.
ReplyDeletesonic x pro review
Amazing post! I appreciate your hard work. Thank you for sharing. I have also share some use full information.
ReplyDeleteDrone pro review
PhotoStick Mobile Review
mosquitron reviews
eco beat earphones review
Best Front Load Washing Machines in India
ReplyDeleteBest Vaseline Body Lotion in India 2020
Best Refrigerator in India
Best Portable speaker in in India
Nice Post, thanks for sharing such type of valuable content. Boobuddy Review 2020
ReplyDeleteamazing post thanks for sharing valuble content such a good information provide us.
ReplyDeleteLive TempPro Reviews
Great piece of content after reading all this I'm feeling so overwhleming that I've gain some sort of knowledge from this page. Keep up the good work!! Thank YOU!
ReplyDeleteHearing Hero Reviews
Writing on any topic is quite difficult thing, how are you expressing the feeling and research in words, that's matters. You did a fablous job I really like your post. I have also write some review about electronics gadget I hope peoples will like it, and it also help them to choice right product according to their uses.
ReplyDeleteThe Photostick Review
Correct Back Posture Review
Starscope Monocular Review
PrintX Pro Review 2021
Whatever you have written Glad I'm stumbled upon to this blog, the content is very information thanks for sharing such piece of knowledge with us.
ReplyDeletePrintx Pro Review
Aivivu chuyên vé máy bay, tham khảo
ReplyDeletemua ve may bay di my
vé về việt nam từ mỹ
giá thuê máy bay từ anh về việt nam
các chuyến bay từ châu âu về việt nam
giá vé máy bay từ nhật về việt nam
gia ve may bay vietjet tu han quoc ve viet nam
Thanks for sharing this informative blog with us. Find out the best Water Treatment Equipment & Supplies in UAE on Etisalat yellowpages.
ReplyDeleteThanks for sharing this informative blog with us. Find out the best Weighing Scales & Measuring Tapes in UAE on Etisalat yellowpages.
ReplyDeleteThe content on your website is amazing. Thank you for sharing this time. 789betting เข้าสู่ระบบ
ReplyDeleteThanks for sharing informative content.. find best forgot password content for this blog. Also visit my website pakkaoffer.com
ReplyDeletedominos coupons
ola coupons
grofers coupons
oyo coupons
swiggy coupons
zomato coupons
yatra coupons
1mg coupons
bigbasket coupons
Thank you for sharing this information with us.
ReplyDeleteJava Burn Reviews
Dr. Namita Nadar is the Best Dietitian and Nutritionist in Noida and Delhi NCR. She has established her Weight Loss Centre almost two decades ago with the mission of increasing awareness about having a good diet plan or diet chart in our daily life that could bring remarkable effects on our health and lifestyle. Best Dietitian and nutritionist in Noida NCRShe cures her patient with her holistic approach consisting of proper diet planning for weight loss and weight gain, body composition analysis along with the patient’s medical condition.
ReplyDeleteHi
I am glad to see your wonderful article today it is very helpful for all new visitors of your blog.
ReplyDeleteshri ganesh record chart
Desawar Leak Number
Gali Satta Record Chart 2022
Faridabad Satta King 2022
Ghaziabad Satta King
Dietitian Shivi Srivastava at Ultimate Diet Clinic helps you to lose weight & stay slim healthy with the help of nutrition diet programs or with the diet charts which she provides. Dietitians (Dietician) Shivi is trained and Nutritionists who help you to get your body in good shape and healthy with is the effect of diet plans which suites to your body.
ReplyDeleteAt Ultimate Diet Clinic, Greater Noida, We Understand the food requirment/habit and accordingly based on taste we create customized diet plan. We Alaways create diet plan based one one on one discussion so that we can provide the best suitable plan as per your body requirment because everybody metabolism different from another.because of "Every individual having different result
Great article! I found your insights incredibly valuable. It reminded me of a related post on our blog that dives deeper into this topic here Iubenda Review
ReplyDeleteThank you for sharing this insightful article! It provided me with a fresh perspective on the topic and expanded my understanding. Need writing help,Visit For More Info
ReplyDelete