Skip to content

Instantly share code, notes, and snippets.

@tesh254
Created October 8, 2019 12:30
Show Gist options
  • Save tesh254/6b9ede82c7a1e46b4fd921d96ec56631 to your computer and use it in GitHub Desktop.
Save tesh254/6b9ede82c7a1e46b4fd921d96ec56631 to your computer and use it in GitHub Desktop.
import jwt from "jsonwebtoken"
import config from "../config"
import User from "../models/user.models"
const authorize = (req, res, next) => {
const token = req.headers["authorization"]
if (!token) {
return res.status(403).json({
auth: false,
message: "Please login a user"
})
}
jwt.verify(token, config.secretKey, (err, decoded) => {
if (err)
return res.status(500).json({
auth: false,
message: "Failed to authenticate"
})
User.findOne({ email: decoded.data }, { password: 0 }, (err, user) => {
if (err)
return res.status(500).json({
exists: false,
message: "Something went wrong in identifying you"
})
if (!user)
return res.status(404).json({
exists: false,
message: "You are registered, please signup"
})
req.user = user
next()
})
})
}
module.exports = authorize
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment