|
| 1 | +const User = require("../models/user"); |
| 2 | +const EmailValidator = require("email-validator"); |
| 3 | +const validateBody = require("../services/validateBody"); |
| 4 | + |
| 5 | +module.exports = async (req, res, next) => { |
| 6 | + if (!req.body) return res.status(400).json({ message: "No body provided" }); |
| 7 | + const { username, name, email, password, checkPassword } = req.body; |
| 8 | + |
| 9 | + //* validate body |
| 10 | + if (!validateBody.username(username)) { |
| 11 | + return res |
| 12 | + .status(400) |
| 13 | + .json({ message: "No username provided or no length accept" }); |
| 14 | + } |
| 15 | + |
| 16 | + if (!validateBody.name(name)) |
| 17 | + return res |
| 18 | + .status(400) |
| 19 | + .json({ message: "No name provided or no length accept" }); |
| 20 | + |
| 21 | + if (!EmailValidator.validate(email)) |
| 22 | + return res |
| 23 | + .status(400) |
| 24 | + .json({ message: "No email provided or invalid format" }); |
| 25 | + |
| 26 | + if (!validateBody.password(password)) |
| 27 | + return res |
| 28 | + .status(400) |
| 29 | + .json({ message: "No password provided or doesn't match params" }); |
| 30 | + |
| 31 | + if (!validateBody.checkPassword(password, checkPassword)) |
| 32 | + return res.status(400).json({ |
| 33 | + message: "No checkPassword provided or passwords doesn't match", |
| 34 | + }); |
| 35 | + |
| 36 | + //* verify if user exists |
| 37 | + const userExists = await User.findOne({ username }); |
| 38 | + const emailExists = await User.findOne({ email }); |
| 39 | + |
| 40 | + if (userExists || emailExists) |
| 41 | + return res.status(400).json({ message: "Username or Email already exists"}); |
| 42 | + |
| 43 | + next(); |
| 44 | +}; |
0 commit comments