Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

bearer

Package Overview
Dependencies
Maintainers
1
Versions
20
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

bearer - npm Package Compare versions

Comparing version 0.0.14 to 0.0.15

132

bearer.js

@@ -37,22 +37,2 @@ //Authentication setup

function bearerJS(settings) {
//get token value
settings.app.post(settings.tokenUrl, function (req, res) {
var token=settings.createToken(req);
if (token){
var encrypted = CryptoJS.AES.encrypt(JSON.stringify(token), settings.serverKey);
var bearer=encrypted.toString();
var jsonToken={
access_token:bearer,
expDate:token.expire
};
res.send(jsonToken);
}else
{
res.statusCode=401;
res.send({});
}
});
//Check if URL should be authenticated and redirect accordingly

@@ -69,4 +49,22 @@ settings.app.use(function (req, res, next) {

}
var proceed=function(){
req.authToken=token;
req.isAuthenticated=true;
if (settings.onAuthorized){
settings.onAuthorized(req,token);
}
next();
};
var cancel=function(statusCode, errorMessage){
res.statusCode=(statusCode || 401);
res.statusText=errorMessage;
if (settings.onUnauthorized){
settings.onUnauthorized(req,token);
}
res.send({error:errorMessage});
};
var isAuthenticated=false;
var errorMessage="";
var routeCheck=checkUrl(req.url,req.method.toLowerCase(),settings.secureRoutes);

@@ -77,41 +75,21 @@ if (routeCheck){

if (!tokenValid){
errorMessage="Token expired";
cancel(401, "Token expired");
}else //Authorized request
{
if (settings.onTokenValid){
var canProceed=settings.onTokenValid(token);
if (!canProceed){
errorMessage="User disabled";
}else
{
settings.onTokenValid(token, function(){
if (routeCheck.roles){ //if there is a Role based limit to request
errorMessage="User role rejected";
isAuthenticated=false;
for (var i=0; i<routeCheck.roles.length; i++){
if (settings.userInRole(token, routeCheck.roles[i])){
isAuthenticated=true;
break;
}
}
settings.userInRole(token, routeCheck.roles, function(){proceed()}, function(){cancel(401,"User role rejected")});
}else
{
isAuthenticated=true;
proceed();
}
}
}, function(){cancel(401, "User disabled")});
}else
{
if (routeCheck.roles){ //if there is a Role based limit to request
errorMessage="User role rejected";
isAuthenticated=false;
for (var i=0; i<routeCheck.roles.length; i++){
if (settings.userInRole(token, routeCheck.roles[i])){
isAuthenticated=true;
break;
}
}
settings.userInRole(token, routeCheck.roles, function(){proceed()}, function(){cancel(401,"User role rejected")});
}else
{
isAuthenticated=true;
proceed();
}

@@ -122,25 +100,51 @@ }

{
errorMessage="Invalid token";
cancel(401,"Invalid token");
}
}else
{
isAuthenticated=true;
proceed();
}
});
if (isAuthenticated){
req.authToken=token;
req.isAuthenticated=true;
if (settings.onAuthorized){
settings.onAuthorized(req,token);
}
next();
}else
{
//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 jsonToken={
access_token:bearer,
expDate:token.expire
};
res.send(jsonToken);
}
var cancel=function(){
res.statusCode=401;
res.statusText=errorMessage;
if (settings.onUnauthorized){
settings.onUnauthorized(req,token);
}
res.send({error:errorMessage});
res.send({error:"Token not provided"});
};
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 jsonToken={
access_token:bearer,
expDate:token.expire
};
res.send(jsonToken);
}
var cancel=function(){
res.statusCode=401;
res.send({error:"Login failed"});
};
settings.createToken(req,function(token){proceed(token);},function(){cancel()});
});

@@ -147,0 +151,0 @@ }

{
"name": "bearer",
"version": "0.0.14",
"version": "0.0.15",
"description": "Bearer authentication module using token and Authorization HTTP header",

@@ -5,0 +5,0 @@ "main": "bearer.js",

@@ -12,3 +12,3 @@ BearerJS

```
https://github.com/dselmanovic/BearerJSDemo.git
https://github.com/dselmanovic/BearerJSDemo
```

@@ -31,19 +31,41 @@

tokenUrl:'/token', //Call this URL to get your token. Accepts only POST method
createToken:function(req){
extendTokenUrl:'/extendtoken', //Call this URL to get your token. Accepts only POST method
createToken:function(req, next, cancel){
//If your user is not valid just return "underfined" from this method.
//Your token will be added to req object and you can use it from any method later
var username=req.body.username;
var userValid=true; //You are aware that this is where you check username/password in your DB, right!?
if (userValid) return({
expire: moment(Date.now()).add('days', 1).format('YYYY-MM-DD HH:mm:ss'),
username: username,
contentType: req.get('Content-Type'),
ip: req.ip,
userAgent: req.header('user-agent'),
custom_id: '55555',
another: 'Some data you need in your token',
moreData: 'Some more data you need'
});
return undefined;
//var password=req.body.password;
//You get the idea how to use next and cancel callbacks, right?
if (true){
next({
expire: moment(Date.now()).add('days', 1).format('YYYY-MM-DD HH:mm:ss'),
username: username,
contentType: req.get('Content-Type'),
ip: req.ip,
userAgent: req.header('user-agent'),
custom_id: '55555',
another: 'Some data you need in your token',
moreData: 'Some more data you need'
});
}else{
cancel();
}
},
extendToken:function(req, next, cancel){
var token=req.authToken;
if (token){
next({
expire: moment(Date.now()).add('days', 1).format('YYYY-MM-DD HH:mm:ss'),
username: token.username,
contentType: req.get('Content-Type'),
ip: req.ip,
userAgent: req.header('user-agent'),
custom_id: '55555',
another: 'Some data you need in your token',
moreData: 'Some more data you need'
});
}else{
cancel();
}
},
validateToken:function(req, token){

@@ -56,19 +78,30 @@ //you could also check if request came from same IP using req.ip==token.ip for example

},
onTokenValid:function(token){
onTokenValid:function(token, next, cancel){
//This is in case you would like to check user account status in DB each time he attempts to do something.
//Doing this will affect your performance but its your choice if you really need it
//Returning false from this method will reject user even if his token is OK
return true;
var username=token.username;
if (true){
next()
}else{
cancel();
}
},
userInRole:function(token, role){
userInRole:function(token, roles, next, cancel){
//Provide role level access restrictions on url
//You can use onTokenValid for this also, but I find this easier to read later
//If you specified "roles" property for any secureRoute below, you must implement this method
return true;
var username=token.username;
if (true){
next();
}else
{
cancel();
}
},
onAuthorized: function(req, token){
console.log("this will be executed if request is OK");
//console.log("this will be executed if request is OK");
},
onUnauthorized: function(req, token){
console.log("this will be executed if request fails authentication");
//console.log(req.path, "this will be executed if request fails authentication");
},

@@ -87,2 +120,3 @@ secureRoutes:[

* tokenURL: We will add this route for POST method as end point for user authentication to generate token
* extendToken: No need to store password in your client to be able to get new token. Just POST here with Authorize header and get new token
* createToken: Use this function to generate any token content you might need. Token will be encrypted and sent back as response from tokenURL request

@@ -121,3 +155,3 @@ * validateToken: This method will provide you with decrypted token from request. Use it wisely to verify that it is ok

You can use it in subsequential requests as part of your HTTP Header (dont forget the "Bearer " prefix)
You can use it in subsequent requests as part of your HTTP Header (don't forget the "Bearer " prefix)

@@ -124,0 +158,0 @@ ```

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc