SHARE
TWEET

Untitled

a guest Nov 12th, 2019 66 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const express = require('express')
  2. const User = require('../models/user')
  3. const auth = require('../middleware/auth')
  4. const router = new express.Router()
  5.  
  6. router.post('/users', async (req, res) => {
  7.     const user = new User(req.body)
  8.  
  9.     try {
  10.         await user.save()
  11.         const token = await user.generateAuthToken()
  12.         res.status(201).send({ user, token })
  13.     } catch (e) {
  14.         res.status(400).send(e)
  15.     }
  16. })
  17.  
  18. router.post('/users/login', async (req, res) => {
  19.     try {
  20.         const user = await User.findByCredentials(req.body.email, req.body.password)
  21.         const token = await user.generateAuthToken()
  22.         res.send({ user, token })
  23.     } catch (e) {
  24.         res.status(400).send()
  25.     }
  26. })
  27.  
  28. router.post('/users/logout', auth, async (req, res) => {
  29.     try {
  30.         req.user.tokens = req.user.tokens.filter((token) => {
  31.             return token.token !== req.token
  32.         })
  33.         await req.user.save()
  34.  
  35.         res.send()
  36.     } catch (e) {
  37.         res.status(500).send()
  38.     }
  39. })
  40.  
  41. router.post('/users/logoutAll', auth, async (req, res) => {
  42.     try {
  43.         req.user.tokens = []
  44.         await req.user.save()
  45.         res.send()
  46.     } catch (e) {
  47.         res.status(500).send()
  48.     }
  49. })
  50.  
  51. router.get('/users/me', auth, async (req, res) => {
  52.     res.send(req.user)
  53. })
  54.  
  55. router.patch('/users/me', auth, async (req, res) => {
  56.     const updates = Object.keys(req.body)
  57.     const allowedUpdates = ['name', 'email', 'password', 'age']
  58.     const isValidOperation = updates.every((update) => allowedUpdates.includes(update))
  59.  
  60.     if (!isValidOperation) {
  61.         return res.status(400).send({ error: 'Invalid updates!' })
  62.     }
  63.  
  64.     try {
  65.         updates.forEach((update) => req.user[update] = req.body[update])
  66.         await req.user.save()
  67.         res.send(req.user)
  68.     } catch (e) {
  69.         res.status(400).send(e)
  70.     }
  71. })
  72.  
  73. router.delete('/users/me', auth, async (req, res) => {
  74.     try {
  75.         await req.user.remove()
  76.         res.send(req.user)
  77.     } catch (e) {
  78.         res.status(500).send()
  79.     }
  80. })
  81.  
  82. module.exports = router
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top