Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.7 kB
9
Indexable
Never
exports.signup = (req, res, next) => {
    let { name, password } = req.body;
    let errors = [];
    if (!name) {
        errors.push({ name: "required" });
    }

    if (!password) {
        errors.push({ password: "required" });
    }

    if (errors.length > 0) {
        return res.status(422).json({ errors: errors });
    }

    User.findOne({ name: name })
        .then(user => {
            if (user) {
                return res.status(422).json({ errors: [{ user: "username already exists" }] });
            } else {
                const user = new User({
                    name: name,
                    password: password,
                });
                bcrypt.genSalt(10, function (err, salt) {
                    bcrypt.hash(password, salt, function (err, hash) {
                        if (err) throw err;
                        user.password = hash;
                        user.save()
                            .then(response => {
                                res.status(200).json({
                                    success: true,
                                    result: response
                                })
                            })
                            .catch(err => {
                                res.status(500).json({
                                    errors: [{ error: err }]
                                });
                            });
                    });
                });
            }
        }).catch(err => {
            res.status(500).json({
                errors: [{ error: 'Something went wrong' }]
            });
        })
}