Created
April 10, 2019 10:13
-
-
Save WagnerMatos/86bc562a61af089e2a6d9a1d66c74be6 to your computer and use it in GitHub Desktop.
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
"use strict"; | |
let jwt = require("jsonwebtoken"); | |
let sharedSecret = "shh"; | |
let issuer = "my-awesome-website.com"; | |
const User = require('../../api/models/user'); | |
//Here we setup the security checks for the endpoints | |
//that need it (in our case, only /protected). This | |
//function will be called every time a request to a protected | |
//endpoint is received | |
exports.verifyToken = function(req, authOrSecDef, token, callback) { | |
//these are the scopes/roles defined for the current endpoint | |
let currentScopes = req.swagger.operation["x-security-scopes"]; | |
function sendError() { | |
return req.res.status(403).json({ message: "Error: Access Denied" }); | |
} | |
//validate the 'Authorization' header. it should have the following format: | |
//'Bearer tokenString' | |
if (token && token.indexOf("Bearer ") === 0) { | |
let tokenString = token.split(" ")[1]; | |
jwt.verify(tokenString, sharedSecret, function(verificationError, decodedToken) { | |
//check if the JWT was verified correctly | |
if ( | |
verificationError == null && | |
Array.isArray(currentScopes) && | |
decodedToken && | |
decodedToken.role | |
) { | |
// check if the role is valid for this endpoint | |
let roleMatch = currentScopes.indexOf(decodedToken.role) !== -1; | |
// check if the issuer matches | |
let issuerMatch = decodedToken.iss === issuer; | |
// check if email matches | |
User.findOne(function(err, user) { | |
if(err) throw err; | |
let emailMatch = decodedToken.sub === user.email; | |
// you can add more verification checks for the | |
// token here if necessary, such as checking if | |
// the email belongs to an active user | |
if (roleMatch && issuerMatch && emailMatch) { | |
//add the token to the request so that we | |
//can access it in the endpoint code if necessary | |
req.auth = decodedToken; | |
//if there is no error, just return null in the callback | |
return callback(null); | |
} else { | |
//return the error in the callback if there is one | |
return callback(sendError()); | |
} | |
}); | |
} else { | |
//return the error in the callback if the JWT was not verified | |
return callback(sendError()); | |
} | |
}); | |
} else { | |
//return the error in the callback if the Authorization header doesn't have the correct format | |
return callback(sendError()); | |
} | |
}; | |
exports.issueToken = function(email, role) { | |
return jwt.sign( | |
{ | |
sub: email, | |
iss: issuer, | |
role: role | |
}, | |
sharedSecret | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment