Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const express = require('express')
- const bodyParser = require('body-parser')
- const mongoose = require('mongoose')
- const password = require('password-hash-and-salt')
- const { Router } = express
- const app = express()
- mongoose.connect('mongodb://localhost:27017/hubbers', { useNewUrlParser: true })
- const User = mongoose.model('User', {
- name: String,
- email: String,
- password: String,
- phone: String,
- accountType: {
- type: String,
- enum: ['buyer', 'seller', 'partner'],
- default: 'buyer'
- },
- facebookId: String,
- isFacebookAccount: { type: Boolean, default: false }
- })
- app.use(bodyParser.json())
- const authenticationRouter = Router()
- const userRouter = Router()
- authenticationRouter.post('/login', async (req, res) => {
- try {
- const user = await User.findOne({ email: req.body.email })
- if (user) {
- password(req.body.password).verifyAgainst(user.password, (err, verified) => {
- if (err) throw err
- if (verified) {
- res.json(user)
- } else {
- res.status(400)
- res.json('Password is invalid')
- }
- })
- } else {
- res.status(400)
- res.json('Email not found')
- }
- } catch (err) {
- throw err
- }
- })
- authenticationRouter.post('/register', async (req, res) => {
- try {
- const user = await User.findOne({ email: req.body.email })
- if (user) {
- res.status(400)
- res.json('Email already registered')
- } else {
- password(req.body.password).hash(async (err, hash) => {
- if (err) throw err
- const newUser = await User.create({
- name: req.body.name,
- email: req.body.email,
- password: hash,
- phone: req.body.phone,
- type: req.body.accountType
- })
- res.json(newUser)
- })
- }
- } catch (err) {
- throw err
- }
- })
- userRouter.put('/password', async (req, res) => {
- try {
- const user = await User.findById(req.body.id)
- if (user) {
- password(req.body.password).verifyAgainst(user.password, (err, verified) => {
- if (err) throw err
- if (verified) {
- password(req.body.newPassword).hash((err, hash) => {
- if (err) throw err
- User.findByIdAndUpdate(req.body.id, {
- $set: { password: hash }
- }, { new: true }, (err, user) => {
- if (err) throw err
- res.json('Ok')
- })
- })
- } else {
- res.status(400)
- res.json('Passwords does not match')
- }
- })
- } else {
- res.status(400)
- res.json('User ID not found')
- }
- } catch (err) {
- throw err
- }
- })
- userRouter.put('/profile', async (req, res) => {
- try {
- const user = await User.findByIdAndUpdate(req.body.id, {
- $set: {
- name: req.body.name,
- email: req.body.email,
- phone: req.body.phone
- }
- }, { new: true })
- res.json(user)
- } catch (err) {
- throw err
- }
- })
- app.use('/authentication', authenticationRouter)
- app.use('/user', userRouter)
- app.listen(process.env.PORT || 3000)
Add Comment
Please, Sign In to add comment