Example #1
0
	constructor() {
		super( ...arguments );

		this.bindNode = this.bindNode.bind( this );
		this.focusToolbar = this.focusToolbar.bind( this );
		this.focusSelection = this.focusSelection.bind( this );

		this.switchOnKeyDown = cond( [
			[ matchesProperty( [ 'keyCode' ], ESCAPE ), this.focusSelection ],
		] );
	}
module.exports = function (app) {
    app.use(['/applications/*', '/organizations/*', '/accounts/*', '/factors/*', '/challenges/*'], updateBearer, handleRedirects);
    //handle successful 1st factor: either redirect to application or ask for a 2nd factor
    app.post('/applications/:id/loginAttempts', afterAuthentication(_.property('account.href'), false));
    //after account creation, redirect to the application if the email verification workflow is not enabled
    app.post(
        ['/applications/:id/accounts', '/organizations/:id/accounts'],
        afterAuthentication(result => Optional.ofNullable(result.href).filter(_.constant(result.status === 'ENABLED')).orElseGet(_.stubFalse), true)
    );
    //tokens should not be exposed to the user
    app.post('/applications/:id/passwordResetTokens', suppressOutput);
    //password reset tokens can only be used once
    app.post('/applications/:applicationId/passwordResetTokens/:tokenId', removeCurrentPathFromScope);
    //allow challenging newly created factors
    app.post('/accounts/:id/factors', addPathsToScope(r => ({['/factors/' + r.id + '/challenges']: ['post']})));
    //Hide configured factor secrets
    app.get('/accounts/:id/factors', hideFactorSecrets);
    //after getting factors:
    // - allow deleting them if the user is authenticated (security settings view)
    // - allow challenging verified factors if he is not authenticated yet
    app.get('/accounts/:id/factors', addPathsToScope(
        (r, req) => req.authInfo.authenticated ?
            _(r.items)
                .map(f => ({['/factors/' + f.id]: ['delete']}))
                .reduce(_.merge) :
            _(r.items)
                .filter(_.matches({verificationStatus: 'VERIFIED'}))
                .map(f => ({['/factors/' + f.id + '/challenges']: ['post']}))
                .reduce(_.merge)
    ));
    //allow veryfing created challenges
    app.post('/factors/:id/challenges', addPathsToScope(_.cond([[_.matches({status: 'CREATED'}), c => ({['challenges/' + c.id]: ['post']})], [_.stubTrue, _.stubObject]])));
    //handle successful 2nd factor: redirect to application if the user is not yet authenticated
    app.post(['/challenges/:id', '/factors/:id/challenges'], afterAuthentication(
        (result, req) => !req.authInfo.authenticated && result.status === 'SUCCESS' ? result.account.href : null,
        false,
        _.property('type')
    ));
    //redirect to application once the user is done setting up his account (password or multi factor change)
    app.get('/accounts/:id', afterAuthentication(_.property('href'), false));
    //allow the user to choose any of his organization
    app.get('/accounts/:id/organizations', addPathsToScope((r, req) => _(r.items).map(o => ({[`${req.path}/${o.id}`]: 'post'})).reduce(_.merge)));
    //handle organization choice
    app.post('/accounts/:accountId/organizations/:organizationId',
        afterAuthentication(
            _.property('account.href'),
            null,
            null,
            _.property('organization.href')
        )
    );
};
 .orElseGet(() => {
     //ros => request organization selection
     if (req.authInfo.ros) {
         return models.account.build({id: accountId}).countOrganizations()
             .then(_.cond([
                 //no org => no need for selection
                 [_.partial(_.eq, 0), _.constant(null)],
                 //only one org => just take this one
                 [_.partial(_.eq, 1), () => models.account.build({id: accountId}).getOrganizations({
                     limit: 1,
                     attributes: ['id']
                 }).get(0).get('href')],
                 //more than one: selection needed
                 [_.stubTrue, _.stubFalse]
             ]));
     } else {
         //no org requested
         return null;
     }
 })
 * Returns whether the node is a function declaration that has a block
 * @param {Object} node
 * @returns {boolean}
 */
const isFunctionDefinitionWithBlock = _.overSome(
    _.matchesProperty('type', 'FunctionExpression'),
    _.matches({type: 'ArrowFunctionExpression', body: {type: 'BlockStatement'}})
)

/**
 * If the node specified is a function, returns the node corresponding with the first statement/expression in that function
 * @param {Object} node
 * @returns {node|undefined}
 */
const getFirstFunctionLine = _.cond([
    [isFunctionDefinitionWithBlock, _.property(['body', 'body', 0])],
    [_.matches({type: 'ArrowFunctionExpression'}), _.property('body')]
])

/**
 *
 * @param {Object} node
 * @returns {boolean|undefined}
 */
const isPropAccess = _.overSome(_.matches({computed: false}), _.matchesProperty(['property', 'type'], 'Literal'))

/**
 * Returns whether the node is a member expression starting with the same object, up to the specified length
 * @param {Object} node
 * @param {string} objectName
 * @param {number} maxPropertyPathLength
 * @param {boolean} allowComputed
exports.nl = function() {
	return _.toArray(arguments).join('\n');
}

exports.addES6 = function(config) {
	var parserOptions = _.merge({ ecmaVersion: 6 }, config);

	return function(item, index) {
		item.parserOptions = parserOptions;

		return item;
	};
};

var invertValue = _.cond([[_.partial(_.eq, 0), _.constant(2)], [_.partial(_.eq, 2), _.constant(0)]]);

exports.getRule = function(ruleName, invert, obj) {
	var rule;

	var rules = obj || lintRules;

	if (_.isNumber(ruleName)) {
		ruleName = Object.keys(rules)[ruleName];
	}

	var retVal = _.pick(rules, ruleName);

	if (invert) {
		retVal[ruleName] = invertValue(retVal[ruleName]);
	}
 * Returns whether the node is a function declaration that has a block
 * @param {Object} node
 * @returns {boolean}
 */
var isFunctionDefinitionWithBlock = _.overSome(
    _.matchesProperty("type", "FunctionExpression"),
    _.matches({type: "ArrowFunctionExpression", body: {type: "BlockStatement"}})
);

/**
 * If the node specified is a function, returns the node corresponding with the first statement/expression in that function
 * @param {Object} node
 * @returns {node|undefined}
 */
var getFirstFunctionLine = _.cond([
    [isFunctionDefinitionWithBlock, _.property(["body", "body", 0])],
    [_.matches({type: "ArrowFunctionExpression"}), _.property("body")]
]);

/**
 *
 * @param {Object} node
 * @returns {boolean|undefined}
 */
var isPropAccess = _.overSome(_.matches({computed: false}), _.matchesProperty(["property", "type"], "Literal"));

/**
 * Returns whether the node is a member expression starting with the same object, up to the specified length
 * @param {Object} node
 * @param {string} objectName
 * @param {number} maxPropertyPathLength
 * @param {boolean} allowComputed
Example #7
0
const templates = {
    amd: templateAMDTemplate,
    commonjs: templateCommonJSTemplate,
    typescript: templateTypescriptTemplate,
    es6: templateES6Template,
    none: templatePJSTemplate,
    jsrt: templateJSRTTemplate
}

const isImportAsterisk = _.matches({member: '*'})
const defaultCase = _.constant(true)

const buildImportTypeScript = _.cond([
    [isImportAsterisk, d => `import ${d.alias} = require('${d.moduleName}');`],
    [_.matches({member: 'default'}), d => `import ${d.alias} from '${d.moduleName}';`],
    [defaultCase, d => `import { ${d.member} as ${d.alias} } from '${d.moduleName}';`]
])

const buildImportES6 = _.cond([
    [isImportAsterisk, d => `import * as ${d.alias} from '${d.moduleName}';`],
    [_.matches({member: 'default'}), d => `import ${d.alias} from '${d.moduleName}';`],
    [defaultCase, d => `import { ${d.member} as ${d.alias} } from '${d.moduleName}';`]
])

const buildImportCommonJS = _.cond([
    [isImportAsterisk, d => `var ${d.alias} = require('${d.moduleName}');`],
    [defaultCase, d => `var ${d.alias} = require('${d.moduleName}').${d.member};`]
])

const buildImport = {
Example #8
0
  content => `${htmlCatch}<script>${content}${jsCatch}</script>`
);
const wrapInStyle = partial(
  transformContents,
  content => `${htmlCatch}<style>${content}</style>`
);
const setExtToHTML = partial(setExt, 'html');
const padContentWithJsCatch = partial(compileHeadTail, jsCatch);
const padContentWithHTMLCatch = partial(compileHeadTail, htmlCatch);

export const jsToHtml = cond([
  [
    matchesProperty('ext', 'js'),
    flow(
      padContentWithJsCatch,
      wrapInScript,
      setExtToHTML
    )
  ],
  [stubTrue, identity]
]);

export const cssToHtml = cond([
  [
    matchesProperty('ext', 'css'),
    flow(
      padContentWithHTMLCatch,
      wrapInStyle,
      setExtToHTML
    )
  ],
Example #9
0
const HTML$JSReg = /html|js/;

const testHTMLJS = conforms({ ext: ext => HTML$JSReg.test(ext) });
// const testJS = matchesProperty('ext', 'js');
const passToNext = [stubTrue, identity];

// Detect if a JS multi-line comment is left open
const throwIfOpenComments = cond([
  [
    testHTMLJS,
    function _checkForComments({ contents }) {
      const openingComments = contents.match(/\/\*/gi);
      const closingComments = contents.match(/\*\//gi);
      if (
        openingComments &&
        (!closingComments || openingComments.length > closingComments.length)
      ) {
        throw new SyntaxError('Unfinished multi-line comment');
      }
    }
  ],
  passToNext
]);

// Nested dollar sign calls breaks browsers
const nestedJQCallReg = /\$\s*?\(\s*?\$\s*?\)/gi;
const throwIfNestedJquery = cond([
  [
    testHTMLJS,
    function({ contents }) {
      if (nestedJQCallReg.test(contents)) {
Example #10
0
const CLIENT_URL = 'clients/';

const CITIES_URL = 'cities/';
const CATEGORIES_URL = 'categories/';
const PLACES_URL = 'purchasePlaces/';

const httpRequests   = {};
const cache          = {};

let _HttpService, _$q;
let _curryHas = curry(has, 2);

let getFromCache = cond([
   [_curryHas(cache),         getCachePromise],
   [_curryHas(httpRequests),  addToHttpRequestDeferreds],
   [constant(true),           addHttpRequest]
]);

export default class cacheService {
   constructor(HttpService, $q) {
      'ngInject';
      _HttpService = HttpService;
      _$q = $q;
   }

   get(url) {
      return getFromCache(url);
   }

   clearCache(url) {
Example #11
0
const logger = require('../../helpers/loggingHelper').logger;

const exceptionToApiError = _.cond([
    //HTTP method not suported
    [
        _.property('allowedMethods'),
        e => new ApiError(405, 405, 'Method not supported (supported method(s): ' + e.allowedMethods.join() + ')')
    ],
    //unique constraint violation
    [
        _.matches({'name': 'SequelizeUniqueConstraintError'}),
        e => new ApiError(409, 2001, e.errors.length > 0 ? e.errors[0].message + ' (' + e.errors[0].value + ')' : e.message)
    ],
    //Ill-formed query or sequelize validation error
    [
        e => e.statusCode === 400 || _.startsWith(e.message, 'Validation error') || e.name === 'SequelizeValidationError',
        e => ApiError.BAD_REQUEST(_.isEmpty(e.errors) ? e.message : _.isEmpty(e.errors[0].errors) ? e.errors[0].message : e.errors[0].errors[0].message)
    ],
    //swagger validation errors (keep the first one)
    [
        _.property('failedValidation'),
        e => ApiError.BAD_REQUEST(_.isEmpty(e.results) ? e.message : e.results.errors[0].message)
    ],
    //other errors
    [
        _.stubTrue,
        ApiError.FROM_ERROR
    ]
]);

module.exports = function (err, req, res, next) {
Example #12
0
  Babel.transform(code, options).code;

// const sourceReg =
//  /(<!-- fcc-start-source -->)([\s\S]*?)(?=<!-- fcc-end-source -->)/g;
const NBSPReg = new RegExp(String.fromCharCode(160), 'g');

const testJS = matchesProperty('ext', 'js');
const testJSX = matchesProperty('ext', 'jsx');
const testHTML = matchesProperty('ext', 'html');
const testHTML$JS$JSX = overSome(testHTML, testJS, testJSX);
export const testJS$JSX = overSome(testJS, testJSX);

export const replaceNBSP = cond([
  [
    testHTML$JS$JSX,
    partial(vinyl.transformContents, contents => contents.replace(NBSPReg, ' '))
  ],
  [stubTrue, identity]
]);

function tryTransform(wrap = identity) {
  return function transformWrappedPoly(source) {
    const result = attempt(wrap, source);
    if (isError(result)) {
      console.error(result);
      // note(Bouncey): Error thrown here to collapse the build pipeline
      // At the minute, it will not bubble up
      // We collapse the pipeline so the app doesn't fall over trying
      // parse bad code (syntax/type errors etc...)
      throw result;
    }
module.exports = function (context) {
    var astUtil = require('../util/astUtil');
    var lodashUtil = require('../util/lodashUtil');
    var settings = require('../util/settingsUtil').getSettings(context);
    var _ = require('lodash');
    var nilChecks = {
        null: {
            isValue: _.matches({type: 'Literal', value: null}),
            expressionChecks: [getLodashTypeCheckedBy('isNull'), getValueComparedTo('null')]
        },
        undefined: {
            isValue: _.matches({type: 'Identifier', name: 'undefined'}),
            expressionChecks: [getLodashTypeCheckedBy('isUndefined'), getValueComparedTo('undefined'), getValueWithTypeofUndefinedComparison]
        }
    };

    function getLodashTypeCheckedBy(typecheck) {
        return function (node) {
            return lodashUtil.isLodashCallToMethod(node, settings, typecheck) && node.arguments[0];
        };
    }

    function getValueComparedTo(nil) {
        return function (node, operator) {
            return node.type === 'BinaryExpression' && node.operator === operator &&
                ((nilChecks[nil].isValue(node.right) && node.left) || (nilChecks[nil].isValue(node.left) && node.right));
        };
    }


    var getTypeofArgument = _.cond([
        [_.matches({type: 'UnaryExpression', operator: 'typeof'}), _.property('argument')]
    ]);

    var isUndefinedString = _.matches({type: 'Literal', value: 'undefined'});

    function getValueWithTypeofUndefinedComparison(node, operator) {
        return node.type === 'BinaryExpression' && node.operator === operator &&
            ((isUndefinedString(node.right) && getTypeofArgument(node.left)) ||
            (isUndefinedString(node.left) && getTypeofArgument(node.right)));
    }

    function checkExpression(nil, operator, node) {
        return _(nilChecks[nil].expressionChecks)
            .map(function (check) {
                return check(node, operator);
            })
            .find();
    }

    function checkNegatedExpression(nil, node) {
        return (astUtil.isNegationExpression(node) && checkExpression(nil, '===', node.argument)) || checkExpression(nil, '!==', node);
    }

    function isEquivalentExistingExpression(node, leftNil, rightNil) {
        var leftExp = checkExpression(leftNil, '===', node.left);
        return leftExp && astUtil.isEquivalentExp(leftExp, checkExpression(rightNil, '===', node.right));
    }

    function isEquivalentExistingNegation(node, leftNil, rightNil) {
        var leftExp = checkNegatedExpression(leftNil, node.left);
        return leftExp && astUtil.isEquivalentExp(leftExp, checkNegatedExpression(rightNil, node.right));
    }

    return {
        LogicalExpression: function (node) {
            if (node.operator === '||') {
                if (isEquivalentExistingExpression(node, 'undefined', 'null') ||
                    isEquivalentExistingExpression(node, 'null', 'undefined')) {
                    context.report(node, 'Prefer isNil over checking for undefined or null.');
                }
            } else if (isEquivalentExistingNegation(node, 'undefined', 'null') ||
                isEquivalentExistingNegation(node, 'null', 'undefined')) {
                context.report(node, 'Prefer isNil over checking for undefined or null.');
            }
        }
    };
};