DEV Community

Margaret W.N
Margaret W.N

Posted on

User signup & Password Hashing

The goal is to create a new user, hash the password and save it to the database.

User Model

I added a user model file to the models folder and created a user model.

const mongoose = require('mongoose');
const { Schema } = mongoose;

const userModel = new Schema(
  {
    email: {
      type: String,
      required: true
    },
    password: {
      type: String,
      required: true
    },
  }
);

module.exports = mongoose.model('User', userModel);
Enter fullscreen mode Exit fullscreen mode

User Route

I also created user routes. It's labelled /users but it should essentially work like as signup for the users. I'm making a post request to this route then hashing the password.

Hashing:

Encryption is scrambling information to unreadable format to protect confidentiality. Hashing is like a one-way form of encryption which means we can use a string to generate a hash (random string generated by a hashing algorithm), but we can't decode the hash to a string.The same string will always generate the same hash to make the hash unique we add a salt. A salt is just random data added to an input. I'll be using bcrypt which is a hashing function.
Fun fact about bcrypt: It is preferred because its slow. Apparently this makes its harder for hackers to decode.

Ofcourse we'll need to npm install bcrypt and include it in the js file. Inside the post function i'll create a variable salt which stores a randomly generated salt. I'll hash the password and salt and save that to req.body.password. Finally i'll create a user, pass the data from request body and save.

const bcrypt = require('bcrypt');

function userRoutes(User) {
  const router = express.Router();

  router.route('/users')
    .post(async (req, res) => {
      try {
        const salt = await bcrypt.genSalt();
        req.body.password = await bcrypt.hash(req.body.password, salt)

        const user = new User(req.body);

        user.save((err) => {
          if (err) {
            return res.send(err);
          }
          return res.json(user);
        })
      } catch {
        res.status(400).send()
      }
    });

  return router;
}

module.exports = userRoutes;

Enter fullscreen mode Exit fullscreen mode

Next, I included both the model and the route in the app.js

const User = require('./Models/userModel');
const userRouter = require('./routes/userRoutes')(User);

app.use(userRouter);
Enter fullscreen mode Exit fullscreen mode

The output from postman

Alt Text

Day 23

Top comments (0)