thegameofcode/cipherlayer

View on GitHub
scripts/add_users.js

Summary

Maintainability
A
1 hr
Test Coverage
'use strict';

/* eslint-disable no-console, no-process-env */
const async = require('async');
const nock = require('nock');
const userMng = require('../src/managers/user');
const config = require('../config.json');
const userDao = require('../src/managers/dao');
/*
 * Objects for `async.eachSeries`
 */

// Function to apply to each fixture
const addFixture = function (fixture, callback) {

    const data = fixture;

    // Define user object to be passed to userMng
    const pin = null;
    const profileBody = {
        id: data._id.$oid || data._id,
        email: data.email,
        password: data.password || (process.env.DEFAULT_PASS ? process.env.DEFAULT_PASS : 'qwerty')
    };

    if (!profileBody.id || !profileBody.email || !profileBody.password) {
        console.log('Missing mandatory parameter(s)');
        return callback();
    }
    // Nock the createUser URL
    nock(`http://${config.private_host}:${config.private_port}${config.passThroughEndpoint.path}`, {
        reqheaders: {
            'Content-Type': 'application/json; charset=utf-8'
        }
    })
        .post(config.passThroughEndpoint.path)
        .reply(201, profileBody);

    // Save user data to database
    return userMng().createUser(profileBody, pin, err => {
        if (err) {

            if (err.err === 'auth_proxy_user_error') {
                console.log(`${profileBody.email} ${err.des}`);
                return callback();
            }
            return callback(err);
        }
        console.log(`${profileBody.email} added`);
        return callback();
    });

};

/*
 * Main part of the script:
 *  - Exports the function, or
 *  - Executes the function if running from CLI
 */
const runLoadFixtures = function (fixtureFile, callback) {
    console.log('running Load Fixtures');
    async.eachSeries(fixtureFile, addFixture, callback);
};

module.exports = runLoadFixtures;

if (!module.parent) { // Run as CLI command exec
    async.series([

        // Start cipherLayer components (mongodb, redis...)
        userDao.connect,

        function drop(done) {
            if (!process.env.DROP_DB) {
                return done();
            }
            console.log('Dropping database');
            return userDao.deleteAllUsers(done);
        },

        function load(done) {
            const fixtureFile = require(`${__dirname}/../tests/fixtures/User.json`);
            runLoadFixtures(fixtureFile, done);
        },

        userDao.disconnect

    ], err => {
        if (err) {
            console.error(err);
            process.exit(1);
        }

        console.info('Fixtures loaded');
        process.exit();
    });

}