Skip to content

Commit

Permalink
feat: option to create multiple token at once
Browse files Browse the repository at this point in the history
  • Loading branch information
mgreg89 committed Nov 20, 2022
1 parent c0e0f6a commit c78ef62
Show file tree
Hide file tree
Showing 3 changed files with 126 additions and 87 deletions.
178 changes: 93 additions & 85 deletions bearer.js
Original file line number Diff line number Diff line change
@@ -1,36 +1,36 @@
//Authentication setup
var CryptoJS = require('node-cryptojs-aes').CryptoJS;

function matchPath(mask, path){
mask=mask.toLowerCase();
path=path.toLowerCase();
if (path.indexOf("?")>0)
path=path.substring(0, path.indexOf("?"));
var maskArray=mask.split("/");
var pathArray=path.split("/");
if (maskArray.length!=pathArray.length) return false;
for (var i= 0; i<maskArray.length; i++){
if ((maskArray[i]!="*") && (pathArray[i]!=maskArray[i])) return false;
function matchPath(mask, path) {
mask = mask.toLowerCase();
path = path.toLowerCase();
if (path.indexOf("?") > 0)
path = path.substring(0, path.indexOf("?"));
var maskArray = mask.split("/");
var pathArray = path.split("/");
if (maskArray.length != pathArray.length) return false;
for (var i = 0; i < maskArray.length; i++) {
if ((maskArray[i] != "*") && (pathArray[i] != maskArray[i])) return false;
}
return true;
}

//Check if route should be authorized and return route setting
function checkUrl(url, method, routes){
method=method.toLowerCase();
for (var i=0; i<routes.length; i++){
var route=routes[i];
if ((matchPath(route.url,url)) && (method==route.method)) return route;
function checkUrl(url, method, routes) {
method = method.toLowerCase();
for (var i = 0; i < routes.length; i++) {
var route = routes[i];
if ((matchPath(route.url, url)) && (method == route.method)) return route;
}
return false;
}

function decryptToken(settings){
function decryptToken(settings) {
var decrypted = CryptoJS.AES.decrypt(settings.bearer, settings.serverKey);
var token;
try{
token=JSON.parse(CryptoJS.enc.Utf8.stringify(decrypted));
}catch(e){
try {
token = JSON.parse(CryptoJS.enc.Utf8.stringify(decrypted));
} catch (e) {
}
return token;
}
Expand All @@ -41,118 +41,126 @@ function bearerJS(settings) {
//var bearer=req.get('Authorization');

var bearer = req.get('Authorization');

var token;
if (bearer){
bearer=bearer.replace('Bearer ','');
token=decryptToken({
bearer:bearer,
serverKey:settings.serverKey
if (bearer) {
bearer = bearer.replace('Bearer ', '');
token = decryptToken({
bearer: bearer,
serverKey: settings.serverKey
});
}

var proceed=function(){
req.authToken=token;
req.isAuthenticated=true;
if (settings.onAuthorized){
var proceed = function () {
req.authToken = token;
req.isAuthenticated = true;
if (settings.onAuthorized) {
settings.onAuthorized(req, token, res);
}
next();
};

var cancel=function(statusCode, errorMessage){
res.statusCode=(statusCode || 401);
res.statusText=errorMessage;
if (settings.onUnauthorized){
var cancel = function (statusCode, errorMessage) {
res.statusCode = (statusCode || 401);
res.statusText = errorMessage;
if (settings.onUnauthorized) {
settings.onUnauthorized(req, token, res, errorMessage);
}else{
res.send({error:errorMessage});
} else {
res.send({ error: errorMessage });
}
};

var isAuthenticated=false;
var routeCheck=checkUrl(req.url,req.method.toLowerCase(),settings.secureRoutes);
if (routeCheck){
if (token){
var tokenValid= await settings.validateToken(req,token);
if (!tokenValid){
var isAuthenticated = false;
var routeCheck = checkUrl(req.url, req.method.toLowerCase(), settings.secureRoutes);
if (routeCheck) {
if (token) {
var tokenValid = await settings.validateToken(req, token);
if (!tokenValid) {
cancel(401, "Token expired or not valid");
}else //Authorized request
} else //Authorized request
{
if (settings.onTokenValid){
settings.onTokenValid(token, function(){
if (routeCheck.roles){ //if there is a Role based limit to request
settings.userInRole(token, routeCheck.roles, function(){proceed()}, function(){cancel(401,"User role rejected")});
}else
{
if (settings.onTokenValid) {
settings.onTokenValid(token, function () {
if (routeCheck.roles) { //if there is a Role based limit to request
settings.userInRole(token, routeCheck.roles, function () { proceed() }, function () { cancel(401, "User role rejected") });
} else {
proceed();
}
}, function(){cancel(401, "User disabled")});
}else
{
if (routeCheck.roles){ //if there is a Role based limit to request
settings.userInRole(token, routeCheck.roles, function(){proceed()}, function(){cancel(401,"User role rejected")});
}else
{
}, function () { cancel(401, "User disabled") });
} else {
if (routeCheck.roles) { //if there is a Role based limit to request
settings.userInRole(token, routeCheck.roles, function () { proceed() }, function () { cancel(401, "User role rejected") });
} else {
proceed();
}
}
}
}else
{
cancel(401,"Invalid token");
} else {
cancel(401, "Invalid token");
}
}else
{
} else {
proceed();
}
});

//Extend existing token without validating password again
settings.app.post(settings.extendTokenUrl, function (req, res) {
var proceed=function(token){
var encrypted = CryptoJS.AES.encrypt(JSON.stringify(token), settings.serverKey);
var bearer=encrypted.toString();
var proceed = function (token) {
if (!Array.isArray(token)) {
token = [token];
}

var jsonToken={
access_token:bearer,
expDate:token.expire
};
const resultTokenArray = [];
for (const singleToken of token) {
resultTokenArray.push(buildJsonToken(singleToken));
}

res.send(jsonToken);
res.send(resultTokenArray);
}

var cancel=function(){
res.statusCode=401;
res.send({error:"Token not provided"});
var cancel = function () {
res.statusCode = 401;
res.send({ error: "Token not provided" });
};

settings.extendToken(req, function(token){proceed(token);}, function () {cancel()});
settings.extendToken(req, function (token) { proceed(token); }, function () { cancel() });
});

//get token value
settings.app.post(settings.tokenUrl, function (req, res) {
var proceed=function(token){
var encrypted = CryptoJS.AES.encrypt(JSON.stringify(token), settings.serverKey);
var bearer=encrypted.toString();
var proceed = function (token) {
if (!Array.isArray(token)) {
token = [token];
}

var jsonToken={
access_token:bearer,
expDate:token.expire
};
const resultTokenArray = [];
for (const singleToken of token) {
resultTokenArray.push(buildJsonToken(singleToken));
}

res.send(jsonToken);
res.send(resultTokenArray);
}

var cancel=function(data){
res.statusCode=401;
var cancel = function (data) {
res.statusCode = 401;
res.send({
error:"Login failed",
data:data
error: "Login failed",
data: data
});
};
settings.createToken(req,function(token){proceed(token);},function(data){cancel(data)});
settings.createToken(req, function (token) { proceed(token); }, function (data) { cancel(data) });
});

function buildJsonToken(token) {
var encrypted = CryptoJS.AES.encrypt(JSON.stringify(token), settings.serverKey);
var bearer = encrypted.toString();

var jsonToken = {
access_token: bearer,
expDate: token.expire
};
return jsonToken;
}
}

module.exports = {
Expand Down
31 changes: 31 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "bearer",
"version": "0.0.20",
"version": "0.0.21",
"description": "Bearer authentication module using token and Authorization HTTP header",
"main": "bearer.js",
"scripts": {
Expand All @@ -19,6 +19,6 @@
"author": "Demir Selmanovic",
"license": "ISC",
"dependencies": {
"node-cryptojs-aes":"~0.4.0"
"node-cryptojs-aes": "~0.4.0"
}
}

0 comments on commit c78ef62

Please sign in to comment.