Created
June 12, 2021 07:18
-
-
Save feliperodriguess/16da6c8dbb85630bdc28c3f8212516c9 to your computer and use it in GitHub Desktop.
⚡️ node.js auth middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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', | |
}) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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