Skip to content

Commit

Permalink
commit for version 2.2.0
Browse files Browse the repository at this point in the history
  • Loading branch information
vamsee committed Apr 30, 2020
2 parents 8d4112d + 57d3b4a commit 1e51b3f
Show file tree
Hide file tree
Showing 19 changed files with 442 additions and 378 deletions.
13 changes: 7 additions & 6 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/client/
/coverage/
/node_modules/
server/dropdb.js
/lib/expression-language/expression-syntax-parser.js
/test/
build/
client/
coverage/
node_modules/
test/
drop.js
Gruntfile.js
2 changes: 1 addition & 1 deletion .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@
"no-undefined": 1, // http://eslint.org/docs/rules/no-undefined
"no-with": 2, // http://eslint.org/docs/rules/no-with
"handle-callback-err": 1, // http://eslint.org/docs/rules/handle-callback-err
"radix": 2, // http://eslint.org/docs/rules/radix
"radix": 0, // http://eslint.org/docs/rules/radix
"wrap-iife": [2, "any"], // http://eslint.org/docs/rules/wrap-iife
"yoda": 2, // http://eslint.org/docs/rules/yoda

Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,4 @@ out/
*.zip
/common/models/test
package-lock.json
oracle-user.sh
40 changes: 2 additions & 38 deletions Gruntfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,38 +10,6 @@ module.exports = function GruntConfig(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),

mkdir: {
all: {
options: {
create: ['dist']
}
}
},

copy: {
main: {
files: [
// includes files within path and its sub-directories
{
expand: true,
src: ['**', '!node_modules/**', '!coverage/**'],
dest: 'dist/'
}
]
}
},

mochaTest: {
test: {
options: {
quiet: false,
clearRequireCache: true,
timeout: 100000
},
src: ['test/*.spec.js']
}
},

clean: {
coverage: {
src: ['coverage/']
Expand All @@ -56,7 +24,7 @@ module.exports = function GruntConfig(grunt) {
mochaOptions: ['--exit']
},
coverage: {
src: 'test/test.js',
src: 'test/*.spec.js',
options: {
timeout: 60000,
check: {
Expand All @@ -72,12 +40,8 @@ module.exports = function GruntConfig(grunt) {
});

// Add the grunt-mocha-test tasks.
grunt.loadNpmTasks('grunt-mocha-test');
grunt.loadNpmTasks('grunt-mocha-istanbul');
grunt.loadNpmTasks('grunt-contrib-clean');

grunt.loadNpmTasks('grunt-mkdir');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-mocha-istanbul');

grunt.registerTask('test-with-coverage', ['clean:coverage', 'mocha_istanbul']);
};
64 changes: 60 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,19 +1,22 @@
# oe-validation
# oe-component-passport

This project implements validation functionality on Models.
This project implements multiple authentication capability provided by passportjs.

## Pre-requisites

* oe-cloud
* oe-logger
* loopback-component-passport
* Configure model-config.json of application with UserIdentity and UserCredential with proper datasource as per application's datasource configuration


## Features

1. Local and 3rd party authentication support (like Facebook, google oauth authentication)
2. JWT authentication support
3. Configurable "Cookie" generation with users/login api (set ENABLE_COOKIE=true)
3. JWT as access_token
4. Configurable "Cookie" generation with users/login api (set ENABLE_COOKIE=true)
5. Parameterized providers.json

### Difference from previous version of oe-cloud

Expand All @@ -36,8 +39,61 @@ Usage of this module needs an entry in package.json and also an entry to applica
```

Inside your application, authentication can be done using "/User/login" or "/auth/local" which returns access_token as payload and in cookie if configured.
### Configure model-config.json

Add UserIdentity and UserCredential models in your application's model-config.json (in your application's server directory) with correct dataSource name.
Also set public true or false depending on your requirement to expose those as REST API or not.

```
"UserCredential": {
"dataSource": "db",
"public": false
},
"UserIdentity": {
"dataSource": "db",
"public": false
}
```

### Parameterized providers.json

You can write providers json like this where you can parameterise a value like *${variable_name}*

``` javascript
{
"local": {
"provider": "local",
"module": "passport-local",
"usernameField": "${userfieldname}",
"passwordField": "${PASSWORD_FIELD_NAME}",
"authPath": "/auth/local",
"successRedirect": "/explorer",
"failureRedirect": "/login",
"failureFlash": false,
"callbackHTTPMethod": "post",
"setAccessToken": true
}
}

```
In above example, usernameField value would be set to value of environment (or configuration) variable '**userfieldname**' and passwordField value would be from environment (or configuration) variable '**PASSWORD_FIELD_NAME**'. If those environmental variables are not set or not in configuration, '' (blank string) would be assigned.

### JWT_FOR_ACCESS_TOKEN
To improve performance JWT can be used as access token. to enable that, set following environmental variable
``` javascript
JWT_SECRET_KEY = 'secret'
JWT_FOR_ACCESS_TOKEN = true;
```
*JWT_SECRET_KEY* could be any secret consisting alphanumeric value.


Please note that this implementation of JWT just replaces generic access-token with JWT and saves checking user id from database for api every request that needs authentication (ACL).

To implement custom JWT payload to have user roles(to use in ACL varification) and other details; override User.login function along with User.prototype.createAccessToken and AccessToken.resolve

For any other login related customization, like password complexity, password history etc; please extend User model and add customized code in extended model (some example available in oe-demo-app)


Examples are coming up in oe-demo-app project.



Expand Down
42 changes: 39 additions & 3 deletions lib/passport.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,15 +49,51 @@ module.exports.configurePassport = function configurePassport(app, providerConfi
// Merge util will merge providers.json from each dependent module and pass configurePassport() with this parameter
try {
config = providerConfigParameter ? providerConfigParameter : require(path.join(app.locals.apphome, 'providers.json'));
config = getUpdatedConfigObject(config);
} catch (err) {
console.error('could not load login configuration ', path.join(app.locals.apphome, 'providers.json'), ' https://docs.strongloop.com/display/public/LB/Configuring,providers.json ', err);
process.exit(1);
}

// var flash = require('connect-flash');
function checkDynamicParam(value) {
var PARAM_REGEX = /\$\{(\w+)\}$/;
var match = value.match(PARAM_REGEX);
if (match) {
var appValue = process.env[match[1]] || app.get(match[1]) || '';
if (appValue !== undefined) {
value = appValue;
} else {
console.warn('%s does not resolve to a valid value. ' +
'"%s" must be resolvable by app.get().', value, match[1]);
}
}
return value;
}
function getUpdatedConfigObject(element) {
if (typeof element === 'string') {
return checkDynamicParam(element);
} else if (Array.isArray(element)) {
return element.map(getUpdatedConfigObject);
} else if (typeof element !== 'object' || element === null) {
return element;
}
// recurse into object props
var interpolated = {};
Object.keys(element).forEach(configKey => {
var value = element[configKey];
if (Array.isArray(value)) {
interpolated[configKey] = value.map(getUpdatedConfigObject);
} else if (typeof value === 'string') {
interpolated[configKey] = checkDynamicParam(value);
} else if (typeof value === 'object' && Object.keys(value).length) {
interpolated[configKey] = getUpdatedConfigObject(value);
} else {
interpolated[configKey] = value;
}
});
return interpolated;
}

// boot(app, __dirname);
// app.emit('ready');
// to support JSON-encoded bodies
var jsonremoting = {
limit: '1mb'
Expand Down
22 changes: 9 additions & 13 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
{
"name": "oe-component-passport",
"version": "2.1.0",
"description": "oe-cloud modularization project",
"version": "2.2.0",
"description": "oe-cloud module to initialize passport component supporting regular strategies and JWT as access token",
"engines": {
"node": ">=6"
},
"main": "index.js",
"scripts": {
"pretest": "npm install --no-optional",
"test": "mocha --no-timeouts test/test.js",
"test": "mocha --no-timeouts test/*.spec.js",
"lint": "eslint .",
"fix-lint": "eslint --fix .",
"grunt-cover": "grunt test-with-coverage"
},
"dependencies": {
"body-parser": "1.9.0",
"body-parser": "1.19.0",
"cookie-parser": "1.4.3",
"jsonwebtoken": "8.4.0",
"loopback-component-passport": "3.10.0",
Expand All @@ -31,25 +31,21 @@
"async": "2.6.1",
"babel-eslint": "7.2.3",
"chai": "3.4.1",
"chai-datetime": "1.4.0",
"chai-things": "0.2.0",
"chalk": "1.1.1",
"eslint": "4.10.0",
"grunt": "1.0.4",
"grunt-banner": "0.6.0",
"grunt-cli": "1.3.2",
"grunt-contrib-clean": "2.0.0",
"grunt-contrib-copy": "1.0.0",
"grunt-jsbeautifier": "0.2.13",
"grunt-mkdir": "1.0.0",
"grunt-mocha-istanbul": "5.0.2",
"grunt-mocha-test": "0.13.3",
"istanbul": "0.4.5",
"mocha": "5.2.0",
"oe-cloud": "^2.0.0",
"oe-connector-mongodb": "^2.0.0",
"oe-connector-oracle": "^2.0.0",
"oe-connector-postgresql": "^2.0.0",
"superagent-defaults": "0.1.14",
"supertest": "3.4.2",
"loopback-connector-mongodb": "3.9.2",
"oe-cloud": "^2.0.0"
"supertest": "3.4.2"
},
"author": "Dipayan Aich <[email protected]>",
"repository": {
Expand Down
9 changes: 0 additions & 9 deletions server/model-config.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,5 @@
"mixins": [
"../common/mixins"
]
},
"UserCredential": {
"dataSource": "db",
"public": false
},
"UserIdentity": {
"dataSource": "db",
"public": false
}

}
46 changes: 46 additions & 0 deletions test/bootstrap.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
var oecloud = require('oe-cloud');
var logger = require('oe-logger');
var log = logger('test-bootstrapper');

// var loopback = require('loopback');
// oecloud.attachMixinsToBaseEntity("SkeletonMixin");
process.env.userfieldname = 'username';
process.env.PASSWORD_FIELD_NAME = 'password';
process.env.JWT_SECRET_KEY = 'secret';
process.env.JWT_FOR_ACCESS_TOKEN = true;

oecloud.observe('loaded', function (ctx, next) {
console.log('oe-cloud modules loaded');
return next();
});

var testContext = {
ctx: {
tenantId: 'test-tenant'
}
};

oecloud.get('/info', function (req, res) {
return res.end(JSON.stringify({'status': 'logged in', 'access-token': res.accessToken}));
});

oecloud.get('/failed', function (req, res) {
return res.end(JSON.stringify({'status': 'failed'}));
});

oecloud.boot(__dirname, function (err) {
if (err) {
log.error(testContext, err);
// console.log('Error:', err)
process.exit(1);
}
oecloud.start();
oecloud.emit('test-start');
});

module.exports = new Promise(booted =>
oecloud.on('test-start', () => {
// debugger;
// console.log('booted');
booted();
} ) );
3 changes: 1 addition & 2 deletions test/datasources.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,14 @@
"name": "transient",
"connector": "transient"
},

"db": {
"host": "localhost",
"port": 27017,
"url": "mongodb://localhost:27017/oe-component-passport-test",
"database": "oe-component-passport-test",
"password": "admin",
"name": "db",
"connector": "mongodb",
"connector": "oe-connector-mongodb",
"user": "admin",
"connectionTimeout": 500000,
"connectTimeoutMS": 500000,
Expand Down
Loading

0 comments on commit 1e51b3f

Please sign in to comment.