Created
March 18, 2019 13:25
-
-
Save Bilguun132/261212c3c19c472eee9c3964f3265d91 to your computer and use it in GitHub Desktop.
nodejs-auth-Tutorial-userroute
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const auth = require("../middleware/auth"); | |
| const bcrypt = require("bcrypt"); | |
| const { User, validate } = require("../models/user.model"); | |
| const express = require("express"); | |
| const router = express.Router(); | |
| router.get("/current", auth, async (req, res) => { | |
| const user = await User.findById(req.user._id).select("-password"); | |
| res.send(user); | |
| }); | |
| router.post("/", async (req, res) => { | |
| // validate the request body first | |
| const { error } = validate(req.body); | |
| if (error) return res.status(400).send(error.details[0].message); | |
| //find an existing user | |
| let user = await User.findOne({ email: req.body.email }); | |
| if (user) return res.status(400).send("User already registered."); | |
| user = new User({ | |
| name: req.body.name, | |
| password: req.body.password, | |
| email: req.body.email | |
| }); | |
| user.password = await bcrypt.hash(user.password, 10); | |
| await user.save(); | |
| const token = user.generateAuthToken(); | |
| res.header("x-auth-token", token).send({ | |
| _id: user._id, | |
| name: user.name, | |
| email: user.email | |
| }); | |
| }); | |
| module.exports = router; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment