Search code examples
node.jsexpressauthenticationmongoosemern

What is the best practice for password encryption?


I am a beginner Nodejs developer and When doing the authentication, I have seen some encrypt the password directly inside the signup controller function, while some encrypt the password using a middleware that triggers before the save method of mongoose. I really can't understand the difference between 2 practices. Can anyone tell me what is the best practice and why?

I typically encrypt password in the signup controller


Solution

  • Having it on Repository level ensures that no password is saved in plain format (which in general is the worst security risk you can have).

    In future you can add multiple ways how to create and save new users or change their passwords. Having it on Controller level increases risk that you will not notice the encryption is not done on Repository level and you can save tha password in plain format.

    i.e. you add functionality to create new user with password and 2 weeks later you add functionality to reset password - which is different controller.