Step 7

Let's add a new route for authentications! Create the file auth.js inside the routes folder with the following content:

const express = require("express");
const UserDao = require("../data/UserDao");

const router = express.Router();
const users = new UserDao();

router.post("/register", async (req, res) => {
  try {
    const { username, password } = req.body;
    const data = await users.create({ username, password, role: "CLIENT" });
    res.status(201).json({ data });
  } catch (err) {
    res.status(err.status || 500).json({ message: err.message });
  }
});

router.post("/authenticate", async (req, res) => {
  const { username, password } = req.body;

  if (!username || !password) {
    return res.status(400).json({
      message: "You must provide both username and password.",
    });
  }

  try {
    const user = await users.readOne(username);

    // Authentication!
    if (!user || user.password !== password) {
      return res.status(403).json({
        message: "Wrong username or password!",
      });
    } else {
      return res.json({
        message: "Authentication successful!",
        data: user,
      });
    }
  } catch (err) {
    return res.status(err.status || 500).json({ message: err.message });
  }
});

module.exports = router;

Notice we are introducing two new routes:

  • /register where a client will register
  • /authenticate where a client will authenticate

Update the index.js as follows:

  const db = require("./data/db");
  const notes = require("./routes/notes.js");
  const users = require("./routes/users.js");
+ const auth = require("./routes/auth.js");

  const express = require("express");
  const app = express();
  const port = process.env.PORT || 5000;

  db.connect(); // no need to await for it due to Mongoose buffering!

  app.use(express.json());

  app.get("/", (req, res) => {
    res.send("QuickNote API!");
  });

  // routing
  app.use(notes);
  app.use(users);
+ app.use(auth);

  app.listen(port, () => {
    console.log(`Express app listening at port: http://localhost:${port}/`);
  });
``