Last active
March 18, 2019 13:04
-
-
Save Bilguun132/048faba84ae0cb80445bd4fa4ae84a64 to your computer and use it in GitHub Desktop.
nodejs-auth-Tutorial-auth.js
This file contains hidden or 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
| const jwt = require("jsonwebtoken"); | |
| const config = require("config"); | |
| module.exports = function(req, res, next) { | |
| //get the token from the header if present | |
| const token = req.headers["x-access-token"] || req.headers["authorization"]; | |
| //if no token found, return response (without going to the next middelware) | |
| if (!token) return res.status(401).send("Access denied. No token provided."); | |
| try { | |
| //if can verify the token, set req.user and pass to next middleware | |
| const decoded = jwt.verify(token, config.get("myprivatekey")); | |
| req.user = decoded; | |
| next(); | |
| } catch (ex) { | |
| //if invalid token | |
| res.status(400).send("Invalid token."); | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment