JWT Authentication with Node.js

const jwt = require('jsonwebtoken')const config = require('config')module.exports = function(req, res, next){// Get token from headerconst token = req.header('x-auth-token')// Check if no tokenif(!token){return res.status(401).json({msg: 'No token, authorization denied'})}//Verify tokentry {const decoded = jwt.verify(token, config.get('jwtSecret'))req.user = decoded.usernext()} catch(err){res.status(401).json({msg: 'Token is not valid'})}}
const express = require('express')const router = express.Router()const bcrypt = require('bcryptjs')const jwt = require('jsonwebtoken')const config = require('config')const { check, validationResult } = require('express-validator')const auth = require('../../middleware/auth')const User = require('../../models/User')
// @route GET api/auth
// @desc Get user by token// @access Publicrouter.get('/', auth, async (req, res) => {try {const user = await User.findById(req.user.id).select('-password')res.json(user)} catch(err){res.status(500).send('Server error')}})
// @route   POST api/auth// @desc    Authenticate User and get token// @access  Publicrouter.post('/',[check('email', 'Please include a valid email').isEmail(),check('password', 'Password is required').exists()],async (req, res) => {const errors = validationResult(req)
if(!errors.isEmpty()){return res.status(400).json({ errors: errors.array() })}const { email, password } = req.bodytry {let user = await User.findOne({ email })if(!user) {return res.status(400).json({ errors: [{msg: 'Invalid credentials'}] })}const isMatch = await bcrypt.compare(password, user.password)if(!isMatch){return res.status(400).json({ errors: [{msg: 'Invalid credentials'}] })}const payload = {user: {id: user.id}}jwt.sign(payload,config.get('jwtSecret'),{ expiresIn: 36000 },(err, token) => {if(err) throw errres.json({ token })})} catch(err){res.status(500).send('Server error')}})

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store