Adding backend auth routes
Course: PayTM project - chapter 6
In the user router (backend/routes/user), add 3 new routes.
1. Signup
Section titled “1. Signup”This route needs to get user information, do input validation using zod and store the information in the database provided
- Inputs are correct (validated via zod)
- Database doesn’t already contain another user
If all goes well, we need to return the user a jwt which has their user id encoded as follows -
{ userId: "userId of newly added user"}💡 Note - We are not hashing passwords before putting them in the database. This is standard practise that should be done, you can find more details here - https://mojoauth.com/blog/hashing-passwords-in-nodejs/
**Method: POST ** Route: /api/v1/user/signup Body:
{ username: "name@gmail.com", firstName: "name", lastName: "name", password: "123456"}Response:
Status code - 200
{ message: "User created successfully", token: "jwt"}Status code - 411
{ message: "Email already taken / Incorrect inputs"}Solution
$1b2. Route to sign in
Section titled “2. Route to sign in”Let’s an existing user sign in to get back a token.
Method: POST Route: /api/v1/user/signin Body:
{ username: "name@gmail.com", password: "123456"}Response:
Status code - 200
{ token: "jwt"}Status code - 411
{ message: "Error while logging in"}Solution
const signinBody = zod.object({ username: zod.string().email(), password: zod.string()})
router.post("/signin", async (req, res) => { const { success } = signinBody.safeParse(req.body) if (!success) { return res.status(411).json({ message: "Incorrect inputs" }) }
const user = await User.findOne({ username: req.body.username, password: req.body.password });
if (user) { const token = jwt.sign({ userId: user._id }, JWT_SECRET);
res.json({ token: token }) return; }
res.status(411).json({ message: "Error while logging in" })})By the end, routes/user.js should look like follows
Solution
$1d