Skip to content

Instantly share code, notes, and snippets.

@feliperodriguess
Created June 12, 2021 07:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save feliperodriguess/16da6c8dbb85630bdc28c3f8212516c9 to your computer and use it in GitHub Desktop.
Save feliperodriguess/16da6c8dbb85630bdc28c3f8212516c9 to your computer and use it in GitHub Desktop.
⚡️ node.js auth middleware
//usage: routes.use(authMiddleware) in line above of the following authenticated routes
import jwt from 'jsonwebtoken'
import { promisify } from 'util'
import authConfig from '../config/auth'
export default async (req, res, next) => {
const authHeader = req.headers.authorization
if (!authHeader) {
return res.status(401).json({
error: 'Token not provided',
})
}
const [, token] = authHeader.split(' ')
try {
const decoded = await promisify(jwt.verify)(token, authConfig.secret)
req.userId = decoded.id
return next()
} catch (err) {
return res.status(401).json({
error: 'Token invalid',
})
}
}
require('dotenv').config();
export default {
secret: process.env.JWT_SECRET,
expiresIn: process.env.JWT_EXPIRES_IN,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment