Exemple #1
0
module.exports = function () {

    var rc = require('./utils/manageRC');
    var config = rc.init();

    if (config.exists) {

        program.version(pkg.version).option('-c, --component [name]', 'Create a component with specified name').option('-b, --bundle [name]', 'Create an AEM bundle with a specified name').option('-l, --clientlib [name]', 'Create a Client Library with a specified name').option('-s, --set_style_language [arg]', 'Set the style_language for the project').parse(process.argv);

        if (program.component) createComponent(program);
        if (program.bundle) createBundle(program);
        if (program.clientlib) createClientLib(program);
        if (program.set_style_language) editRc.changeStyleLanguage(program.set_style_language);

        if (!program.component && !program.clientlib && !program.bundle && !program.set_style_language) {
            console.log(chalk.red.bold("\n[ ERROR ] No argument supplied"));
            console.log(chalk.yellow("if you need help use: ") + 'iron -h \n');
        }
    } else {

        program.version(pkg.version).option('[name]', 'Give your project a name').parse(process.argv);

        if (program.args[0]) {
            createProject(program);
        } else {
            console.log(chalk.red.bold("[ ERROR ] No argument for project name") + '\n' + chalk.yellow("Please supply Iron with a project name for example: ") + 'iron myProject \n');
        }
    }
};
Exemple #2
0
			return { repos: _.map( val, function( val ) {
				var repo = {};
				if ( val.map.endsWith( '-folder' ) ) {
					var folderType = val.map.slice( 0, -7 );
					if ( -1 === [ 'themes', 'plugins', 'mu-plugins' ].indexOf( folderType ) ) {
						this.log(
							chalk.red.bold( "Uh oh!\n" ) +
							chalk.red( "One of your source maps contains a folder type that " ) +
							chalk.red( "doesn't exist... please fix this and try again. :(\n" ) +
							chalk.red( "Folder maps must be themes-folder, plugins-folder, or " ) +
							chalk.red( "mu-plugins-folder.\n\n") +
							chalk.red.bold( "See :\n") +
							chalk.red( JSON.stringify( val, null, "  " ) )
						);
						process.exit( 0 );
					}
					repo.dir = folderType;
					if ( val.dir ) {
						repo.path = [ 'src', val.dir ];
					} else if ( path.extname( val.url ) ) {
						repo.path = [ 'src', path.basename( val.url ).slice( 0, 0 - path.extname( val.url ) ) ];
					} else {
						repo.path = [ 'src', path.basename( val.url ) ];
					}
				}
				return _.assign( {
					repo: val.url,
					path: repoPathMap[ val.map ],
				}, repo );
			}.bind( this ) ) };
Exemple #3
0
  webpack(config, (err, stats) => {
    if (err) {
      console.log(chalk.red.bold('Failed to create a production build!'));
      console.log(chalk.red(err.message || err));
      process.exit(1);
    }

    if (stats.compilation.errors && stats.compilation.errors.length) {
      console.log(chalk.red.bold('Failed to create a production build!'));
      stats.compilation.errors.forEach(err => console.log(chalk.red(err.message || err)));
      process.exit(1);
    }

    const jsonStats = stats.toJson();

    console.log('Assets:');
    const assets = jsonStats.assets.slice();
    assets.sort((a, b) => b.size - a.size);
    assets.forEach(asset => {
      let sizeLabel = formatSize(asset.size);
      const leftPadding = ' '.repeat(Math.max(0, 8 - sizeLabel.length));
      sizeLabel = leftPadding + sizeLabel;
      console.log('', chalk.yellow(sizeLabel), asset.name);
    });
    console.log();

    const seconds = jsonStats.time / 1000;
    console.log('Duration: ' + seconds.toFixed(2) + 's');
    console.log();

    console.log(chalk.green.bold('Compiled successfully!'));
  });
glob(cli.input[0], function(err, files) {

  if (err) {
    console.warn(chalk.red(err));
  }

  files.forEach(function(f) {

    var html = fs.readFileSync(path.join(process.cwd(), f), 'utf8');

    var component = extractReactComponents(html, {
      componentType: flags.c,
      moduleType: flags.m,
      moduleFileNameDelimiter: processDelimiterOption(flags.d),
      output: {
        path: flags.o,
        fileExtension: flags.e
      }
    });

    components.push(component);
  });

  var stats = components.reduce(function(agg, cs) {

    var names = Object.keys(cs);

    agg.count += names.length;
    agg.names = agg.names.concat(names);

    return agg;
  }, { count: 0, names: [] });

  console.log(chalk.green('Successfully generated ' + chalk.red.bold(stats.count) + ' components: ' + chalk.red.bold(stats.names.join(', '))));
});
        function doFinish() {
            logger.pendingTasks = logger.pendingTasks.filter((pendingTask) => {
                if (pendingTask.migrateTaglibFile) {
                    if (pendingTask.migrateTaglibFile.endsWith('lasso/marko-taglib.json')) {
                        return false;
                    } else if (pendingTask.migrateTaglibFile.endsWith('marko-widgets/marko-taglib.json')) {
                        return false;
                    }
                }

                return true;
            });

            var results = logger.end();

            console.log(results.output);

            fs.writeFileSync(logFile, results.outputNoColor, { encoding: 'utf8' });

            if (results.warningCount) {
                console.log(chalk.red.bold(`Migration completed with warning(s):`));
            } else {
                console.log(chalk.green('Migration completed successfully!:'));
            }

            console.log(chalk.red.bold(`- ${results.warningCount} warning(s)`));
            console.log(chalk.yellow.bold(`- ${results.pendingTaskCount} remaining task(s)`));
        }
    projectPackages.forEach(projectPackage => {
      const projectVersion = projectPackage.dependencies[module];

      if (rootVersion !== projectVersion && projectVersion !== undefined) {
        invalidDependencies.push(
          `${module} is ${chalk.red.bold(rootVersion)} in root but ` +
            `${chalk.red.bold(projectVersion)} in ${projectPackage.name}`
        );
      }
    });
Exemple #7
0
 function formatResult (result) {
   switch (result.outcome) {
     case CONSTANTS.PASSED:
       return chalk.green('.')
     case CONSTANTS.FAILED:
       return chalk.red.bold('F')
     case CONSTANTS.ERRORED:
       return chalk.red.bold('E')
   }
 }
    projectPackages.forEach(projectPackage => {
      // Not all packages have dependencies (eg react-is)
      const projectVersion = projectPackage.dependencies
        ? projectPackage.dependencies[module]
        : undefined;

      if (rootVersion !== projectVersion && projectVersion !== undefined) {
        invalidDependencies.push(
          `${module} is ${chalk.red.bold(rootVersion)} in root but ` +
            `${chalk.red.bold(projectVersion)} in ${projectPackage.name}`
        );
      }
    });
Exemple #9
0
    function * mergePr () {
        var commitMessage;
        yield executil.execHelper(executil.ARGS('git checkout master'));

        yield executil.execHelper(['git', 'pull', origin, 'master']);
        var commit = yield executil.execHelper(executil.ARGS('git rev-parse HEAD'), /* silent */ true);
        yield executil.execHelper(['git', 'fetch', /* force update */ '-fu', origin,
            'refs/pull/' + argv.pr + '/head:' + localBranch]);

        if (!pull_only) {
            try {
                yield executil.execHelper(executil.ARGS('git merge --ff-only ' + localBranch),
                    /* silent */ true, /* allowError */ true);
                commitMessage = yield executil.execHelper(executil.ARGS('git log --format=%B -n 1 HEAD'), /* silent */ true);
                yield executil.execHelper(['git', 'commit', '--amend', '-m',
                    commitMessage + '\n\n This closes #' + argv.pr]);
            } catch (e) {
                if (e.message.indexOf('fatal: Not possible to fast-forward, aborting.') > 0) {
                    // Let's try to rebase
                    yield executil.execHelper(executil.ARGS('git checkout ' + localBranch));
                    yield executil.execHelper(['git', 'pull', '--rebase', origin, 'master']);
                    yield executil.execHelper(executil.ARGS('git checkout master'));
                    yield executil.execHelper(executil.ARGS('git merge --ff-only ' + localBranch));
                    commitMessage = yield executil.execHelper(executil.ARGS('git log --format=%B -n 1 HEAD'), /* silent */ true);
                    yield executil.execHelper(['git', 'commit', '--amend', '-m',
                        commitMessage + '\n\n This closes #' + argv.pr]);
                } else {
                    throw e;
                }
            }
            console.log();
            var commits = yield executil.execHelper(['git', 'log',
                '--graph',
                '--pretty=format:%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset',
                '--abbrev-commit',
                '--stat',
                commit + '..HEAD'], /* silent */ true);

            if (commits) {
                console.log('---------------');
                console.log('Commits merged:');
                console.log('---------------');
                console.log(commits);
                console.log(chalk.red.bold('Success! Please test, squash, and rebase to meaningful commits before pushing to remote master using: git push origin master'));
            } else {
                console.log(chalk.red.bold('Nothing to merge - Has this already been merged?'));
            }
        }
    }
const validateSnapshotVersion = snapshotContents => {
  const versionTest = SNAPSHOT_VERSION_REGEXP.exec(snapshotContents);
  const version = versionTest && versionTest[1];

  if (!version) {
    return new Error(
    chalk.red(
    `${chalk.bold('Outdated snapshot')}: No snapshot header found. ` +
    `Jest 19 introduced versioned snapshots to ensure all developers on ` +
    `a project are using the same version of Jest. ` +
    `Please update all snapshots during this upgrade of Jest.\n\n`) +

    SNAPSHOT_VERSION_WARNING);

  }

  if (version < SNAPSHOT_VERSION) {
    return new Error(
    chalk.red(
    `${chalk.red.bold('Outdated snapshot')}: The version of the snapshot ` +
    `file associated with this test is outdated. The snapshot file ` +
    `version ensures that all developers on a project are using ` +
    `the same version of Jest. ` +
    `Please update all snapshots during this upgrade of Jest.\n\n`) +

    `Expected: v${SNAPSHOT_VERSION}\n` +
    `Received: v${version}\n\n` +
    SNAPSHOT_VERSION_WARNING);

  }

  if (version > SNAPSHOT_VERSION) {
    return new Error(
    chalk.red(
    `${chalk.red.bold('Outdated Jest version')}: The version of this ` +
    `snapshot file indicates that this project is meant to be used ` +
    `with a newer version of Jest. ` +
    `The snapshot file version ensures that all developers on a project ` +
    `are using the same version of Jest. ` +
    `Please update your version of Jest and re-run the tests.\n\n`) +

    `Expected: v${SNAPSHOT_VERSION}\n` +
    `Received: v${version}`);

  }

  return null;
};
Exemple #11
0
const handler = (err, stats, options) => {
  options = Object.assign({
    log: true,
  }, options)

  const errors = stats.compilation.errors
  if (errors.length) {
    const err = errors[0].error
    console.log()
    console.log(chalk.red.bold(err.message))
    console.log(chalk.red(err.stack))
    console.log()
    return
  }

  browserSync.reload()

  if (options.log) {
    const time = moment
      .duration(stats.endTime - stats.startTime)
      .asSeconds()
      .toFixed(2)
    gutil.log(`Finished '${chalk.cyan('webpack')}' after ${chalk.magenta(`${time} s`)}`)
  }
}
Exemple #12
0
  return new Promise((resolve, reject) => {
    const rootPath = process.cwd()
    if (!utils.checkIOS(rootPath)) {
      console.log()
      console.log(chalk.red('  iOS project not found !'))
      console.log()
      console.log(`  You should run ${chalk.blue('weexpack init')} first`)
      reject()
    }

    // change working directory to ios
    // process.chdir(path.join(rootPath, 'ios/playground'))
    process.chdir(path.join(rootPath, 'platforms/ios'))

    const xcodeProject = utils.findXcodeProject(process.cwd())

    if (xcodeProject) {
      console.log()
      resolve({xcodeProject, options, rootPath})
    } else {
      console.log()
      console.log(`  ${chalk.red.bold('Could not find Xcode project files in ios folder')}`)
      console.log()
      console.log(`  Please make sure you have installed iOS Develop Environment and CocoaPods`)
      console.log(`  See ${chalk.cyan('http://alibaba.github.io/weex/doc/advanced/integrate-to-ios.html')}`)
      reject()
    }
  })
Exemple #13
0
        this.npmInstall(packages, {'save': true}, function () {
            exec('which paxctl', function (error, stdout, stderr) {
                if (error) {
                    that.log.error('Cannot set PhantomJS PAX headers. Skipping ...');
                } else {
                    var paxctl = stdout.trim();
                    [
                        'node_modules/iconizr/node_modules/phantomjs/lib/phantom/bin/phantomjs',
                        'node_modules/phantomjs-prebuilt/lib/phantom/bin/phantomjs'
                    ].forEach(function (phamtomJS) {
                        that.spawnCommandSync(paxctl, ['-cm', phamtomJS]);
                    });
                }
            });

            // Adjust file permissions
            that.log('Adjusting file & directory permissions ...');
            that.spawnCommandSync('find', ['-type', 'f', '-exec', 'chmod', '664', '{}', '\;']);
            that.spawnCommandSync('find', ['-type', 'd', '-exec', 'chmod', '775', '{}', '\;']);

            that.log();
            that.log(chalk.green.bold('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'));
            that.log(chalk.green.bold('Congratulations - the tollwerk project kickstarter finished successfully!'));
            that.log(chalk.green.bold('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'));

            if (that.t3x_tw_squeezr) {
                that.log();
                that.log(chalk.red.bold('Please remember to follow these steps to activate the squeezr extension:'));
                that.log(chalk.yellow('1.) Visit the TYPO3 extension manager (EM) and run the squeezr update script. Repeat this each time you modify the extension\'s configuration.'));
                that.log(chalk.yellow('2.) In the constant editor, define some image breakpoints and enable squeezr.'));
            }
        });
Exemple #14
0
  }).exec(function (err) {
    if (wasSigintTriggered) { return; }
    else {
      process.removeListener('SIGINT', sigintListener);
    }

    if (err) {
      console.log(chalk.dim('------------------------------------------------------------'));
      console.log(chalk.red.bold('Failed to install dependencies.'));
      console.log(chalk.white.bold('New app was generated successfully, but some dependencies'));
      console.log(chalk.white.bold('in node_modules/ are probably still incomplete or missing.'));
      console.log();
      console.log(chalk.white('Before you continue, please make sure you are connected to the'));
      console.log(chalk.white('internet, and that your NPM registry hasn\'t gone down.'));
      console.log(chalk.white('Then cd into the new app and run:'));
      console.log(chalk.white('    rm -rf node_modules && npm install'));
      console.log();
      console.log(chalk.gray('See below for complete error details.'));
      console.log(chalk.gray('For more help, visit https://sailsjs.com/support.'));
      console.log();
      return cb(err);
    }

    // SUCCESS!
    cb.log.info('Created a new Sails app `' + scope.appName + '`!');

    return cb();

  });//</ Process.executeCommand>
Exemple #15
0
 Task.prototype.showMethod = function(method, path, entity) {
   console.log('');
   console.log(chalk.red.bold(entity.id));
   console.log(chalk.blue('  '+path.id));
   this.showOneMethod(method);
   console.log('');
 };
    }, function (error, response) {
      pingCount += 1;

      if (!error && response.statusCode > 199 && response.statusCode < 300) {
        console.log(chalk.dim('At ' + (new Date()).toTimeString()), chalk.green.bold(file), 'pinged.');
      } else {
        console.error(
          chalk.dim('At ' + (new Date()).toTimeString()),
          chalk.red.bold(file),
          'failed to be pinged.',
          !response ? chalk.dim('No HTTP response') : chalk.dim(
            'HTTP code ' + response.statusCode +
            (response.headers['retry-after'] ? ' – should retry after ' + parseInt(response.headers['retry-after'], 10) + ' seconds' : '')
          )
        );

        fails += 1;
        delete templateFetchesLeft[file];

        if (!options.sync && objectEmpty(templateFetchesLeft)) {
          console.log(chalk.green('Done with all ' + count + ' pings!'), fails ? chalk.red(fails + ' of them failed.') : '');
          server.close();
        }
      }

      if (options.sync && pingCount === count) {
        server.close();
      }
    });
Exemple #17
0
 http({ url }, (error, response) => {
   if (!error && response.statusCode === 200) {
     if (response.headers['x-gg-state'] === 'cached') {
       config.wordnik.date.remain++
       noon.save(CFILE, config)
       if (config.usage) console.log('Cached response, not decrementing usage.')
     }
     const list = JSON.parse(response.body)
     const hcont = []
     for (let i = 0; i <= list.length - 1; i++) {
       const item = list[i]
       if (item.type === 'stress') {
         hcont.push(`${chalk.red.bold(item.text)}`)
         tofile[[`stress${i}`]] = item.text
       } else if (item.type === 'secondary stress') {
         hcont.push(ctstyle(item.text))
         tofile[[`secondary${i}`]] = item.text
       } else {
         hcont.push(ctstyle(item.text))
         tofile[[`syllable${i}`]] = item.text
       }
       if (i < list.length - 1) hcont.push(ctstyle('-'))
     }
     themes.label(theme, 'right', 'Hyphenation', hcont.join(''))
     if (argv.o) tools.outFile(argv.o, argv.f, tofile)
     if (config.usage) reset ? console.log(`Timestamp expired, not decrementing usage.\n${config.wordnik.date.remain}/${config.wordnik.date.limit} requests remaining this hour.`) : console.log(`${config.wordnik.date.remain}/${config.wordnik.date.limit} requests remaining this hour, will reset in ${59 - minutes} minutes.`)
   } else throw new Error(`HTTP ${error.statusCode}: ${error.reponse.body}`)
 })
Exemple #18
0
        function(results){
          if (typeof results[0] != "undefined") {
            console.log(chalk.green.bold("Subtitles found!"));
            console.log(chalk.green.bold("Downloading..."));

            //download file
            var url = results[0].SubDownloadLink.split('.gz').join('.srt');
            var dest = os.tmpdir() + "/sub.srt";
            var cb;

            var download = function(url, dest, cb) {
              var file = fs.createWriteStream(dest);
              var request = http.get(url, function(response) {
                response.pipe(file);
                file.on('finish', function() {
                  file.close(cb);
                  console.log(chalk.green.bold("Subtitles downloaded."));
                  peerflix_subtitle = dest;
                  deferred.resolve(peerflix_subtitle);
                });
              });
            };

            download(url, dest, cb);

          } else {
            console.log(chalk.red.bold("No subtitles found :( Sorry."));
            deferred.resolve(false);
          }
        }
 exec('./node_modules/.bin/flow', function(error, stdout) {
     var lines = stdout.split('\n');
     var fileRegexp = /^src.*\.jsx?\:[\d]*/;
     var sumRegexpErr = /Found [\d]* error/;
     var sumRegexpOk = /No errors/;
     var pointerRegexp = /\^/;
     for (var i = 0; i < lines.length; i++) {
         var line = lines[i];
         if (fileRegexp.test(line)) {
             console.log(chalk.red.underline(line));
         } else if (pointerRegexp.test(line)) {
             var start = line.indexOf('\^');
             var end = line.lastIndexOf('\^');
             console.log(
                 line.slice(0, start) + chalk.yellow(line.slice(start, end + 1)) + line.slice(end + 1)
             );
         } else if (sumRegexpErr.test(line)) {
             console.log(chalk.white.bold.underline('TypeCheck:') + ' ' + chalk.red.bold(line));
         } else if (sumRegexpOk.test(line)) {
             console.log(chalk.white.bold.underline('TypeCheck:') + ' ' + chalk.green.bold(line));
         } else {
             console.log(chalk.white(line));
         }
     }
     if (!noErrors && error) {
         cb(error);
     } else {
         cb();
     }
 });
const error = function(msg, trace) {
    console.error(`${chalk.red.bold('ERROR!')} ${chalk.red(msg)}`);
    if (trace) {
        console.log(trace);
    }
    process.exit(1);
};
    checkCmd: function(cmd, exit) {
        exit = exit !== false;

        var deferred = Q.defer();

        if(this.options['check-' + cmd] === false) {
            deferred.resolve(undefined);
        }

        if(!this.utils.shell.which(cmd)) {
            this.log(chalk.red.bold('(ERROR)') + ' It looks like you do not have ' + cmd + ' installed...');
            if(exit === true) {
                deferred.reject(new Error(cmd + ' is missing'));
                this.utils.shell.exit(1);
            } else {
                deferred.resolve(false);
            }

        } else {
            this.log(chalk.gray(cmd + ' is installed, continuing...\n'));
            deferred.resolve(true);
        }

        return deferred.promise;
    },
Exemple #22
0
 .catch(error => {
     console.log();
     console.log(chalk.red.bold('Template initialization has failed!'));
     console.log(chalk.red(error.message));
     console.log();
     process.exit(1);
 });
Exemple #23
0
 .on('exit', function (err) {
   if (err) {
     this.log.error(chalk.red.bold('Choke... Error: ' + err));
   } else {
     this.emit('nextTask');
   }
 }.bind(this));
    .then(function (template) {
      if (!options.sync && options.fetches && !templateFetchesLeft[name]) {
        console.error('Tried to fetch mention', chalk.red.bold(name), 'too many times.');
        res.send(500);
        return;
      }

      console.log(chalk.dim('At ' + (new Date()).toTimeString()), chalk.blue.bold(name), 'was fetched.');
      res.send(template);

      if (!options.sync && options.fetches) {
        templateFetchesLeft[name] -= 1;

        if (templateFetchesLeft[name] === 0) {
          delete templateFetchesLeft[name];

          if (objectEmpty(templateFetchesLeft)) {
            console.log(chalk.green('Done with all ' + count + ' pings!'), count * options.fetches, 'fetches has been done.', fails ? chalk.red(fails + ' of them failed.') : '');
            server.close();
          }
        }
      }

      if (!templates.length && !options.sync) {
        console.log(chalk.green('Done with all ' + count + ' pings!'), fails ? chalk.red(fails + ' of them failed.') : '');
        server.close();
      }
    })
Exemple #25
0
 it('wraps a long string containing ansi chars', () => {
   const string = `abcde ${chalk.red.bold('red-bold')} 1234456` +
    `${chalk.dim('bcd')} 123ttttttththththththththththththththththththththth` +
    `tetetetetettetetetetetetetete${chalk.underline.bold('stnhsnthsnth')}ssot`;
   expect(wrapAnsiString(string, 10)).toMatchSnapshot();
   expect(stripAnsi(wrapAnsiString(string, 10))).toMatchSnapshot();
 });
exports.verifyConfig = function() {
  if (!GITHUB_DEST_REPO) {
    console.log(chalk.red.bold("Please define GITHUB_DEST_REPO in " +
                               "your environment."));
    process.exit(1);
  }
};
Exemple #27
0
const run = async () => {
  if (process.argv.includes("--version"))
    return console.log(`v${packageJSON.version}`);
  init();

  const solutions = Object.keys(problems);
  const input = await userInput();
  const { PROBLEM_ID } = input;

  if (!PROBLEM_ID) {
    console.log(chalk.yellow("\n⚠️ No Problem ID provided."));
    process.exit(1);
  }

  if (solutions.includes(PROBLEM_ID)) {
    await problems[PROBLEM_ID]({ verbose });
  } else {
    console.log(
      chalk.red.bold(
        "❌ There is no solution for this problem, yet. Feel free to open a pull request to add your own. 🤓"
      )
    );
  }
  process.exit(1);
};
     ` -c .jsdoc-config.json -u docs lib --query 'pkgVersion=${pkg.version}'`, function (code) {
     // output status
     console.log(code ?
         chalk.red.bold('unable to genereate documentation') :
         ` - documentation created at "${TARGET_DIR}"`);
     exit(code);
 });
Exemple #29
0
// display a message in the command line
function log(type = 'message', message, verbose = false) {
    switch (type) {
        case 'app':
            console.log(chalk.bgRgb(230, 20, 20)(`  ${ message }  `));
            break;
        case 'dump':
            if (verbose) {
                console.log(chalk.magenta.bold(`📦 ${ JSON.stringify(message, null, 2) }`));
            }
            break;
        case 'running':
            console.log(chalk.green.bold(`💻 ${ chalk.green(message) }`));
            break;
        case 'title':
            console.log(chalk.blue.bold(`🛠 ${ message }`));
            break;
        case 'verbose':
            if (verbose) {
                console.log(chalk.keyword('orange')(`🕵 ${ message }`));
            }
            break;
        case 'warn':
            console.warn(chalk.red.bold(`🚧 ${ message }`));
            break;
        default:
            console.log(message);
    }
}
Exemple #30
0
	function(req, res) {
		console.log(chalk.red.bold("Debugging-------"))
		console.log(req.params)
		user = req.res.req.user
		console.log(user);
		Token.findOne({
			token_type: 'self',
			user_id: user._id
		}, function(err, token){
			if(err) throw err;

			if(!token){
        //ruh roh we dont have a token
        console.log(chalk.bold.red("Token Not Found"));
        res.json({success: false, message: "Token Not Found"})
      }

      //if we got here we validated the user and got a token for the correct user.
      console.log(chalk.bold.green("User Validated"))
      var t = jwt.sign({token: token.token, user: user._id}, app.get('superSecret'), {
        expiresIn: "24h" // expires in 24 hours
      });

      console.log(chalk.bold.blue("Setting Cookie"));
      res.cookie(config.token_cookie, t, { domain: '.zaphyrr.com' });
      console.log(chalk.bold.blue("Sending token"))
      res.redirect(config.auth.facebook.redirectURL);
		})
		// User.findOne({}, function(err, user){})

	}