Lets now create a todo application
with the data being persisted
in the database.
npm init -y
npm install express mongoose
index.js
const { UserModel, TodoModel } = require("./db");
/signup
endpointapp.post("/signup", async function(req, res) {
const email = req.body.email;
const password = req.body.password;
const name = req.body.name;
await UserModel.create({
email: email,
password: password,
name: name
});
res.json({
message: "You are signed up"
})
});
/signin
endpoint (need to install jsonwebtoken library)const JWT_SECRET = "s3cret";
app.post("/signin", async function(req, res) {
const email = req.body.email;
const password = req.body.password;
const response = await UserModel.findOne({
email: email,
password: password,
});
if (response) {
const token = jwt.sign({
id: response._id.toString()
})
res.json({
token
})
} else {
res.status(403).json({
message: "Incorrect creds"
})
}
});
auth
middleware (in a new file auth.js)const jwt = require("jsonwebtoken");
const JWT_SECRET = "s3cret";
function auth(req, res, next) {
const token = req.headers.authorization;
const response = jwt.verify(token, JWT_SECRET);
if (response) {
req.userId = token.userId;
next();
} else {
res.status(403).json({
message: "Incorrect creds"
})
}
}
module.exports = {
auth,
JWT_SECRET
}
POST
todo endpointconst { auth, JWT_SECRET } = require("./auth");