New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

bella

Package Overview
Dependencies
Maintainers
1
Versions
8
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

bella - npm Package Compare versions

Comparing version 0.4.0 to 0.5.0

336

lib/bella.js

@@ -5,3 +5,3 @@ /*

*
* Copyright (c) 2014 Christopher EnyTC
* Copyright (c) 2014, Christopher EnyTC
* Licensed under the MIT license.

@@ -16,75 +16,68 @@ */

var generator = require('./generator.js');
var users = [];
var hat = require('hat'),
rack = hat.rack(),
_ = require('underscore');
/**
@class Bella
*/
/*
* Private Methods
*/
function inUsersList(username, password) {
var result;
for (var u in users) {
if (String(users[u].username) === String(username) && String(users[u].password) === String(password)) {
result = true;
}
}
return result;
}
/*
* Public Methods
*/
/**
* Method responsible for initiating the module and set the Schema and create a model to be used by other methods.
* @class Bella
*
* @constructor
*
* Constructor responsible for provide a bootstrap
*
* @example
*
* app.configure(function() {
* app.use(bella.init(mongoose, conn, [{username: 'bella', password: 'test'}]));
* });
* app.use(bella.init(mongoose, {connection: conn, uri: dbUri, status: true, model: userModel}));
*
* @method init
* @param {Object} mongoose Instance of Mongoose
* @param {Object} conn A mongoose connection
* @param {Object} usersList A list of authorized users
* @param {Object} mongoose Mongoose instance
* @param {Object} options Options for Bella
* @return {Function} Returns a middleware
*/
exports.init = function init(mongoose, conn, usersList) {
//Create Mongoose Schema
var Schema = mongoose.Schema;
//Create Mongoose Model
var bellaSchema = new Schema({
ip: {
type: String,
required: true
},
domain: {
type: String,
required: true
},
access_token: {
type: String,
required: true,
unique: true
exports.init = function Bella(mongoose, options) {
//Create Mongoose Schema
var Schema = mongoose.Schema,
db = options.connection;
//Create Mongoose connection
if (options.uri) {
mongoose.connect(options.uri, function(err) {
if (err) {
throw err;
}
});
//Get connection
db = mongoose.connection;
}
});
//set Users
users = usersList || [];
//Create a Instance of Mongoose Model and parse to methods
this.Model = conn.model('Bella', bellaSchema);
//Return a middleware
return function (req, res, next) {
next();
};
//Create Mongoose Model
var PermissionSchema = new Schema({
access_token: {
type: String,
required: true,
unique: true
},
ip: {
type: String,
required: true
},
domain: {
type: String,
required: true
},
permissions: {
type: Array,
default: ['user']
},
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
//Set default permissions
this.enableStatus = options.status || false;
this.UserModel = options.model || db.model('User');
this.PermissionModel = db.model('Permission', PermissionSchema);
//Return a middleware
return function init(req, res, next) {
next();
};
};

@@ -97,3 +90,3 @@

*
* bella.create('example.com', '127.0.0.1', function(err, access_token) {
* bella.create(req.user, ['user', 'create_article'], '127.0.0.1', 'example.com', function(err, access_token) {
* console.log('Token: ' + access_token);

@@ -103,4 +96,6 @@ * });

* @method create
* @param {Object} user A user
* @param {String} permissions A array list of permissions
* @param {String} ip A new Ip
* @param {String} domain A new Domain
* @param {String} ip A new Ip
* @param {Function} cb A callback with the error and a new access_token

@@ -110,27 +105,29 @@ * @return {Function} Returns a callback

exports.create = function create(domain, ip, cb) {
//Fallback
cb = cb || function () {};
//Make a new access_token with this data
var access_token = generator.generate(null, domain, ip, 19092013);
//Create new User with this data
var user = new this.Model({
domain: domain,
ip: ip,
access_token: access_token
});
//Save this user in database
try {
user.save(function (err) {
//If error throw this error
if (err) {
throw err;
} else {
//Return a callback with access_token
cb(null, access_token);
}
exports.create = function create(user, permissions, ip, domain, cb) {
//Fallback
cb = cb || function() {};
//Make a new access_token with this data
var access_token = rack();
//Create new User with this data
var permissionAuth = new this.PermissionModel({
access_token: access_token,
ip: ip,
domain: domain,
permissions: permissions,
user: user
});
} catch (e) {
cb(e, access_token);
}
//Save this token in database
try {
permissionAuth.save(function(err) {
//If error throw this error
if (err) {
throw err;
} else {
//Return a callback with access_token
cb(null, access_token);
}
});
} catch (e) {
cb(e, null);
}

@@ -150,3 +147,3 @@ };

* @param {String} access_token A Access Token generated by create method
* @param {Function} cb A callback with the error and access_token
* @param {Function} cb A callback with the error
* @return {Function} Returns a callback

@@ -156,21 +153,21 @@ */

exports.remove = function remove(access_token, cb) {
//Fallback
cb = cb || function () {};
//delete this user on database
try {
this.Model.remove({
access_token: access_token
}, function (err) {
//If error throw this error
if (err) {
throw err;
} else {
//Fallback
cb = cb || function() {};
//delete this user on database
try {
this.PermissionModel.remove({
access_token: access_token
}, function(err) {
//If error throw this error
if (err) {
throw err;
} else {
//Return a callback with access_token
cb(null, access_token);
}
});
} catch (e) {
//Return a callback with access_token
cb(null, access_token);
}
});
} catch (e) {
//Return a callback with access_token
cb(e, access_token);
}
cb(e, null);
}

@@ -181,3 +178,3 @@ };

* Method responsible for authenticating access the API.
* Only users with Access Token, Domain, IP, Username and Password authenticated can access the API.
* Only users with Access Token, Domain and IP authenticated can access the API.
*

@@ -187,3 +184,3 @@ * @example

* app.configure(function() {
* app.use(bella.init(mongoose, conn));
* app.use(bella.init(mongoose, {connection: conn, uri: dbUri, status: true, model: userModel}));
* app.use(bella.authenticate());

@@ -194,60 +191,79 @@ * });

*
* app.get('/users', bella.authenticate(), ctrl);
* app.get('/users', bella.authenticate('user'), ctrl);
*
* @method authenticate
* @param {String} permission The required permission
* @return {Function} Returns a middleware
*/
exports.authenticate = function authenticate() {
//Save this scope
var that = this;
// return a middleware
return function (req, res, next) {
//Search for tokens
that.Model.findOne({
access_token: req.query.access_token
}, function (err, doc) {
//Try get token
try {
//If error throw a new error
if (err) {
throw err;
exports.authenticate = function authenticate(permission) {
//Save this scope
var that = this;
// return a middleware
return function authenticate(req, res, next) {
//Callback
function callback(msg) {
//Access denied
if (typeof msg === 'string') {
msg = msg;
} else {
msg = msg.message;
}
res.jsonp(401, {
message: 'Bad Authentication. You do not have permission to access the API.',
error: msg
});
}
//Check if this requests is a access_token request
if (req.query.access_token) {
//Check if the authentication data
if (req.domain !== doc.domain && req.ip !== doc.ip && req.query.access_token !== doc.access_token) {
//User do not have access
throw new Error('Bad Authentication. You do not have permission to access the API.');
} else {
//Check if all permissions exists
function inPermissionList(list, permission) {
return _.contains(list, permission);
}
//Check if user exists
return that.UserModel.findOne({
access_token: req.query.access_token
}).exec(function(err, data) {
if (err) {
return callback(err);
}
if (!data) {
return that.PermissionModel.findOne({
access_token: req.query.access_token
}).populate('user')
.exec(function(pErr, pData) {
if (pErr) {
return callback(pErr);
}
if (!pData) {
return callback('access_token not found');
}
if (req.host !== pData.domain || req.ip !== pData.ip) {
return callback('The IP or domain is different from registered for this access_token');
}
if (!inPermissionList(pData.permissions, permission)) {
return callback('This access_token not have the permissions to continue the request.');
}
//Create permissionData
req.user = pData;
req.profile = pData;
return next();
});
}
if (that.enableStatus) {
if (!data.status) {
return callback('Inactive User');
}
}
if (!inPermissionList(data.permissions, permission)) {
return callback('This access_token not have the permissions to continue the request.');
}
//Create userData
req.user = data;
req.profile = data;
//Access granted
next();
}
} else {
//Check for the basic auth login
if (inUsersList(req.query.username, req.query.password)) {
//Access granted
next();
} else {
//User do not have access
throw new Error('Bad Authentication. You do not have permission to access the API.');
}
}
} catch (e) {
//If user do not have permission to acessing the API, send a 401 response with error message
res.json(401, {
error: 'Bad Authentication. You do not have permission to access the API.'
return next();
});
//Next request with error
if ('test' !== process.env.NODE_ENV) {
next(e);
} else {
next();
}
}
});
};
};
};
{
"name": "bella",
"description": "An API Authentication for node.js",
"version": "0.4.0",
"homepage": "https://github.com/chrisenytc/bella",
"author": {
"name": "Christopher EnyTC",
"email": "chrisenytc@gmail.com"
},
"repository": {
"type": "git",
"url": "git://github.com/chrisenytc/bella.git"
},
"bugs": {
"url": "https://github.com/chrisenytc/bella/issues"
},
"licenses": [
{
"type": "MIT",
"url": "https://github.com/chrisenytc/bella/blob/master/LICENSE"
}
],
"main": "lib/bella",
"engines": {
"node": ">= 0.10.0"
},
"scripts": {
"start": "NODE_ENV=development node ./example/app.js",
"test": "NODE_ENV=test grunt test"
},
"dependencies": {
"livia-algorithm": "~0.1.2",
"underscore": "~1.6.0"
},
"devDependencies": {
"mocha": "~1.10.0",
"chai": "~1.8.1",
"supertest": "~0.8.2",
"grunt-contrib-jshint": "~0.6.0",
"grunt-contrib-watch": "~0.5.0",
"grunt-mocha-cli": "~1.3.0",
"load-grunt-tasks": "~0.2.0",
"time-grunt": "~0.1.1",
"jshint-stylish": "~0.1.3",
"grunt-contrib-watch": "~0.5.0"
},
"keywords": ["api", "auth", "authentication", "token", "key"]
"name": "bella",
"description": "A API Authentication for node.js",
"version": "0.5.0",
"homepage": "https://github.com/chrisenytc/bella",
"author": {
"name": "Christopher EnyTC",
"email": "chrisenytc@gmail.com"
},
"repository": {
"type": "git",
"url": "git://github.com/chrisenytc/bella.git"
},
"bugs": {
"url": "https://github.com/chrisenytc/bella/issues"
},
"licenses": [{
"type": "MIT",
"url": "https://github.com/chrisenytc/bella/blob/master/LICENSE"
}],
"main": "lib/bella",
"engines": {
"node": ">= 0.10.26"
},
"scripts": {
"start": "NODE_ENV=development node ./example/app.js",
"test": "NODE_ENV=test grunt test"
},
"dependencies": {
"hat": "~0.0.3",
"underscore": "~1.6.0"
},
"devDependencies": {
"mocha": "~1.10.0",
"chai": "~1.8.1",
"supertest": "~0.8.2",
"grunt-contrib-jshint": "~0.6.0",
"grunt-contrib-watch": "~0.5.0",
"grunt-mocha-cli": "~1.3.0",
"load-grunt-tasks": "~0.2.0",
"time-grunt": "~0.1.1",
"jshint-stylish": "~0.1.3"
},
"keywords": ["api", "auth", "authentication", "token", "key"]
}
# Bella [![Build Status](https://secure.travis-ci.org/chrisenytc/bella.png?branch=master)](https://travis-ci.org/chrisenytc/bella) [![Dependency Status](https://gemnasium.com/chrisenytc/bella.png)](https://gemnasium.com/chrisenytc/bella) [![NPM version](https://badge-me.herokuapp.com/api/npm/bella.png)](http://badges.enytc.com/for/npm/bella) [![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/chrisenytc/bella/trend.png)](https://bitdeli.com/free "Bitdeli Badge")
> An API Authentication for node.js
> A API Authentication for node.js

@@ -12,4 +12,4 @@ ## Getting Started

app.configure(function() {
app.use(bella.init(mongoose, conn, [{username: 'bella', password: 'test'}]));
app.use(bella.authenticate());
app.use(bella.init(mongoose, {connection: conn, uri: dbUri, status: true, model: userModel}));
app.use(bella.authenticate('user'));
});

@@ -20,3 +20,3 @@ ```

#### .init(mongoose, conn, usersList)
#### .init(mongoose, options)

@@ -27,12 +27,16 @@ **Parameter**: `mongoose`

**Parameter**: `conn`
**Parameter**: `options`
**Type**: `Object`
**Example**: `var conn = mongoose.connect('mongodb://localhost/testdb');`
**Example**: `{connection: conn, status: true, model: userModel}`
**Parameter**: `usersList`
**Type**: `JSON Object`
**Example**: `[{username: 'bella', password: 'test'}]`
The 'init' is method responsible for initiating the module and set the Schema and create a model to be used by other methods.
- **connection**: Mongoose connection
- **uri**: Database uri e.g: `mongo://localhost/belladb`
- **status**: if true required a property `status` with the value `true`
- **model**: your custom mongoose user model
The `init` is method responsible for initiating the module and set the Schema and create a model to be used by other methods.
How to use this method

@@ -42,12 +46,18 @@

app.configure(function() {
app.use(bella.init(mongoose, conn, [{username: 'bella', password: 'test'}]));
app.use(bella.init(mongoose, {connection: conn, uri: dbUri, status: true, model: userModel}));
});
```
#### .create(domain, ip, cb)
#### .create(user, ip, domain, cb)
**Parameter**: `domain`
**Type**: `String`
**Example**: `example.com`
**Parameter**: `user`
**Type**: `ObjectID`
**Example**: `5349788398020b89c53c4297`
**Parameter**: `permissions`
**Type**: `Array`
**Example**: `['create_article']`
**Parameter**: `ip`

@@ -57,2 +67,8 @@ **Type**: `String`

**Parameter**: `domain`
**Type**: `String`
**Example**: `example.com`
**Parameter**: `cb`

@@ -62,8 +78,9 @@ **Type**: `Function`

The 'create' is method responsible for creating the access_tokens to be used by the authentication system.
The `create` is method responsible for creating the access_tokens to be used by the authentication system.
How to use this method
```javascript
bella.create('example.com', '127.0.0.1', function(err, access_token) {
bella.create(req.user, ['create_article'], '127.0.0.1', 'example.com', function(err, access_token) {
console.log('Token: ' + access_token);

@@ -78,2 +95,3 @@ });

**Parameter**: `cb`

@@ -83,2 +101,3 @@ **Type**: `Function`

The 'remove' method is responsible for removing users

@@ -94,7 +113,12 @@

#### .authenticate()
#### .authenticate(permission)
The 'authenticate' method is responsible for authenticating access the API.
Only users with Access Token, Domain, IP, Username and Password authenticated can access the API.
**Parameter**: `permission`
**Type**: `String`
**Example**: `create_article`
The `authenticate` method is responsible for authenticating access the API.
Only users with Access Token, Domain, and IP authenticated can access the API.
How to use this method

@@ -104,4 +128,4 @@

app.configure(function() {
app.use(bella.init(mongoose, conn));
app.use(bella.authenticate());
app.use(bella.init(mongoose, {connection: conn, uri: dbUri, status: true, model: userModel}));
app.use(bella.authenticate('create_article'));
});

@@ -111,3 +135,3 @@

app.get('/users', bella.authenticate(), ctrl);
app.get('/users', bella.authenticate('create_article'), ctrl);
```

@@ -123,4 +147,7 @@

## License
Copyright (c) 2014 Christopher EnyTC
The MIT License
Copyright (c) 2014, Christopher EnyTC
Permission is hereby granted, free of charge, to any person

@@ -127,0 +154,0 @@ obtaining a copy of this software and associated documentation

@@ -5,3 +5,3 @@ /*

*
* Copyright (c) 2014 Christopher EnyTC
* Copyright (c) 2014, Christopher EnyTC
* Licensed under the MIT license.

@@ -16,102 +16,63 @@ */

var chai = require('chai');
chai.expect();
var expect = chai.expect;
chai.should();
describe('bella module', function () {
//Describe #init
describe('#init()', function () {
it('should respond with Content-Type json and status code 200', function (done) {
request
.get('/')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200, {
hello: 'hello world'
}, done);
describe('bella module', function() {
//Describe #init
describe('#init()', function() {
it('should respond with Content-Type json and status code 200', function(done) {
request
.get('/')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200, {
hello: 'hello world'
}, done);
});
});
});
//Describe #create
describe('#create()', function () {
it('should create a new user and responde with status code 200', function (done) {
request
.post('/create')
.send({ip: '127.0.0.1', domain: 'example.com'})
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200, {
msg: 'Auth Key Created: d948a41098fc2aa79c24864d8978c4360cbef88837c4117957173626f3f50557520bcb6dfcdac6717692b2ad2545bcbaae6b3b927575a1cc5b667b23b3641d6c'
}, done);
//Describe #create
describe('#create()', function() {
it('should create a new user and responde with status code 200', function(done) {
request
.post('/create')
.send({
ip: '127.0.0.1',
domain: 'localhost'
})
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200, {
msg: 'Auth Key Created: null'
})
.end(done);
});
});
});
//Describe #authenticate
describe('#authenticate()', function () {
//With basic auth
//Describe #authenticate
describe('#authenticate()', function() {
//Bad Authentication
it('should respond with status code 401 and authentication error', function (done) {
request
.get('/users?username=notlogged&password=test')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(401, {
error: 'Bad Authentication. You do not have permission to access the API.'
}, done);
});
//Bad Authentication
it('should respond with status code 401 and authentication error', function(done) {
request
.get('/users')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(401, {
message: 'Bad Authentication. You do not have permission to access the API.',
error: 'access_token not found'
}, done);
});
it('should respond with status code 200 and authentication success', function (done) {
request
.get('/users?username=bella&password=test')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200, {
token: 'Access Token: undefined'
}, done);
});
//Bad Authentication
it('should respond with status code 401 and authentication error with access_token', function(done) {
request
.get('/users?access_token=testtoken')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(401, {
message: 'Bad Authentication. You do not have permission to access the API.',
error: 'access_token not found'
}, done);
});
it('should respond with status code 200 and authentication success', function (done) {
request
.get('/users?username=chris&password=123')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200, {
token: 'Access Token: undefined'
}, done);
});
//Bad Authentication
it('should respond with status code 401 and authentication error', function (done) {
request
.get('/users')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(401, {
error: 'Bad Authentication. You do not have permission to access the API.'
}, done);
});
it('should respond with status code 200 and authentication success', function (done) {
request
.get('/users?access_token=d948a41098fc2aa79c24864d8978c4360cbef88837c4117957173626f3f50557520bcb6dfcdac6717692b2ad2545bcbaae6b3b927575a1cc5b667b23b3641d6c')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200, {
token: 'Access Token: d948a41098fc2aa79c24864d8978c4360cbef88837c4117957173626f3f50557520bcb6dfcdac6717692b2ad2545bcbaae6b3b927575a1cc5b667b23b3641d6c'
}, done);
});
});
//Describe #remove
describe('#remove()', function () {
it('should remove a selected user and responde with status code 200', function (done) {
request
.del('/remove')
.send({
access_token: 'd948a41098fc2aa79c24864d8978c4360cbef88837c4117957173626f3f50557520bcb6dfcdac6717692b2ad2545bcbaae6b3b927575a1cc5b667b23b3641d6c'
})
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200, {
msg: 'Auth Key Deleted: d948a41098fc2aa79c24864d8978c4360cbef88837c4117957173626f3f50557520bcb6dfcdac6717692b2ad2545bcbaae6b3b927575a1cc5b667b23b3641d6c'
}, done);
});
});
});
{
"name": "Bella API",
"description": "Bella API: An API Authentication for node.js",
"version": "0.4.0",
"description": "Bella API: A API Authentication for node.js",
"version": "0.5.0",
"url": "https://github.com/chrisenytc/bella",

@@ -6,0 +6,0 @@ "options": {

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

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