<commit_before>const FILE = 'FILE'
const EMAIL = 'test@mailjet.com'
const EMAIL2 = 'test2@mailjet.com'
const NAME = 'name'
const SUBJECT = 'subject'
const TEXT_PART = 'text'
const VAR = {'Key1': 'Value1', 'Key2': 'Value2'}
const SIMPLE_RECIPIENTS = [{email: EMAIL}, {email: EMAIL2}]
const UNIQUE_RECIPIENT = [{email: EMAIL}]
const RECIPIENTS_NAME = [{email: EMAIL, name: NAME}, {email: EMAIL2, name: NAME}]
const RECIPIENTS_VARS = [{email: EMAIL, vars: VAR}]
const API_KEY = process.env.MJ_APIKEY_PUBLIC
const API_SECRET = process.env.MJ_APIKEY_PRIVATE

var Mailjet = require('../mailjet-client')
var chai = require('chai')
var expect = chai.expect
var should = chai.should() // eslint-disable-line no-unused-vars
var Promise = require('bluebird')
var nock = require('nock')

if (typeof API_KEY === 'undefined' || typeof API_SECRET === 'undefined') {
  throw new Error('Mailjet API_KEY and API_SECRET are required, respectively ' + API_KEY + ' and ' + API_SECRET + ' given ')
}

describe('Basic Usage', function () {
  var client = Mailjet.connect(API_KEY, API_SECRET)

  describe('connection', function () {
    it('creates an instance of the client', function () {
      var connectionType1 = new Mailjet(API_KEY, API_SECRET)
      var connectionType2 = new Mailjet().connect(API_KEY, API_SECRET)
      var connectionType3 = Mailjet.connect(API_KEY, API_SECRET)

      expect('' + connectionType1.apiKey + connectionType1.apiSecret).to.equal('' + API_KEY + API_SECRET)
      expect('' + connectionType2.apiKey + connectionType2.apiSecret).to.equal('' + API_KEY + API_SECRET)
      expect('' + connectionType3.apiKey + connectionType3.apiSecret).to.equal('' + API_KEY + API_SECRET)
    })

    it('creates an instance of the client with options', function () {
      var options = {
        proxyUrl: 'http://localhost:3128',
        timeout: 10000
      }

      var connectionType1 = new Mailjet(API_KEY, API_SECRET, options)
      var connectionType2 = new Mailjet().connect(API_KEY, API_SECRET, options)
      var connectionType3 = Mailjet.connect(API_KEY, API_SECRET, options)

      var connections = [connectionType1, connectionType2, connectionType3]
      connections.forEach(function (connection) {
        expect(connection).to.have.property('apiKey', API_KEY)
        expect(connection).to.have.property('apiSecret', API_SECRET)
        expect(connection.options).to.have.property('proxyUrl', options.proxyUrl)
        expect(connection.options).to.have.property('timeout', 10000)
      })
    })
  })

  describe('method request', function () {
    describe('get', function () {
      var contact = client.get('contact')

      it('calls the contact ressource instance whith no parameters', function (done) {
        contact.request()
          .then(function (result) {
            result.body.should.be.a('object')
            expect(result.response.statusCode).to.equal(200)
            done()
          })
          .catch(function (reason) {
            // We want it to raise an error if it gets here
            expect(reason).to.equal(undefined)
            done()
          })
      })

      it('calls the contact ressource instance whith parameters', function (done) {
        var promise = contact.request({Name: 'Guillaume Badi'})
          .then(function (result) {
            result.body.should.be.a('object')
            expect(result.response.statusCode).to.be.within(200, 201)
            done()
          })
          .catch(function (reason) {
            // We want it to raise an error if it gets here
            expect(reason).to.equal(undefined)
            done()
          })
        expect(Promise.prototype.isPrototypeOf(promise)).to.equal(true)
      })

      it('calls the contact ressource instance with empty parameters', function (done) {
        contact.request({}).then(function (result) {
          result.body.should.be.a('object')
          expect(result.response.statusCode).to.be.within(200, 201)
          done()
        })
      })
    })

    describe('post', function () {
      var sender = client.post('sender')
      var deletedErrorMessage = 'There is an already existing deleted sender with the same email. ' +
        'You can use "validate" action in order to activate it.'
      var inactiveErrorMessage = 'There is an already existing inactive sender with the same email. ' +
        'You can use "validate" action in order to activate it.'

      it('calls the sender ressource instance whith no parameters', function (done) {
        sender.request().catch(function (reason) {
          //reason.ErrorMessage.should.equal(deletedErrorMessage)
          reason.statusCode.should.equal(400)
          done()
        })
      })

      it('calls the sender ressource instance whith invalid parameters', function (done) {
        sender.request({Name: 'Guillaume Badi'}).catch(function (reason) {
          //expect(reason.ErrorMessage).to.equal(deletedErrorMessage)
          expect(reason.statusCode).to.equal(400)
          done()
        })
      })

      it('calls the sender ressource instance whith valid parameters', function (done) {
        sender.request({email: 'gbadi@mailjet.com'})
          .then(function (result) {
            expect(result.response.statusCode).to.equal(201)
            done()
          })
          .catch(function (reason) {
            // if it fails because the sender already exist. should be 400
            expect(reason.ErrorMessage).to.equal(inactiveErrorMessage)
            expect(reason.statusCode).to.equal(400)
            done()
          })
      })

      it('calls the sender resource with empty parameters', function (done) {
        sender.request({}).catch(function (reason) {
          // expect(reason.ErrorMessage).to.equal(deletedErrorMessage)
          expect(reason.statusCode).to.equal(400)
          done()
        })
      })
    })
  })
})

describe('Advanced API Calls', function () {
  function Example (fn, payload) {
    this.fn = fn
    this.payload = payload
    this.format = function (obj) { return JSON.stringify(obj).match(/\S+/g).join('') }
    this.call = function () {
      var res = this.fn.request(this.payload)
      var ret = res[0] + ' ' + this.format(res[1])
      return ret
    }
  }

  var client2 = new Mailjet(API_KEY, API_SECRET, null, true)

  const EXAMPLES_SET = [
    new Example(client2.get('contact')),
    new Example(client2.get('contact').id(2)),
    new Example(client2.get('contact/2')),
    new Example(client2.get('contact').id(3).action('getcontactslist')),
    new Example(client2.get('contact'), {countOnly: 1}),
    new Example(client2.get('contact'), {limit: 2}),
    new Example(client2.get('contact'), {offset: 233}),
    new Example(client2.get('contact'), {contatctList: 34}),
    new Example(client2.post('contactslist').id(34).action('managecontact'), {email: EMAIL}),
    new Example(client2.post('contactslist').id(34).action('csvdata'), FILE),
    new Example(client2.get('newsletter'), {filters: {CountOnly: 1}}),
    new Example(client2.get('batchjob').action('csverror')),
    new Example(client2.post('contact'), {email: EMAIL}),
    new Example(client2.post('send'), {'FromName': NAME, 'FromEmail': EMAIL, 'Subject': SUBJECT, 'Text-Part': TEXT_PART, 'Recipients': UNIQUE_RECIPIENT}),
    new Example(client2.post('send'), {'FromName': NAME, 'FromEmail': EMAIL, 'Subject': SUBJECT, 'Text-Part': TEXT_PART, 'Recipients': SIMPLE_RECIPIENTS}),
    new Example(client2.post('send'), {'FromName': NAME, 'FromEmail': EMAIL, 'Subject': SUBJECT, 'Text-Part': TEXT_PART, 'Recipients': RECIPIENTS_NAME}),
    new Example(client2.post('send'), {'FromName': NAME, 'FromEmail': EMAIL, 'Subject': SUBJECT, 'Text-Part': TEXT_PART, 'Recipients': RECIPIENTS_VARS})
  ]

  const EXPECTED_SET = [
    'https://api.mailjet.com/v3/REST/contact {}',
    'https://api.mailjet.com/v3/REST/contact/2 {}',
    'https://api.mailjet.com/v3/REST/contact/2 {}',
    'https://api.mailjet.com/v3/REST/contact/3/getcontactslist {}',
    'https://api.mailjet.com/v3/REST/contact/?countOnly=1 {}',
    'https://api.mailjet.com/v3/REST/contact/?limit=2 {}',
    'https://api.mailjet.com/v3/REST/contact/?offset=233 {}',
    'https://api.mailjet.com/v3/REST/contact/?contatctList=34 {}',
    'https://api.mailjet.com/v3/REST/contactslist/34/managecontact {"email":"test@mailjet.com"}',
    'https://api.mailjet.com/v3/DATA/contactslist/34/csvdata "FILE"',
    'https://api.mailjet.com/v3/REST/newsletter/?CountOnly=1 {}',
    'https://api.mailjet.com/v3/DATA/batchjob/csverror {}',
    'https://api.mailjet.com/v3/REST/contact {"email":"test@mailjet.com"}',
    'https://api.mailjet.com/v3/send {"FromName":"name","FromEmail":"test@mailjet.com","Subject":"subject","Text-Part":"text","Recipients":[{"email":"test@mailjet.com"}]}',
    'https://api.mailjet.com/v3/send {"FromName":"name","FromEmail":"test@mailjet.com","Subject":"subject","Text-Part":"text","Recipients":[{"email":"test@mailjet.com"},{"email":"test2@mailjet.com"}]}',
    'https://api.mailjet.com/v3/send {"FromName":"name","FromEmail":"test@mailjet.com","Subject":"subject","Text-Part":"text","Recipients":[{"email":"test@mailjet.com","name":"name"},{"email":"test2@mailjet.com","name":"name"}]}',
    'https://api.mailjet.com/v3/send {"FromName":"name","FromEmail":"test@mailjet.com","Subject":"subject","Text-Part":"text","Recipients":[{"email":"test@mailjet.com","vars":{"Key1":"Value1","Key2":"Value2"}}]}'
  ]

  EXPECTED_SET.forEach(function (test, index) {
    it('should output: ' + test, function () {
      EXAMPLES_SET[index].call().should.equal(test)
    })
  })
})

/* This fixture needs to run last so that it doesn't interfere with the other tests */
describe('Mocked API calls', function () {
  /* Set a very short timeout */
  var client = Mailjet.connect(API_KEY, API_SECRET, { timeout: 10 })

  describe('method request', function () {
    describe('get', function () {
      var contact = client.get('contact')

      it('calls the contact resource instance and the request times out', function (done) {
        /* Simulate a delayed response */
        nock('https://api.mailjet.com')
          .get('/v3/REST/contact')
          .delayConnection(1000)
          .reply(200, {})

        contact.request({})
          .then(function (result) {
            // We want it to raise an error if it gets here
            expect(result).to.equal(undefined)
            done()
          })
          .catch(function (reason) {
            expect(reason.ErrorMessage).to.equal('timeout of 10ms exceeded')
            expect(reason.statusCode).to.equal(null)
            expect(reason.response).to.equal(null)
            done()
          })
      })
    })
  })
})
<commit_msg>Remove last message comparaisons<commit_after>const FILE = 'FILE'
const EMAIL = 'test@mailjet.com'
const EMAIL2 = 'test2@mailjet.com'
const NAME = 'name'
const SUBJECT = 'subject'
const TEXT_PART = 'text'
const VAR = {'Key1': 'Value1', 'Key2': 'Value2'}
const SIMPLE_RECIPIENTS = [{email: EMAIL}, {email: EMAIL2}]
const UNIQUE_RECIPIENT = [{email: EMAIL}]
const RECIPIENTS_NAME = [{email: EMAIL, name: NAME}, {email: EMAIL2, name: NAME}]
const RECIPIENTS_VARS = [{email: EMAIL, vars: VAR}]
const API_KEY = process.env.MJ_APIKEY_PUBLIC
const API_SECRET = process.env.MJ_APIKEY_PRIVATE

var Mailjet = require('../mailjet-client')
var chai = require('chai')
var expect = chai.expect
var should = chai.should() // eslint-disable-line no-unused-vars
var Promise = require('bluebird')
var nock = require('nock')

if (typeof API_KEY === 'undefined' || typeof API_SECRET === 'undefined') {
  throw new Error('Mailjet API_KEY and API_SECRET are required, respectively ' + API_KEY + ' and ' + API_SECRET + ' given ')
}

describe('Basic Usage', function () {
  var client = Mailjet.connect(API_KEY, API_SECRET)

  describe('connection', function () {
    it('creates an instance of the client', function () {
      var connectionType1 = new Mailjet(API_KEY, API_SECRET)
      var connectionType2 = new Mailjet().connect(API_KEY, API_SECRET)
      var connectionType3 = Mailjet.connect(API_KEY, API_SECRET)

      expect('' + connectionType1.apiKey + connectionType1.apiSecret).to.equal('' + API_KEY + API_SECRET)
      expect('' + connectionType2.apiKey + connectionType2.apiSecret).to.equal('' + API_KEY + API_SECRET)
      expect('' + connectionType3.apiKey + connectionType3.apiSecret).to.equal('' + API_KEY + API_SECRET)
    })

    it('creates an instance of the client with options', function () {
      var options = {
        proxyUrl: 'http://localhost:3128',
        timeout: 10000
      }

      var connectionType1 = new Mailjet(API_KEY, API_SECRET, options)
      var connectionType2 = new Mailjet().connect(API_KEY, API_SECRET, options)
      var connectionType3 = Mailjet.connect(API_KEY, API_SECRET, options)

      var connections = [connectionType1, connectionType2, connectionType3]
      connections.forEach(function (connection) {
        expect(connection).to.have.property('apiKey', API_KEY)
        expect(connection).to.have.property('apiSecret', API_SECRET)
        expect(connection.options).to.have.property('proxyUrl', options.proxyUrl)
        expect(connection.options).to.have.property('timeout', 10000)
      })
    })
  })

  describe('method request', function () {
    describe('get', function () {
      var contact = client.get('contact')

      it('calls the contact ressource instance whith no parameters', function (done) {
        contact.request()
          .then(function (result) {
            result.body.should.be.a('object')
            expect(result.response.statusCode).to.equal(200)
            done()
          })
          .catch(function (reason) {
            // We want it to raise an error if it gets here
            expect(reason).to.equal(undefined)
            done()
          })
      })

      it('calls the contact ressource instance whith parameters', function (done) {
        var promise = contact.request({Name: 'Guillaume Badi'})
          .then(function (result) {
            result.body.should.be.a('object')
            expect(result.response.statusCode).to.be.within(200, 201)
            done()
          })
          .catch(function (reason) {
            // We want it to raise an error if it gets here
            expect(reason).to.equal(undefined)
            done()
          })
        expect(Promise.prototype.isPrototypeOf(promise)).to.equal(true)
      })

      it('calls the contact ressource instance with empty parameters', function (done) {
        contact.request({}).then(function (result) {
          result.body.should.be.a('object')
          expect(result.response.statusCode).to.be.within(200, 201)
          done()
        })
      })
    })

    describe('post', function () {
      var sender = client.post('sender')
      var deletedErrorMessage = 'There is an already existing deleted sender with the same email. ' +
        'You can use "validate" action in order to activate it.'
      var inactiveErrorMessage = 'There is an already existing inactive sender with the same email. ' +
        'You can use "validate" action in order to activate it.'

      it('calls the sender ressource instance whith no parameters', function (done) {
        sender.request().catch(function (reason) {
          //reason.ErrorMessage.should.equal(deletedErrorMessage)
          reason.statusCode.should.equal(400)
          done()
        })
      })

      it('calls the sender ressource instance whith invalid parameters', function (done) {
        sender.request({Name: 'Guillaume Badi'}).catch(function (reason) {
          //expect(reason.ErrorMessage).to.equal(deletedErrorMessage)
          expect(reason.statusCode).to.equal(400)
          done()
        })
      })

      it('calls the sender ressource instance whith valid parameters', function (done) {
        sender.request({email: 'gbadi@mailjet.com'})
          .then(function (result) {
            expect(result.response.statusCode).to.equal(201)
            done()
          })
          .catch(function (reason) {
            // if it fails because the sender already exist. should be 400
            // expect(reason.ErrorMessage).to.equal(inactiveErrorMessage)
            expect(reason.statusCode).to.equal(400)
            done()
          })
      })

      it('calls the sender resource with empty parameters', function (done) {
        sender.request({}).catch(function (reason) {
          // expect(reason.ErrorMessage).to.equal(deletedErrorMessage)
          expect(reason.statusCode).to.equal(400)
          done()
        })
      })
    })
  })
})

describe('Advanced API Calls', function () {
  function Example (fn, payload) {
    this.fn = fn
    this.payload = payload
    this.format = function (obj) { return JSON.stringify(obj).match(/\S+/g).join('') }
    this.call = function () {
      var res = this.fn.request(this.payload)
      var ret = res[0] + ' ' + this.format(res[1])
      return ret
    }
  }

  var client2 = new Mailjet(API_KEY, API_SECRET, null, true)

  const EXAMPLES_SET = [
    new Example(client2.get('contact')),
    new Example(client2.get('contact').id(2)),
    new Example(client2.get('contact/2')),
    new Example(client2.get('contact').id(3).action('getcontactslist')),
    new Example(client2.get('contact'), {countOnly: 1}),
    new Example(client2.get('contact'), {limit: 2}),
    new Example(client2.get('contact'), {offset: 233}),
    new Example(client2.get('contact'), {contatctList: 34}),
    new Example(client2.post('contactslist').id(34).action('managecontact'), {email: EMAIL}),
    new Example(client2.post('contactslist').id(34).action('csvdata'), FILE),
    new Example(client2.get('newsletter'), {filters: {CountOnly: 1}}),
    new Example(client2.get('batchjob').action('csverror')),
    new Example(client2.post('contact'), {email: EMAIL}),
    new Example(client2.post('send'), {'FromName': NAME, 'FromEmail': EMAIL, 'Subject': SUBJECT, 'Text-Part': TEXT_PART, 'Recipients': UNIQUE_RECIPIENT}),
    new Example(client2.post('send'), {'FromName': NAME, 'FromEmail': EMAIL, 'Subject': SUBJECT, 'Text-Part': TEXT_PART, 'Recipients': SIMPLE_RECIPIENTS}),
    new Example(client2.post('send'), {'FromName': NAME, 'FromEmail': EMAIL, 'Subject': SUBJECT, 'Text-Part': TEXT_PART, 'Recipients': RECIPIENTS_NAME}),
    new Example(client2.post('send'), {'FromName': NAME, 'FromEmail': EMAIL, 'Subject': SUBJECT, 'Text-Part': TEXT_PART, 'Recipients': RECIPIENTS_VARS})
  ]

  const EXPECTED_SET = [
    'https://api.mailjet.com/v3/REST/contact {}',
    'https://api.mailjet.com/v3/REST/contact/2 {}',
    'https://api.mailjet.com/v3/REST/contact/2 {}',
    'https://api.mailjet.com/v3/REST/contact/3/getcontactslist {}',
    'https://api.mailjet.com/v3/REST/contact/?countOnly=1 {}',
    'https://api.mailjet.com/v3/REST/contact/?limit=2 {}',
    'https://api.mailjet.com/v3/REST/contact/?offset=233 {}',
    'https://api.mailjet.com/v3/REST/contact/?contatctList=34 {}',
    'https://api.mailjet.com/v3/REST/contactslist/34/managecontact {"email":"test@mailjet.com"}',
    'https://api.mailjet.com/v3/DATA/contactslist/34/csvdata "FILE"',
    'https://api.mailjet.com/v3/REST/newsletter/?CountOnly=1 {}',
    'https://api.mailjet.com/v3/DATA/batchjob/csverror {}',
    'https://api.mailjet.com/v3/REST/contact {"email":"test@mailjet.com"}',
    'https://api.mailjet.com/v3/send {"FromName":"name","FromEmail":"test@mailjet.com","Subject":"subject","Text-Part":"text","Recipients":[{"email":"test@mailjet.com"}]}',
    'https://api.mailjet.com/v3/send {"FromName":"name","FromEmail":"test@mailjet.com","Subject":"subject","Text-Part":"text","Recipients":[{"email":"test@mailjet.com"},{"email":"test2@mailjet.com"}]}',
    'https://api.mailjet.com/v3/send {"FromName":"name","FromEmail":"test@mailjet.com","Subject":"subject","Text-Part":"text","Recipients":[{"email":"test@mailjet.com","name":"name"},{"email":"test2@mailjet.com","name":"name"}]}',
    'https://api.mailjet.com/v3/send {"FromName":"name","FromEmail":"test@mailjet.com","Subject":"subject","Text-Part":"text","Recipients":[{"email":"test@mailjet.com","vars":{"Key1":"Value1","Key2":"Value2"}}]}'
  ]

  EXPECTED_SET.forEach(function (test, index) {
    it('should output: ' + test, function () {
      EXAMPLES_SET[index].call().should.equal(test)
    })
  })
})

/* This fixture needs to run last so that it doesn't interfere with the other tests */
describe('Mocked API calls', function () {
  /* Set a very short timeout */
  var client = Mailjet.connect(API_KEY, API_SECRET, { timeout: 10 })

  describe('method request', function () {
    describe('get', function () {
      var contact = client.get('contact')

      it('calls the contact resource instance and the request times out', function (done) {
        /* Simulate a delayed response */
        nock('https://api.mailjet.com')
          .get('/v3/REST/contact')
          .delayConnection(1000)
          .reply(200, {})

        contact.request({})
          .then(function (result) {
            // We want it to raise an error if it gets here
            expect(result).to.equal(undefined)
            done()
          })
          .catch(function (reason) {
            expect(reason.ErrorMessage).to.equal('timeout of 10ms exceeded')
            expect(reason.statusCode).to.equal(null)
            expect(reason.response).to.equal(null)
            done()
          })
      })
    })
  })
})
<|endoftext|>


<commit_before>/* global $ */
(function () {
    "use strict";
    function updateQueryParameters() {
        let baseURL = window.location.origin + "/embed/" + $("#queryparam_guildid").val();
        let inputs = $("input.queryparam");
        let url = baseURL;
        for (let i = 0; i < inputs.length; i++) {
            let input = $(inputs[i]);
            let name = input.attr("name");
            let value = input.val();
            if (!value) {
                continue;
            }
            if (!url.includes("?")) {
                url += "?";
            } else {
                url += "&";
            }
            url += `${name}=${value}`;
        }
        $("#queryparam_url").val(url);
        $("#queryparam_iframe").val("");
    }

    $(function () {
        $("input.queryparam").change(updateQueryParameters);
        $("#queryparam_guildid").change(updateQueryParameters);
        updateQueryParameters();
    });
})();<commit_msg>Strip off leading query parameter input values to prevent confusion<commit_after>/* global $ */
(function () {
    "use strict";
    function updateQueryParameters() {
        let baseURL = window.location.origin + "/embed/" + $("#queryparam_guildid").val();
        let inputs = $("input.queryparam");
        let url = baseURL;
        for (let i = 0; i < inputs.length; i++) {
            let input = $(inputs[i]);
            let name = input.attr("name");
            let value = input.val().trim();
            if (!value) {
                continue;
            }
            if (!url.includes("?")) {
                url += "?";
            } else {
                url += "&";
            }
            if (value.startsWith(`${name}=`)) {
                value = value.substr(name.length + 1);
            }
            url += `${name}=${value}`;
        }
        $("#queryparam_url").val(url);
        $("#queryparam_iframe").val("");
    }

    $(function () {
        $("input.queryparam").change(updateQueryParameters);
        $("#queryparam_guildid").change(updateQueryParameters);
        updateQueryParameters();
    });
})();<|endoftext|>


<commit_before>import _ from 'lodash';
import { Observable } from 'rx';
import dedent from 'dedent';
// import debugFactory from 'debug';
import { isEmail } from 'validator';
import { check, validationResult } from 'express-validator/check';

import { ifUserRedirectTo } from '../utils/middleware';
import {
  wrapHandledError,
  createValidatorErrorFormatter
} from '../utils/create-handled-error.js';

const isSignUpDisabled = !!process.env.DISABLE_SIGNUP;
// const debug = debugFactory('fcc:boot:auth');

module.exports = function enableAuthentication(app) {
  // enable loopback access control authentication. see:
  //  loopback.io/doc/en/lb2/Authentication-authorization-and-permissions.html
  app.enableAuth();
  const ifUserRedirect = ifUserRedirectTo();
  const router = app.loopback.Router();
  const api = app.loopback.Router();
  const { AuthToken, User } = app.models;

  router.get('/login', (req, res) => res.redirect(301, '/signin'));
  router.get('/logout', (req, res) => res.redirect(301, '/signout'));

  function getEmailSignin(req, res) {
    if (isSignUpDisabled) {
      return res.render('account/beta', {
        title: 'New sign ups are disabled'
      });
    }
    return res.render('account/email-signin', {
      title: 'Sign in to freeCodeCamp using your Email Address'
    });
  }

  router.get('/signup', ifUserRedirect, getEmailSignin);
  router.get('/signin', ifUserRedirect, getEmailSignin);
  router.get('/email-signin', ifUserRedirect, getEmailSignin);

  router.get('/signout', (req, res) => {
    req.logout();
    res.redirect('/');
  });

  router.get(
    '/deprecated-signin',
    ifUserRedirect,
    (req, res) => res.render('account/deprecated-signin', {
      title: 'Sign in to freeCodeCamp using a Deprecated Login'
    })
  );

  const defaultErrorMsg = dedent`
    Oops, something is not right,
    please request a fresh link to sign in / sign up.
  `;

  const passwordlessGetValidators = [
    check('email')
      .isBase64()
      .withMessage('email should be a base64 encoded string'),
    check('token')
      .exists()
      .withMessage('token should exist')
      // based on strongloop/loopback/common/models/access-token.js#L15
      .isLength({ min: 64, max: 64 })
      .withMessage('token is not the right length')
  ];

  function getPasswordlessAuth(req, res, next) {
    const {
      query: {
        email: encodedEmail,
        token: authTokenId
      } = {}
    } = req;
    const validation = validationResult(req)
      .formatWith(createValidatorErrorFormatter('info', '/email-signup'));

    if (!validation.isEmpty()) {
      const errors = validation.array();
      return next(errors.pop());
    }

    const email = User.decodeEmail(encodedEmail);
    if (!isEmail(email)) {
      return next(wrapHandledError(
        new TypeError('decoded email is invalid'),
        {
          type: 'info',
          message: 'The email encoded in the link is incorrectly formatted',
          redirectTo: '/email-sign'
        }
      ));
    }
    // first find
    return AuthToken.findOne$({ where: { id: authTokenId } })
      .flatMap(authToken => {
        if (!authToken) {
          throw wrapHandledError(
            new Error(`no token found for id: ${authTokenId}`),
            {
              type: 'info',
              message: defaultErrorMsg,
              redirectTo: '/email-signin'
            }
          );
        }
        // find user then validate and destroy email validation token
        // finally retun user instance
        return User.findOne$({ where: { id: authToken.userId } })
          .flatMap(user => {
            if (!user) {
              throw wrapHandledError(
                new Error(`no user found for token: ${authTokenId}`),
                {
                  type: 'info',
                  message: defaultErrorMsg,
                  redirectTo: '/email-signin'
                }
              );
            }
            if (user.email !== email) {
              throw wrapHandledError(
                new Error('user email does not match'),
                {
                  type: 'info',
                  message: defaultErrorMsg,
                  redirectTo: '/email-signin'
                }
              );
            }
            return authToken.validate()
              .map(isValid => {
                if (!isValid) {
                  throw wrapHandledError(
                    new Error('token is invalid'),
                    {
                      type: 'info',
                      message: `
                        Looks like the link you clicked has expired,
                        please request a fresh link, to sign in.
                      `,
                      redirectTo: '/email-signin'
                    }
                  );
                }
                return authToken.destroy();
              })
              .map(() => user);
          });
      })
      // at this point token has been validated and destroyed
      // update user and log them in
      .map(user => user.loginByRequest(req, res))
      .do(() => {
        let redirectTo = '/';

        if (
          req.session &&
          req.session.returnTo
        ) {
          redirectTo = req.session.returnTo;
        }

        req.flash('success', { msg:
          'Success! You have signed in to your account. Happy Coding!'
        });

        return res.redirect(redirectTo);
      })
      .subscribe(
        () => {},
        next
      );
  }

  router.get(
    '/passwordless-auth',
    ifUserRedirect,
    passwordlessGetValidators,
    getPasswordlessAuth
  );

  const passwordlessPostValidators = [
    check('email')
      .isEmail()
      .withMessage('email is not a valid email address')
  ];
  function postPasswordlessAuth(req, res, next) {
    const { body: { email } = {} } = req;
    const validation = validationResult(req)
      .formatWith(createValidatorErrorFormatter('info', '/email-signup'));
    if (!validation.isEmpty()) {
      const errors = validation.array();
      return next(errors.pop());
    }

    return User.findOne$({ where: { email } })
      .flatMap(_user => Observable.if(
          // if no user found create new user and save to db
          _.constant(_user),
          Observable.of(_user),
          User.create$({ email })
        )
        .flatMap(user => user.requestAuthEmail(!_user))
      )
      .do(msg => res.status(200).send({ message: msg }))
      .subscribe(_.noop, next);
  }

  api.post(
    '/passwordless-auth',
    ifUserRedirect,
    passwordlessPostValidators,
    postPasswordlessAuth
  );

  app.use('/:lang', router);
  app.use(api);
};
<commit_msg>feat(boot/auth): Add signup disabled debug info<commit_after>import _ from 'lodash';
import { Observable } from 'rx';
import dedent from 'dedent';
// import debugFactory from 'debug';
import { isEmail } from 'validator';
import { check, validationResult } from 'express-validator/check';

import { ifUserRedirectTo } from '../utils/middleware';
import {
  wrapHandledError,
  createValidatorErrorFormatter
} from '../utils/create-handled-error.js';

const isSignUpDisabled = !!process.env.DISABLE_SIGNUP;
// const debug = debugFactory('fcc:boot:auth');
if (isSignUpDisabled) {
  console.log('fcc:boot:auth - Sign up is disabled');
}

module.exports = function enableAuthentication(app) {
  // enable loopback access control authentication. see:
  //  loopback.io/doc/en/lb2/Authentication-authorization-and-permissions.html
  app.enableAuth();
  const ifUserRedirect = ifUserRedirectTo();
  const router = app.loopback.Router();
  const api = app.loopback.Router();
  const { AuthToken, User } = app.models;

  router.get('/login', (req, res) => res.redirect(301, '/signin'));
  router.get('/logout', (req, res) => res.redirect(301, '/signout'));

  function getEmailSignin(req, res) {
    if (isSignUpDisabled) {
      return res.render('account/beta', {
        title: 'New sign ups are disabled'
      });
    }
    return res.render('account/email-signin', {
      title: 'Sign in to freeCodeCamp using your Email Address'
    });
  }

  router.get('/signup', ifUserRedirect, getEmailSignin);
  router.get('/signin', ifUserRedirect, getEmailSignin);
  router.get('/email-signin', ifUserRedirect, getEmailSignin);

  router.get('/signout', (req, res) => {
    req.logout();
    res.redirect('/');
  });

  router.get(
    '/deprecated-signin',
    ifUserRedirect,
    (req, res) => res.render('account/deprecated-signin', {
      title: 'Sign in to freeCodeCamp using a Deprecated Login'
    })
  );

  const defaultErrorMsg = dedent`
    Oops, something is not right,
    please request a fresh link to sign in / sign up.
  `;

  const passwordlessGetValidators = [
    check('email')
      .isBase64()
      .withMessage('email should be a base64 encoded string'),
    check('token')
      .exists()
      .withMessage('token should exist')
      // based on strongloop/loopback/common/models/access-token.js#L15
      .isLength({ min: 64, max: 64 })
      .withMessage('token is not the right length')
  ];

  function getPasswordlessAuth(req, res, next) {
    const {
      query: {
        email: encodedEmail,
        token: authTokenId
      } = {}
    } = req;
    const validation = validationResult(req)
      .formatWith(createValidatorErrorFormatter('info', '/email-signup'));

    if (!validation.isEmpty()) {
      const errors = validation.array();
      return next(errors.pop());
    }

    const email = User.decodeEmail(encodedEmail);
    if (!isEmail(email)) {
      return next(wrapHandledError(
        new TypeError('decoded email is invalid'),
        {
          type: 'info',
          message: 'The email encoded in the link is incorrectly formatted',
          redirectTo: '/email-sign'
        }
      ));
    }
    // first find
    return AuthToken.findOne$({ where: { id: authTokenId } })
      .flatMap(authToken => {
        if (!authToken) {
          throw wrapHandledError(
            new Error(`no token found for id: ${authTokenId}`),
            {
              type: 'info',
              message: defaultErrorMsg,
              redirectTo: '/email-signin'
            }
          );
        }
        // find user then validate and destroy email validation token
        // finally retun user instance
        return User.findOne$({ where: { id: authToken.userId } })
          .flatMap(user => {
            if (!user) {
              throw wrapHandledError(
                new Error(`no user found for token: ${authTokenId}`),
                {
                  type: 'info',
                  message: defaultErrorMsg,
                  redirectTo: '/email-signin'
                }
              );
            }
            if (user.email !== email) {
              throw wrapHandledError(
                new Error('user email does not match'),
                {
                  type: 'info',
                  message: defaultErrorMsg,
                  redirectTo: '/email-signin'
                }
              );
            }
            return authToken.validate()
              .map(isValid => {
                if (!isValid) {
                  throw wrapHandledError(
                    new Error('token is invalid'),
                    {
                      type: 'info',
                      message: `
                        Looks like the link you clicked has expired,
                        please request a fresh link, to sign in.
                      `,
                      redirectTo: '/email-signin'
                    }
                  );
                }
                return authToken.destroy();
              })
              .map(() => user);
          });
      })
      // at this point token has been validated and destroyed
      // update user and log them in
      .map(user => user.loginByRequest(req, res))
      .do(() => {
        let redirectTo = '/';

        if (
          req.session &&
          req.session.returnTo
        ) {
          redirectTo = req.session.returnTo;
        }

        req.flash('success', { msg:
          'Success! You have signed in to your account. Happy Coding!'
        });

        return res.redirect(redirectTo);
      })
      .subscribe(
        () => {},
        next
      );
  }

  router.get(
    '/passwordless-auth',
    ifUserRedirect,
    passwordlessGetValidators,
    getPasswordlessAuth
  );

  const passwordlessPostValidators = [
    check('email')
      .isEmail()
      .withMessage('email is not a valid email address')
  ];
  function postPasswordlessAuth(req, res, next) {
    const { body: { email } = {} } = req;
    const validation = validationResult(req)
      .formatWith(createValidatorErrorFormatter('info', '/email-signup'));
    if (!validation.isEmpty()) {
      const errors = validation.array();
      return next(errors.pop());
    }

    return User.findOne$({ where: { email } })
      .flatMap(_user => Observable.if(
          // if no user found create new user and save to db
          _.constant(_user),
          Observable.of(_user),
          User.create$({ email })
        )
        .flatMap(user => user.requestAuthEmail(!_user))
      )
      .do(msg => res.status(200).send({ message: msg }))
      .subscribe(_.noop, next);
  }

  api.post(
    '/passwordless-auth',
    ifUserRedirect,
    passwordlessPostValidators,
    postPasswordlessAuth
  );

  app.use('/:lang', router);
  app.use(api);
};
<|endoftext|>


<commit_before>/**
 * slush-simbo
 * ===========
 * https://github.com/simbo/slush-simbo
 *
 * Copyright © 2015 Simon Lepel <simbo@simbo.de>
 * Licensed under the MIT license.
 */
'use strict';

// required modules
var _            = require('lodash'),
    autoPlug     = require('auto-plug'),
    chalk        = require('chalk'),
    childProcess = require('child_process'),
    fs           = require('fs'),
    gulp         = require('gulp'),
    ini          = require('ini'),
    inquirer     = require('inquirer'),
    minimist     = require('minimist'),
    path         = require('path'),
    util         = require('util');

// some variables
var cwd = process.cwd(),
    pkgDir = __dirname,
    pkgJson = require(path.join(pkgDir, 'package.json')),
    home = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE,
    templates = path.join(pkgDir, 'templates'),
    savedDataFile = path.join(home, '.' + pkgJson.name),
    savedData = fs.existsSync(savedDataFile) ? ini.parse(fs.readFileSync(savedDataFile, 'utf-8')) : false;

// auto-require plugins
var g = autoPlug({ prefix: 'gulp', config: pkgJson });

// cli params
var params = (function () {
        var cliParams = minimist(process.argv.slice(3)),
            params = {
                silent: cliParams.silent===true || cliParams.s===true || cliParams.S===true || false
            };
        return params;
    })();

// default options
var defaultOptions = (function () {
        var options = {
            authorName: path.basename(home),
            authorEmail: '',
            authorUrl: '',
            authorGithubUser: path.basename(home),
            projectName: path.basename(cwd),
            projectDescription: '',
            projectLicenseType: 'MIT',
            projectVersion: '0.1.0',
            vagrant: false,
            webserver: 'nginx',
            website: 'html',
            php: true,
            database: 'none',
            phpmyadmin: false,
            bower: false,
            travis: true,
            vagrantUp: false,
            install: false
        };
        if (!savedData) {
            var gitconfig = path.join(home, '.gitconfig');
            if (fs.existsSync(gitconfig)) {
                var gitconfigData = ini.parse(fs.readFileSync(gitconfig, 'utf-8'));
                options.authorName = gitconfigData.user.name;
                options.authorEmail = gitconfigData.user.email;
            }
        }
        else {
            options.authorName = savedData.authorName;
            options.authorEmail = savedData.authorEmail;
            options.authorUrl = savedData.authorUrl;
            options.authorGithubUser = savedData.authorGithubUser;
        }
        return options;
    })();

// inquirer questions
var prompts = [{
        name: 'useSavedAuthorData',
        type: 'confirm',
        when: function (answers) {
            return savedData ? true : false;
        },
        message: function (answers) {
            return 'Use this as author data?' +
                chalk.reset.gray('\nName: ') + chalk.yellow(savedData.authorName) +
                chalk.reset.gray('\nE-Mail: ') + chalk.yellow(savedData.authorEmail) +
                chalk.reset.gray('\nURL: ') + chalk.yellow(savedData.authorUrl) +
                chalk.reset.gray('\nGitHub User: ') + chalk.yellow(savedData.authorGithubUser) +
                '\n';
        }
    }, {
        name: 'authorName',
        when: function (answers) {
            return !savedData || !answers.useSavedAuthorData;
        },
        message: 'What is the ' + chalk.yellow('author\'s name') + '?',
        default: defaultOptions.authorName
    }, {
        name: 'authorEmail',
        when: function (answers) {
            return !savedData || !answers.useSavedAuthorData;
        },
        message: 'What is the ' + chalk.yellow('author\'s email') + '?',
        default: defaultOptions.authorEmail
    }, {
        name: 'authorUrl',
        when: function (answers) {
            return !savedData || !answers.useSavedAuthorData;
        },
        message: 'What is the ' + chalk.yellow('author\'s website') + '?',
        default: defaultOptions.authorUrl
    }, {
        name: 'authorGithubUser',
        when: function (answers) {
            return !savedData || !answers.useSavedAuthorData;
        },
        message: 'What is the ' + chalk.yellow('GitHub username') + '?',
        default: defaultOptions.authorGithubUser
    }, {
        name: 'saveAuthorData',
        type: 'confirm',
        when: function (answers) {
            return !savedData || !answers.useSavedAuthorData;
        },
        message: 'Do you want to ' + chalk.yellow('save author information') + ' for future project scaffolding?',
        default: true
    }, {
        name: 'projectName',
        message: 'What is the ' + chalk.yellow('name') + ' of your project?',
        default: defaultOptions.projectName
    }, {
        name: 'projectDescription',
        message: 'What is the ' + chalk.yellow('description') + ' of your project?',
        default: defaultOptions.projectDescription
    }, {
        name: 'projectVersion',
        message: 'What is the ' + chalk.yellow('version') + ' of your project?',
        default: defaultOptions.projectVersion
    }, {
        name: 'projectLicenseType',
        message: 'What ' + chalk.yellow('license') + ' do you want to use for your project?',
        default: defaultOptions.projectLicenseType
    }, {
        name: 'projectLicenseUrl',
        message: 'What is the ' + chalk.yellow('url for license') + ' information?',
        default: function (answers) {
            return getLicenseUrl(answers.projectLicenseType);
        }
    }, {
        name: 'projectRepositoryUrl',
        message: 'What is the url of the project ' + chalk.yellow('repository') + '?',
        default: function (answers) {
            var githubUser = savedData.authorGithubUser || defaultOptions.authorGithubUser || answers.authorGithubUser;
            return githubUser ? getGithubUrl(githubUser, answers.projectName) : '';
        }
    }, {
        name: 'projectBugtrackerUrl',
        message: 'What is the url of the project ' + chalk.yellow('bug tracker') + '?',
        default: function (answers) {
            var githubUser = savedData.authorGithubUser || defaultOptions.authorGithubUser || answers.authorGithubUser;
            return githubUser ? getGithubUrl(githubUser, answers.projectName, 'issues') : '';
        }
    }, {
        name: 'vagrant',
        type: 'confirm',
        message: 'Do you want to use ' + chalk.yellow('Vagrant') + '?',
        default: defaultOptions.vagrant
    }, {
        name: 'webserver',
        type: 'list',
        when: function (answers) {
            return answers.vagrant;
        },
        message: 'What kind of ' + chalk.yellow('webserver') + ' do you want to use?',
        choices: [{
            name: 'nginx',
            value: 'nginx'
        }, {
            name: 'Apache2',
            value: 'apache'
        }, {
            name: 'Connect (node.js)',
            value: 'connect'
        }],
        default: function (answers) {
            return answers.vagrant ? defaultOptions.webserver : 'connect'
        }
    }, {
        name: 'php',
        type: 'confirm',
        when: function (answers) {
            return ['nginx', 'apache'].indexOf(answers.webserver)!==-1;
        },
        message: 'Do want to install ' + chalk.yellow('PHP') + '?',
        default: defaultOptions.php
    }, {
        name: 'database',
        type: 'list',
        when: function (answers) {
            return answers.vagrant;
        },
        message: 'Do want to setup a ' + chalk.yellow('database') + '?',
        choices: [{
            name: 'No',
            value: 'none'
        }, {
            name: 'MySQL',
            value: 'mysql'
        }, {
            name: 'CouchDB',
            value: 'couchdb'
        }],
        default: defaultOptions.database
    }, {
        name: 'phpmyadmin',
        type: 'confirm',
        when: function (answers) {
            return answers.database==='mysql' && answers.php;
        },
        message: 'Do you want to install ' + chalk.yellow('phpMyAdmin') + '?',
        default: function (answers) {
            return answers.database==='mysql' && answers.php ? true : defaultOptions.phpmyadmin;
        }
    }, {
        name: 'website',
        type: 'list',
        message: 'What kind of basic ' + chalk.yellow('website') + ' do you want to setup?',
        choices: [{
            name: 'Single HTML file',
            value: 'html'
        }, {
            name: 'Metalsmith (static site generator)',
            value: 'metalsmith'
        }],
        default: defaultOptions.website
    }, {
        name: 'bower',
        type: 'confirm',
        message: 'Do you want to add ' + chalk.yellow('Bower') + ' support?',
        default: defaultOptions.bower
    }, {
        name: 'travis',
        type: 'confirm',
        message: 'Do you want to add ' + chalk.yellow('Travis CI') + ' support?',
        default: defaultOptions.travis
    }, {
        name: 'vagrantUp',
        type: 'confirm',
        when: function (answers) {
            return answers.vagrant;
        },
        message: 'Do you want to run ' + chalk.yellow('vagrant up') + ' after scaffolding?',
        default: defaultOptions.vagrantUp
    }, {
        name: 'install',
        type: 'confirm',
        when: function (answers) {
            return !answers.vagrant;
        },
        message: function (answers) {
            var bowerMsg = answers.bower ? ' and bower components' : '';
            return 'Do you want to ' + chalk.yellow('install') + ' npm modules' + bowerMsg + ' after scaffolding?';
        },
        default: function (answers) {
            return answers.vagrant ? false : defaultOptions.install;
        }
    }, {
        name: 'continue',
        type: 'confirm',
        message: 'Please check your answers. ' + chalk.yellow('Continue') + '?',
        default: true
    }];

// get url of github repo or repo's issues
function getGithubUrl (user, project, type) {
    var types = {
        repository: '.git',
        issues: '/issues'
    };
    type = Object.keys(types).indexOf(type)===-1 ? 'repository' : type;
    return 'https://github.com/' + user + '/' + project + types[type];
}

// get url for license
function getLicenseUrl (license) {
    switch(license.toLowerCase()) {
        case 'mit':
            return 'http://' + defaultOptions.authorGithubUser + '.mit-license.org/';
        case 'gpl':
        case 'gpl3':
            return 'https://www.gnu.org/licenses/gpl-3.0.txt';
        case 'gpl2':
            return 'https://www.gnu.org/licenses/gpl-2.0.txt';
        default:
            return '';
    }
}

// parse answers, generate options object
function parseAnswers (answers) {
    var options = _.merge({}, answers);
    if (savedData && answers.useSavedAuthorData) {
        options = _.merge(options, savedData);
    }
    options.projectLicenseYear = new Date().getFullYear();
    return options;
}

// combine template sources depending on options
function getTemplateSources (options) {
    var sources = [
            '.editorconfig',
            '.gitignore',
            'GulpConfig.js',
            'Gulpfile.js',
            'LICENSE',
            'package.json',
            'README.md'
        ];
    if (options.vagrant) {
        sources.push(
            'Vagrantfile',
            '.provision/provision.sh',
            '.provision/scripts/functions.sh',
            '.provision/scripts/node.sh'
        );
        if (options.webserver==='apache') {
            sources.push(
                '.provision/scripts/apache.sh',
                '.provision/files/etc/apache2/**/*'
            );
        }
        if (options.webserver==='nginx') {
            sources.push(
                '.provision/scripts/nginx.sh',
                '.provision/files/etc/nginx/nginx.conf',
                '.provision/files/etc/nginx/sites-available/vagrant',
                '.provision/files/etc/nginx/conf.d/deny.conf',
                '.provision/files/etc/nginx/conf.d/expires.conf',
                '.provision/files/etc/nginx/conf.d/favicon.conf',
                '.provision/files/etc/nginx/conf.d/gzip.conf',
                '.provision/files/etc/nginx/conf.d/robots.conf'
            );
            if (options.php) {
                sources.push('.provision/files/etc/nginx/conf.d/php.conf');
            }
            if (options.phpmyadmin) {
                sources.push('.provision/files/etc/nginx/conf.d/phpmyadmin.conf');
            }
        }
        if (options.database==='mysql') {
            sources.push('.provision/scripts/mysql.sh');
        }
        if (options.php) {
            sources.push(
                '.provision/scripts/php.sh',
                '.provision/files/etc/php5/**/*'
            );
        }
        if (options.phpmyadmin) {
            sources.push('.provision/scripts/phpmyadmin.sh');
        }
    }
    if (options.bower) {
        sources.push(
            '.bowerrc',
            'bower.json'
        );
    }
    if (options.travis) {
        sources.push('.travis.yml');
    }
    return sources.map(function (source) {
        return templates + '/' + source;
    });
}

// scaffold the project
function scaffold (options, done) {
    var childProcessOptions = {
        stdio: 'inherit',
        cwd: cwd
    };
    gulp.src(getTemplateSources(options), {
            dot: true,
            base: templates
        })
        .pipe(g.template(options))
        .pipe(g.conflict(cwd + '/'))
        .pipe(gulp.dest(cwd + '/'))
        .on('end', function () {
            if (options.install) {
                childProcess.spawnSync('npm', ['install'], childProcessOptions);
            }
            if (options.vagrantUp) {
                childProcess.spawnSync('vagrant', ['up'], childProcessOptions);
            }
            done();
        });
}

// the actual gulp task
gulp.task('default', function (done) {
    if (params.silent) {
        var options = _.merge({}, defaultOptions);
        options.projectLicenseUrl = getLicenseUrl(defaultOptions.projectLicenseType);
        options.projectRepositoryUrl = getGithubUrl(defaultOptions.authorGithubUser, defaultOptions.projectName);
        options.projectBugtrackerUrl = getGithubUrl(defaultOptions.authorGithubUser, defaultOptions.projectName, 'issues');
        scaffold(parseAnswers(options), done);
    }
    else {
        inquirer.prompt(prompts, function (answers) {
            if (!answers.continue) {
                return done();
            }
            var options = parseAnswers(answers);
            if (answers.saveAuthorData) {
                fs.writeFileSync(savedDataFile, ini.stringify({
                    authorName: options.authorName,
                    authorEmail: options.authorEmail,
                    authorUrl: options.authorUrl,
                    authorGithubUser: options.authorGithubUser,
                }));
            }
            scaffold(options, done);
        });
    }
});
<commit_msg>fix default options handling<commit_after>/**
 * slush-simbo
 * ===========
 * https://github.com/simbo/slush-simbo
 *
 * Copyright © 2015 Simon Lepel <simbo@simbo.de>
 * Licensed under the MIT license.
 */
'use strict';

// required modules
var _            = require('lodash'),
    autoPlug     = require('auto-plug'),
    chalk        = require('chalk'),
    childProcess = require('child_process'),
    fs           = require('fs'),
    gulp         = require('gulp'),
    ini          = require('ini'),
    inquirer     = require('inquirer'),
    minimist     = require('minimist'),
    path         = require('path'),
    util         = require('util');

// some variables
var cwd = process.cwd(),
    pkgDir = __dirname,
    pkgJson = require(path.join(pkgDir, 'package.json')),
    home = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE,
    templates = path.join(pkgDir, 'templates'),
    savedDataFile = path.join(home, '.' + pkgJson.name),
    savedData = fs.existsSync(savedDataFile) ? ini.parse(fs.readFileSync(savedDataFile, 'utf-8')) : false;

// auto-require plugins
var g = autoPlug({ prefix: 'gulp', config: pkgJson });

// cli params
var params = (function () {
        var cliParams = minimist(process.argv.slice(3)),
            params = {
                silent: cliParams.silent===true || cliParams.s===true || cliParams.S===true || false
            };
        return params;
    })();

// default options
var defaultOptions = (function () {
        var options = {
            authorName: path.basename(home),
            authorEmail: '',
            authorUrl: '',
            authorGithubUser: path.basename(home),
            projectName: path.basename(cwd),
            projectDescription: '',
            projectLicenseType: 'MIT',
            projectVersion: '0.1.0',
            vagrant: true,
            webserver: 'connect',
            website: 'html',
            php: true,
            database: 'none',
            phpmyadmin: false,
            bower: false,
            travis: true,
            vagrantUp: false,
            install: false
        };
        if (!savedData) {
            var gitconfig = path.join(home, '.gitconfig');
            if (fs.existsSync(gitconfig)) {
                var gitconfigData = ini.parse(fs.readFileSync(gitconfig, 'utf-8'));
                options.authorName = gitconfigData.user.name;
                options.authorEmail = gitconfigData.user.email;
            }
        }
        else {
            options.authorName = savedData.authorName;
            options.authorEmail = savedData.authorEmail;
            options.authorUrl = savedData.authorUrl;
            options.authorGithubUser = savedData.authorGithubUser;
        }
        return options;
    })();

// inquirer questions
var prompts = [{
        name: 'useSavedAuthorData',
        type: 'confirm',
        when: function (answers) {
            return savedData ? true : false;
        },
        message: function (answers) {
            return 'Use this as author data?' +
                chalk.reset.gray('\nName: ') + chalk.yellow(savedData.authorName) +
                chalk.reset.gray('\nE-Mail: ') + chalk.yellow(savedData.authorEmail) +
                chalk.reset.gray('\nURL: ') + chalk.yellow(savedData.authorUrl) +
                chalk.reset.gray('\nGitHub User: ') + chalk.yellow(savedData.authorGithubUser) +
                '\n';
        }
    }, {
        name: 'authorName',
        when: function (answers) {
            return !savedData || !answers.useSavedAuthorData;
        },
        message: 'What is the ' + chalk.yellow('author\'s name') + '?',
        default: defaultOptions.authorName
    }, {
        name: 'authorEmail',
        when: function (answers) {
            return !savedData || !answers.useSavedAuthorData;
        },
        message: 'What is the ' + chalk.yellow('author\'s email') + '?',
        default: defaultOptions.authorEmail
    }, {
        name: 'authorUrl',
        when: function (answers) {
            return !savedData || !answers.useSavedAuthorData;
        },
        message: 'What is the ' + chalk.yellow('author\'s website') + '?',
        default: defaultOptions.authorUrl
    }, {
        name: 'authorGithubUser',
        when: function (answers) {
            return !savedData || !answers.useSavedAuthorData;
        },
        message: 'What is the ' + chalk.yellow('GitHub username') + '?',
        default: defaultOptions.authorGithubUser
    }, {
        name: 'saveAuthorData',
        type: 'confirm',
        when: function (answers) {
            return !savedData || !answers.useSavedAuthorData;
        },
        message: 'Do you want to ' + chalk.yellow('save author information') + ' for future project scaffolding?',
        default: true
    }, {
        name: 'projectName',
        message: 'What is the ' + chalk.yellow('name') + ' of your project?',
        default: defaultOptions.projectName
    }, {
        name: 'projectDescription',
        message: 'What is the ' + chalk.yellow('description') + ' of your project?',
        default: defaultOptions.projectDescription
    }, {
        name: 'projectVersion',
        message: 'What is the ' + chalk.yellow('version') + ' of your project?',
        default: defaultOptions.projectVersion
    }, {
        name: 'projectLicenseType',
        message: 'What ' + chalk.yellow('license') + ' do you want to use for your project?',
        default: defaultOptions.projectLicenseType
    }, {
        name: 'projectLicenseUrl',
        message: 'What is the ' + chalk.yellow('url for license') + ' information?',
        default: function (answers) {
            return getLicenseUrl(answers.projectLicenseType);
        }
    }, {
        name: 'projectRepositoryUrl',
        message: 'What is the url of the project ' + chalk.yellow('repository') + '?',
        default: function (answers) {
            var githubUser = savedData.authorGithubUser || defaultOptions.authorGithubUser || answers.authorGithubUser;
            return githubUser ? getGithubUrl(githubUser, answers.projectName) : '';
        }
    }, {
        name: 'projectBugtrackerUrl',
        message: 'What is the url of the project ' + chalk.yellow('bug tracker') + '?',
        default: function (answers) {
            var githubUser = savedData.authorGithubUser || defaultOptions.authorGithubUser || answers.authorGithubUser;
            return githubUser ? getGithubUrl(githubUser, answers.projectName, 'issues') : '';
        }
    }, {
        name: 'vagrant',
        type: 'confirm',
        message: 'Do you want to use ' + chalk.yellow('Vagrant') + '?',
        default: defaultOptions.vagrant
    }, {
        name: 'webserver',
        type: 'list',
        when: function (answers) {
            return answers.vagrant;
        },
        message: 'What kind of ' + chalk.yellow('webserver') + ' do you want to use?',
        choices: [{
            name: 'nginx',
            value: 'nginx'
        }, {
            name: 'Apache2',
            value: 'apache'
        }, {
            name: 'Connect (node.js)',
            value: 'connect'
        }],
        default: function (answers) {
            return answers.vagrant ? 'nginx' : defaultOptions.webserver
        }
    }, {
        name: 'php',
        type: 'confirm',
        when: function (answers) {
            return ['nginx', 'apache'].indexOf(answers.webserver)!==-1;
        },
        message: 'Do want to install ' + chalk.yellow('PHP') + '?',
        default: defaultOptions.php
    }, {
        name: 'database',
        type: 'list',
        when: function (answers) {
            return answers.vagrant;
        },
        message: 'Do want to setup a ' + chalk.yellow('database') + '?',
        choices: [{
            name: 'No',
            value: 'none'
        }, {
            name: 'MySQL',
            value: 'mysql'
        }, {
            name: 'CouchDB',
            value: 'couchdb'
        }],
        default: defaultOptions.database
    }, {
        name: 'phpmyadmin',
        type: 'confirm',
        when: function (answers) {
            return answers.database==='mysql' && answers.php;
        },
        message: 'Do you want to install ' + chalk.yellow('phpMyAdmin') + '?',
        default: function (answers) {
            return answers.database==='mysql' && answers.php ? true : defaultOptions.phpmyadmin;
        }
    }, {
        name: 'website',
        type: 'list',
        message: 'What kind of basic ' + chalk.yellow('website') + ' do you want to setup?',
        choices: [{
            name: 'Single HTML file',
            value: 'html'
        }, {
            name: 'Metalsmith (static site generator)',
            value: 'metalsmith'
        }],
        default: defaultOptions.website
    }, {
        name: 'bower',
        type: 'confirm',
        message: 'Do you want to add ' + chalk.yellow('Bower') + ' support?',
        default: defaultOptions.bower
    }, {
        name: 'travis',
        type: 'confirm',
        message: 'Do you want to add ' + chalk.yellow('Travis CI') + ' support?',
        default: defaultOptions.travis
    }, {
        name: 'vagrantUp',
        type: 'confirm',
        when: function (answers) {
            return answers.vagrant;
        },
        message: 'Do you want to run ' + chalk.yellow('vagrant up') + ' after scaffolding?',
        default: defaultOptions.vagrantUp
    }, {
        name: 'install',
        type: 'confirm',
        when: function (answers) {
            return !answers.vagrant;
        },
        message: function (answers) {
            var bowerMsg = answers.bower ? ' and bower components' : '';
            return 'Do you want to ' + chalk.yellow('install') + ' npm modules' + bowerMsg + ' after scaffolding?';
        },
        default: function (answers) {
            return answers.vagrant ? false : defaultOptions.install;
        }
    }, {
        name: 'continue',
        type: 'confirm',
        message: 'Please check your answers. ' + chalk.yellow('Continue') + '?',
        default: true
    }];

// get url of github repo or repo's issues
function getGithubUrl (user, project, type) {
    var types = {
        repository: '.git',
        issues: '/issues'
    };
    type = Object.keys(types).indexOf(type)===-1 ? 'repository' : type;
    return 'https://github.com/' + user + '/' + project + types[type];
}

// get url for license
function getLicenseUrl (license) {
    switch(license.toLowerCase()) {
        case 'mit':
            return 'http://' + defaultOptions.authorGithubUser + '.mit-license.org/';
        case 'gpl':
        case 'gpl3':
            return 'https://www.gnu.org/licenses/gpl-3.0.txt';
        case 'gpl2':
            return 'https://www.gnu.org/licenses/gpl-2.0.txt';
        default:
            return '';
    }
}

// parse answers, generate options object
function parseAnswers (answers) {
    var options = _.merge({}, defaultOptions, answers || {});
    if (savedData && answers.useSavedAuthorData) {
        options = _.merge(options, savedData);
    }
    options.projectLicenseYear = new Date().getFullYear();
    return options;
}

// combine template sources depending on options
function getTemplateSources (options) {
    var sources = [
            '.editorconfig',
            '.gitignore',
            'GulpConfig.js',
            'Gulpfile.js',
            'LICENSE',
            'package.json',
            'README.md'
        ];
    if (options.vagrant) {
        sources.push(
            'Vagrantfile',
            '.provision/provision.sh',
            '.provision/scripts/functions.sh',
            '.provision/scripts/node.sh'
        );
        if (options.webserver==='apache') {
            sources.push(
                '.provision/scripts/apache.sh',
                '.provision/files/etc/apache2/**/*'
            );
        }
        if (options.webserver==='nginx') {
            sources.push(
                '.provision/scripts/nginx.sh',
                '.provision/files/etc/nginx/nginx.conf',
                '.provision/files/etc/nginx/sites-available/vagrant',
                '.provision/files/etc/nginx/conf.d/deny.conf',
                '.provision/files/etc/nginx/conf.d/expires.conf',
                '.provision/files/etc/nginx/conf.d/favicon.conf',
                '.provision/files/etc/nginx/conf.d/gzip.conf',
                '.provision/files/etc/nginx/conf.d/robots.conf'
            );
            if (options.php) {
                sources.push('.provision/files/etc/nginx/conf.d/php.conf');
            }
            if (options.phpmyadmin) {
                sources.push('.provision/files/etc/nginx/conf.d/phpmyadmin.conf');
            }
        }
        if (options.database==='mysql') {
            sources.push('.provision/scripts/mysql.sh');
        }
        if (options.php) {
            sources.push(
                '.provision/scripts/php.sh',
                '.provision/files/etc/php5/**/*'
            );
        }
        if (options.phpmyadmin) {
            sources.push('.provision/scripts/phpmyadmin.sh');
        }
    }
    if (options.bower) {
        sources.push(
            '.bowerrc',
            'bower.json'
        );
    }
    if (options.travis) {
        sources.push('.travis.yml');
    }
    return sources.map(function (source) {
        return templates + '/' + source;
    });
}

// scaffold the project
function scaffold (options, done) {
    var childProcessOptions = {
        stdio: 'inherit',
        cwd: cwd
    };
    gulp.src(getTemplateSources(options), {
            dot: true,
            base: templates
        })
        .pipe(g.template(options))
        .pipe(g.conflict(cwd + '/'))
        .pipe(gulp.dest(cwd + '/'))
        .on('end', function () {
            if (options.install) {
                childProcess.spawnSync('npm', ['install'], childProcessOptions);
            }
            if (options.vagrantUp) {
                childProcess.spawnSync('vagrant', ['up'], childProcessOptions);
            }
            done();
        });
}

// the actual gulp task
gulp.task('default', function (done) {
    if (params.silent) {
        var options = parseAnswers();
        options.projectLicenseUrl = getLicenseUrl(defaultOptions.projectLicenseType);
        options.projectRepositoryUrl = getGithubUrl(defaultOptions.authorGithubUser, defaultOptions.projectName);
        options.projectBugtrackerUrl = getGithubUrl(defaultOptions.authorGithubUser, defaultOptions.projectName, 'issues');
        scaffold(options, done);
    }
    else {
        inquirer.prompt(prompts, function (answers) {
            if (!answers.continue) {
                return done();
            }
            var options = parseAnswers(answers);
            if (answers.saveAuthorData) {
                fs.writeFileSync(savedDataFile, ini.stringify({
                    authorName: options.authorName,
                    authorEmail: options.authorEmail,
                    authorUrl: options.authorUrl,
                    authorGithubUser: options.authorGithubUser,
                }));
            }
            scaffold(options, done);
        });
    }
});
<|endoftext|>


<commit_before>/**
 * @author       Richard Davey <rich@photonstorm.com>
 * @copyright    2020 Photon Storm Ltd.
 * @license      {@link https://opensource.org/licenses/MIT|MIT License}
 */

var Utils = require('../../renderer/webgl/Utils');

/**
 * Renders this Game Object with the WebGL Renderer to the given Camera.
 * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera.
 * This method should not be called directly. It is a utility function of the Render module.
 *
 * @method Phaser.Tilemaps.DynamicTilemapLayer#renderWebGL
 * @since 3.0.0
 * @private
 *
 * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer.
 * @param {Phaser.Tilemaps.DynamicTilemapLayer} src - The Game Object being rendered in this call.
 * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object.
 */
var DynamicTilemapLayerWebGLRenderer = function (renderer, src, camera)
{
    src.cull(camera);

    var renderTiles = src.culledTiles;
    var tileCount = renderTiles.length;
    var alpha = camera.alpha * src.alpha;

    if (tileCount === 0 || alpha <= 0)
    {
        return;
    }

    var gidMap = src.gidMap;
    var pipeline = renderer.pipelines.set(src.pipeline);

    var getTint = Utils.getTintAppendFloatAlpha;

    var scrollFactorX = src.scrollFactorX;
    var scrollFactorY = src.scrollFactorY;

    var x = src.x;
    var y = src.y;

    var sx = src.scaleX;
    var sy = src.scaleY;

    var tilesets = src.tileset;

    //  Loop through each tileset in this layer, drawing just the tiles that are in that set each time
    //  Doing it this way around allows us to batch tiles using the same tileset
    for (var c = 0; c < tilesets.length; c++)
    {
        var currentSet = tilesets[c];
        var texture = currentSet.glTexture;
        var textureUnit = pipeline.setTexture2D(texture, src);

        for (var i = 0; i < tileCount; i++)
        {
            var tile = renderTiles[i];

            var tileset = gidMap[tile.index];

            if (tileset !== currentSet)
            {
                //  Skip tiles that aren't in this set
                continue;
            }

            var tileTexCoords = tileset.getTileTextureCoordinates(tile.index);

            if (tileTexCoords === null)
            {
                continue;
            }

            var frameWidth = tileset.tileWidth;
            var frameHeight = tile.tileHeight;

            var frameX = tileTexCoords.x;
            var frameY = tileTexCoords.y;

            var tw = tileset.tileWidth * 0.5;
            var th = tileset.tileHeight * 0.5;

            var tint = getTint(tile.tint, alpha * tile.alpha);

            pipeline.batchTexture(
                src,
                texture,
                texture.width, texture.height,
                x + ((tw + tile.pixelX) * sx), y + ((th + tile.pixelY) * sy),
                tile.width, tile.height,
                sx, sy,
                tile.rotation,
                tile.flipX, tile.flipY,
                scrollFactorX, scrollFactorY,
                tw, th,
                frameX, frameY, frameWidth, frameHeight,
                tint, tint, tint, tint, false,
                0, 0,
                camera,
                null,
                true,
                textureUnit
            );
        }
    }
};

module.exports = DynamicTilemapLayerWebGLRenderer;
<commit_msg>fixed dynamic layer<commit_after>/**
 * @author       Richard Davey <rich@photonstorm.com>
 * @copyright    2020 Photon Storm Ltd.
 * @license      {@link https://opensource.org/licenses/MIT|MIT License}
 */

var Utils = require('../../renderer/webgl/Utils');

/**
 * Renders this Game Object with the WebGL Renderer to the given Camera.
 * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera.
 * This method should not be called directly. It is a utility function of the Render module.
 *
 * @method Phaser.Tilemaps.DynamicTilemapLayer#renderWebGL
 * @since 3.0.0
 * @private
 *
 * @param {Phaser.Renderer.WebGL.WebGLRenderer} renderer - A reference to the current active WebGL renderer.
 * @param {Phaser.Tilemaps.DynamicTilemapLayer} src - The Game Object being rendered in this call.
 * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object.
 */
var DynamicTilemapLayerWebGLRenderer = function (renderer, src, camera)
{
    src.cull(camera);

    var renderTiles = src.culledTiles;
    var tileCount = renderTiles.length;
    var alpha = camera.alpha * src.alpha;

    if (tileCount === 0 || alpha <= 0)
    {
        return;
    }

    var gidMap = src.gidMap;
    var pipeline = renderer.pipelines.set(src.pipeline);

    var getTint = Utils.getTintAppendFloatAlpha;

    var scrollFactorX = src.scrollFactorX;
    var scrollFactorY = src.scrollFactorY;

    var x = src.x;
    var y = src.y;

    var sx = src.scaleX;
    var sy = src.scaleY;

    var tilesets = src.tileset;

    //  Loop through each tileset in this layer, drawing just the tiles that are in that set each time
    //  Doing it this way around allows us to batch tiles using the same tileset
    for (var c = 0; c < tilesets.length; c++)
    {
        var currentSet = tilesets[c];
        var texture = currentSet.glTexture;
        var textureUnit = pipeline.setTexture2D(texture, src);

        for (var i = 0; i < tileCount; i++)
        {
            var tile = renderTiles[i];

            var tileset = gidMap[tile.index];

            if (tileset !== currentSet)
            {
                //  Skip tiles that aren't in this set
                continue;
            }

            var tileTexCoords = tileset.getTileTextureCoordinates(tile.index);

            if (tileTexCoords === null)
            {
                continue;
            }

            var frameWidth = tileset.tileWidth;
            var frameHeight = tileset.tileHeight;

            var frameX = tileTexCoords.x;
            var frameY = tileTexCoords.y;

            var tw = tileset.tileWidth * 0.5;
            var th = tileset.tileHeight * 0.5;

            var tint = getTint(tile.tint, alpha * tile.alpha);

            pipeline.batchTexture(
                src,
                texture,
                texture.width, texture.height,
                x + ((tw + tile.pixelX) * sx), y + ((th + tile.pixelY) * sy),
                tile.width, tile.height,
                sx, sy,
                tile.rotation,
                tile.flipX, tile.flipY,
                scrollFactorX, scrollFactorY,
                tw, th,
                frameX, frameY, frameWidth, frameHeight,
                tint, tint, tint, tint, false,
                0, 0,
                camera,
                null,
                true,
                textureUnit
            );
        }
    }
};

module.exports = DynamicTilemapLayerWebGLRenderer;
<|endoftext|>


<commit_before>( function() {
	'use strict';

	const Command = require( '../Command' ),
		Text = require( '../Text' );

	class Picture extends Command {
		/**
		 * Returns a buffer containing the image.
		 *
		 * @returns {Buffer}
		 * @memberOf Picture
		 */
		getPicture() {
			var input = this._getImageText(),
				inputLen = input.length,
				buffer = Buffer.alloc( inputLen / 2 );

			for ( var i = 0; i < inputLen; i += 2 ) {
				buffer.writeUInt8(
					parseInt( input.substr( i, 2 ), 16 ),
					i ? ( i / 2 ) : 0
				);
			}

			return buffer;
		}

		/**
		 * @returns {String} Mime type of the image, e.g. `image/png`.
		 * @memberOf Picture
		 */
		getType() {
			let blip = this.getParent().getChild( child => child instanceof Command && child.name.endsWith( 'blip' ) );

			if ( blip ) {
				return 'image/' + blip.name.replace( 'blip', '' );
			}

			return 'image/bmp';
		}

		_getImageText() {
			return this.getParent().getChild( Text ).value;
		}
	}

	module.exports = Picture;
} )();
<commit_msg>Added a browser-friendly method to get picture as a string.<commit_after>( function() {
	'use strict';

	const Command = require( '../Command' ),
		Text = require( '../Text' );

	class Picture extends Command {
		/**
		 * Returns a buffer containing the image.
		 *
		 * @returns {Buffer}
		 * @memberOf Picture
		 */
		getPicture() {
			var input = this._getImageText(),
				inputLen = input.length,
				buffer = Buffer.alloc( inputLen / 2 );

			for ( var i = 0; i < inputLen; i += 2 ) {
				buffer.writeUInt8(
					parseInt( input.substr( i, 2 ), 16 ),
					i ? ( i / 2 ) : 0
				);
			}

			return buffer;
		}

		/**
		 * Browser-friendly version of {@link #getPicture}.
		 *
		 * @returns {String} Returns picture data as a string.
		 * @memberOf Picture
		 */
		getPictureAsString() {
			var input = this._getImageText(),
				inputLen = input.length,
				ret = '',
				i;

			for ( i = 0; i < inputLen; i += 2 ) {
				ret += String.fromCharCode( parseInt( input.substr( i, 2 ), 16 ) );
			}
			return ret;
		}

		/**
		 * @returns {String} Mime type of the image, e.g. `image/png`.
		 * @memberOf Picture
		 */
		getType() {
			let blip = this.getParent().getChild( child => child instanceof Command && child.name.endsWith( 'blip' ) );

			if ( blip ) {
				return 'image/' + blip.name.replace( 'blip', '' );
			}

			return 'image/bmp';
		}

		_getImageText() {
			return this.getParent().getChild( Text ).value;
		}
	}

	module.exports = Picture;
} )();
<|endoftext|>


<commit_before>/**
 * Created by yangyang on 2017/11/5.
 */
import React from 'react'
import {connect} from 'react-redux'
import {withRouter} from 'react-router-dom'
import {
  Button,
  Table,
  Row,
} from 'antd'
import moment from "moment"
import style from './order.module.scss'
import WithdrawApplySearchForm from './WithdrawApplySearchForm'
import {actions, DealType, WITHDRAW_STATUS, WITHDRAW_APPLY_TYPE} from './redux'

class WithdrawApply extends React.PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      loading: false,
      searchParams: {},
    }
  }

  updateSearchParams = (params, total) => {
    const pager = { ...this.state.pagination }
    pager.total = total
    this.setState({searchParams: params, pagination: pager})
  }

  onSearchStart = () => {
    this.setState({loading: true})
  }

  onSearchEnd = () => {
    this.setState({loading: false})
  }

  render() {
    const {pagination, loading, searchParams} = this.state
    let columns = [
      { title: '申请编号', dataIndex: 'id', key: 'id', colSpan: 0,},
      { title: '申请人', dataIndex: 'nickname', key: 'nickname' },
      { title: '手机号码', dataIndex: 'mobilePhoneNumber', key: 'mobilePhoneNumber' },
      { title: '申请日期', dataIndex: 'applyDate', key: 'applyDate', render: (applyDate) => ({moment(new Date(applyDate)).format('LLLL')}) },
      { title: '金额（元）', dataIndex: 'amount', key: 'amount', render: (amount) => ({'¥ ' + Number(amount).toLocaleString()})},
      { title: '申请类别', dataIndex: 'applyType', key: 'applyType', render: (applyType) => ({'¥ ' + applyType}) },
      { title: '状态', dataIndex: 'status', key: 'status', render: (status) => ({'¥ ' + status}) },
      { title: '操作', key: 'action'}
    ]
    if (Number(searchParams.status) === WITHDRAW_STATUS.DONE) {
      columns.pop()
    }
    return (

        <Row>
          <WithdrawApplySearchForm updateSearchParams={this.updateSearchParams}
                              onSearchStart={this.onSearchStart}
                              onSearchEnd={this.onSearchEnd} />
        </Row>

    )
  }
}

const mapStateToProps = (appState, ownProps) => {
  return {
  }
}

const mapDispatchToProps = {
}

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(WithdrawApply))
<commit_msg>modify withdraw apply page<commit_after>/**
 * Created by yangyang on 2017/11/5.
 */
import React from 'react'
import {connect} from 'react-redux'
import {withRouter} from 'react-router-dom'
import {
  Button,
  Table,
  Row,
} from 'antd'
import moment from "moment"
import style from './order.module.scss'
import WithdrawApplySearchForm from './WithdrawApplySearchForm'
import {actions, DealType, WITHDRAW_STATUS, WITHDRAW_APPLY_TYPE} from './redux'

class WithdrawApply extends React.PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      loading: false,
      searchParams: {},
    }
  }

  updateSearchParams = (params, total) => {
    const pager = { ...this.state.pagination }
    pager.total = total
    this.setState({searchParams: params, pagination: pager})
  }

  onSearchStart = () => {
    this.setState({loading: true})
  }

  onSearchEnd = () => {
    this.setState({loading: false})
  }

  render() {
    const {pagination, loading, searchParams} = this.state
    let columns = [
      { title: '申请编号', dataIndex: 'id', key: 'id', colSpan: 0,},
      { title: '申请人', dataIndex: 'nickname', key: 'nickname' },
      { title: '手机号码', dataIndex: 'mobilePhoneNumber', key: 'mobilePhoneNumber' },
      { title: '申请日期', dataIndex: 'applyDate', key: 'applyDate', render: (applyDate) => ({moment(new Date(applyDate)).format('LLLL')}) },
      { title: '金额（元）', dataIndex: 'amount', key: 'amount', render: (amount) => ({'¥ ' + Number(amount).toLocaleString()})},
      { title: '申请类别', dataIndex: 'applyType', key: 'applyType', render: (applyType) => ({'¥ ' + applyType}) },
      { title: '状态', dataIndex: 'status', key: 'status', render: (status) => ({'¥ ' + status}) },
      { title: '操作', key: 'action'}
    ]
    if (Number(searchParams.status) === WITHDRAW_STATUS.DONE) {
      columns.pop()
      columns.push({ title: '操作员', dataIndex: 'operator', key: 'operator' })
      columns.push({ title: '操作时间', dataIndex: 'operateDate', key: 'operateDate', render: (operateDate) => ({moment(new Date(operateDate)).format('LLLL')}) })
    }
    return (

        <Row>
          <WithdrawApplySearchForm updateSearchParams={this.updateSearchParams}
                              onSearchStart={this.onSearchStart}
                              onSearchEnd={this.onSearchEnd} />
        </Row>

    )
  }
}

const mapStateToProps = (appState, ownProps) => {
  return {
  }
}

const mapDispatchToProps = {
}

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(WithdrawApply))
<|endoftext|>


<commit_before>var keys = require('./keys.js');
var Article = require('./models/articleModel.js');
var Keyword = require('./models/keywordModel.js');
var Source = require('./models/sourceModel.js');
var bluebird = require('bluebird');

var fetchData = function (req, res){
  var startDate = req.query.startDate || 00000000;
  var endDate = req.query.endDate || new Date();
  var timePeriod = req.query.timePeriod;

  var keywordId = function(){
    return new Keyword({'word': 'Jeb Bush'})
    .fetch();
  };

  var sourceId = function(){
    return new Source({'name': 'newyorktimes'})
    .fetch();
  };

  bluebird.join(keywordId(), sourceId())
    .then(function(array){
      console.log('our promises are back: ', array[0].get('id'), 'whats this?', array[1].get('id'));
      return new Article()
        .query('where', 'published', '>', startDate )
        .query('where', 'published', '<', endDate )
        .query('where', 'word', '=', array[0].get('id') )
        .query('where', 'source', '=', array[1].get('id') )
        .fetchAll()
    })
    .then(function(articles) {
      res.send(articles.toJSON());
    }).catch(function(error) {
      console.log(error);
      res.send('An error occured, please ensure that you request a keyword and source.');
    });
}

module.exports = fetchData;

// var fetchID = function (table, value){
//   //TODO refactor with lookup to keyword/source tables
//   if (table = 'keywords'){
//     new Keywords({word: 'BP'})
//   }

  // if (table === 'keywords' && value === 'BP'){
  //     return 1;
  // } else if (table === 'sources' && value === 'newyorktimes'){
  //     return 1;
  // }
// };

  // if (timePeriod) {
  //     res.send('We\'ll get to this');
  //     //TODO refactor out
  //     // newyorktimesew Article()
  //     //     .query('count')
  //     //     .query('where', 'published', '>', startDate )
  //     //     .query('where', 'published', '<', endDate )
  //     //     .fetchAll()
  //     //     .then(function(frequencies) {
  //     //         res.send(frequencies.toJSON());
  //     //     }).catch(function(error) {
  //     //         console.log(error);
  //     //         res.send('An error occured');
  //     //     });
  // } else {
  // }
<commit_msg>(feat) Correctly handles keyword/source queries to /data GET<commit_after>var keys = require('./keys.js');
var Article = require('./models/articleModel.js');
var Keyword = require('./models/keywordModel.js');
var Source = require('./models/sourceModel.js');
var bluebird = require('bluebird');

var fetchData = function (req, res){

  //Parse url queries for us in table lookup
  var startDate = req.query.startDate || 00000000;
  var endDate = req.query.endDate || new Date();
  var keyword = req.query.keyword;
  var source = req.query.source;
  var timePeriod = req.query.timePeriod;

  // Both keywordId and sourceId return promises
  var keywordId = function(){
    return new Keyword({'word': keyword})
    .fetch();
  };

  var sourceId = function(){
    return new Source({'name': source})
    .fetch();
  };

  // bluebird is used to resolve promises retured by keywordId and sourceId
  bluebird.join(keywordId(), sourceId())
    .then(function(array){
      return new Article()
        .query('where', 'published', '>', startDate )
        .query('where', 'published', '<', endDate )
        .query('where', 'word', '=', array[0].get('id') )
        .query('where', 'source', '=', array[1].get('id') )
        .fetchAll()
    })
    .then(function(articles) {
      res.send(articles.toJSON());
    }).catch(function(error) {
      console.log(error);
      res.send('An error occured, please ensure that you request a keyword and source.');
    });
};

module.exports = fetchData;

// var fetchID = function (table, value){
//   //TODO refactor with lookup to keyword/source tables
//   if (table = 'keywords'){
//     new Keywords({word: 'BP'})
//   }

  // if (table === 'keywords' && value === 'BP'){
  //     return 1;
  // } else if (table === 'sources' && value === 'newyorktimes'){
  //     return 1;
  // }
// };

  // if (timePeriod) {
  //     res.send('We\'ll get to this');
  //     //TODO refactor out
  //     // newyorktimesew Article()
  //     //     .query('count')
  //     //     .query('where', 'published', '>', startDate )
  //     //     .query('where', 'published', '<', endDate )
  //     //     .fetchAll()
  //     //     .then(function(frequencies) {
  //     //         res.send(frequencies.toJSON());
  //     //     }).catch(function(error) {
  //     //         console.log(error);
  //     //         res.send('An error occured');
  //     //     });
  // } else {
  // }
<|endoftext|>


<commit_before>(function() {
  'use strict';
  // require the module jsonwebtoken
  var env = process.env.NODE_ENV || 'development',
    config = require('../config')[env],
    jsonwebtoken = require('jsonwebtoken'),
    secretKey = config.secretKey;

  module.exports = {
    // function checks for the token
    authenticate: function(req, res, next) {
      console.log('Somebody just came to our app!');
      var token = req.body.token || req.params.token ||
        req.headers['x-access-token'];
      // check if token exists
      if (token) {
        jsonwebtoken.verify(token, secretKey, function(err, decoded) {
          if (err) {
            res.status(403).send({
              success: false,
              message: 'Failed to authenticate user'
            });
          } else {
            req.decoded = decoded;
            next();
          }
        });
      } else {
        res.status(403).send({
          success: false,
          message: 'No token provided!'
        });
      }
    }
  };
})();
<commit_msg>[#111131880] Refactors req decoded access for Heroku<commit_after>(function() {
  'use strict';
  // require the module jsonwebtoken
  var env = process.env.NODE_ENV || 'development',
    config = require('../config')[env],
    jsonwebtoken = require('jsonwebtoken'),
    secretKey = config.secretKey;

  module.exports = {
    // function checks for the token
    authenticate: function(req, res, next) {
      console.log('Somebody just came to our app!');
      var token = req.body.token || req.params.token ||
        req.headers['x-access-token'];
      // check if token exists
      if (token) {
        jsonwebtoken.verify(token, secretKey, function(err, decoded) {
          if (err) {
            res.status(403).send({
              success: false,
              message: 'Failed to authenticate user'
            });
          } else {
            if (decoded._doc) {
              req.decoded = decoded._doc;
            } else {
              req.decoded = decoded;
            }
            next();
          }
        });
      } else {
        res.status(403).send({
          success: false,
          message: 'No token provided!'
        });
      }
    }
  };
})();
<|endoftext|>


<commit_before>/**
 * Created by MiKoRiza-OnE on 3/13/2016.
 */

deepmikoto.UtilityFunctions = Marionette.extend({
    constructor: function ()
    {
        //this.enableSwipeUpAndDownSupport();
    },
    detectSwipe: function ( DOMElement, callback )
    {
        var touchsurface = DOMElement,
            swipedir,
            startX,
            startY,
            distX,
            distY,
            threshold = 150, //required min distance traveled to be considered swipe
            restraint = 100, // maximum distance allowed at the same time in perpendicular direction
            allowedTime = 300, // maximum time allowed to travel that distance
            elapsedTime,
            startTime
        ;

        touchsurface.addEventListener('touchstart', function(e){
            e.preventDefault();
            var touchobj = e.changedTouches[0];
            swipedir = 'none';
            startX = touchobj.pageX;
            startY = touchobj.pageY;
            startTime = new Date().getTime(); // record time when finger first makes contact with surface

        }, false);

        touchsurface.addEventListener('touchmove', function(e){
            e.preventDefault(); // prevent scrolling when inside DIV
        }, false);

        touchsurface.addEventListener('touchend', function(e){
            e.preventDefault();
            var touchobj = e.changedTouches[0];
            distX = touchobj.pageX - startX; // get horizontal dist traveled by finger while in contact with surface
            distY = touchobj.pageY - startY; // get vertical dist traveled by finger while in contact with surface
            elapsedTime = new Date().getTime() - startTime; // get time elapsed
            if (elapsedTime <= allowedTime){ // first condition for awipe met
                if (Math.abs(distX) >= threshold && Math.abs(distY) <= restraint){ // 2nd condition for horizontal swipe met
                    swipedir = (distX < 0)? 'left' : 'right'; // if dist traveled is negative, it indicates left swipe
                }
                else if (Math.abs(distY) >= threshold && Math.abs(distX) <= restraint){ // 2nd condition for vertical swipe met
                    swipedir = (distY < 0)? 'up' : 'down'; // if dist traveled is negative, it indicates up swipe
                }
            }
            typeof callback == 'function' ? callback( swipedir ) : null;
            alert("you swiped on element w to "+swipedir+" direction");

        }, false);
    },
    isElementInViewport: function ( el )
    {
        if( el != undefined ){
            if (typeof jQuery === "function" && el instanceof jQuery) {
                el = el[0];
            }

            var rect = el.getBoundingClientRect();

            return (
                rect.top >= 0 &&
                rect.left >= 0 &&
                rect.bottom <= $( window ).height() &&
                rect.right <= $( window ).width()
            );
        }
    },
    windowScrollToTop: function ()
    {
        window.scrollTo( 0, 0 );
    },
    hideHTMLOverflow: function ()
    {
        $( 'html' ).addClass( 'locked' );
    },
    showHTMLOverflow: function ()
    {
        $( 'html' ).removeClass( 'locked' );
    }
});<commit_msg>try different swipe logic<commit_after>/**
 * Created by MiKoRiza-OnE on 3/13/2016.
 */

deepmikoto.UtilityFunctions = Marionette.extend({
    constructor: function ()
    {
        //this.enableSwipeUpAndDownSupport();
    },
    detectSwipe: function ( DOMElement, callback )
    {
        var touchsurface = DOMElement,
            swipedir,
            startX,
            startY,
            distX,
            distY,
            threshold = 150, //required min distance traveled to be considered swipe
            restraint = 100, // maximum distance allowed at the same time in perpendicular direction
            allowedTime = 300, // maximum time allowed to travel that distance
            elapsedTime,
            startTime
        ;

        touchsurface.addEventListener('touchstart', function(e){
            e.preventDefault();
            var touchobj = e.changedTouches[0];
            swipedir = 'none';
            startX = touchobj.pageX;
            startY = touchobj.pageY;
            startTime = new Date().getTime(); // record time when finger first makes contact with surface
            $('section').find('.section-content').html('' +
                '
startX:' + startX + ' startY:' + startY + '

'
            )

        }, false);

        touchsurface.addEventListener('touchmove', function(e){
            e.preventDefault(); // prevent scrolling when inside DIV
            $('section').find('.section-content').append('.');
        }, false);

        touchsurface.addEventListener('touchend', function(e){
            e.preventDefault();

            var touchobj = e.changedTouches[0];
            distX = touchobj.pageX - startX; // get horizontal dist traveled by finger while in contact with surface
            distY = touchobj.pageY - startY; // get vertical dist traveled by finger while in contact with surface
            elapsedTime = new Date().getTime() - startTime; // get time elapsed
            $('section').find('.section-content').html('' +
                '

' +
                'startX:' + startX + ' startY:' + startY + '
' +
                'touchobj.pageX:' + touchobj.pageX + ' touchobj.pageY:' + touchobj.pageY + '
' +
                'distX:' + distX + ' distY:' + distY + '
' +
                'threshold:' + threshold + ' restraint:' + restraint + '
' +
                '

'
            );
            if (elapsedTime <= allowedTime){ // first condition for awipe met
                if (Math.abs(distX) >= threshold && Math.abs(distY) <= restraint){ // 2nd condition for horizontal swipe met
                    swipedir = (distX < 0)? 'left' : 'right'; // if dist traveled is negative, it indicates left swipe
                }
                else if (Math.abs(distY) >= threshold && Math.abs(distX) <= restraint){ // 2nd condition for vertical swipe met
                    swipedir = (distY < 0)? 'up' : 'down'; // if dist traveled is negative, it indicates up swipe
                }
            }
            typeof callback == 'function' ? callback( swipedir ) : null;
            alert("you swiped on element w to "+swipedir+" direction");

        }, false);
    },
    isElementInViewport: function ( el )
    {
        if( el != undefined ){
            if (typeof jQuery === "function" && el instanceof jQuery) {
                el = el[0];
            }

            var rect = el.getBoundingClientRect();

            return (
                rect.top >= 0 &&
                rect.left >= 0 &&
                rect.bottom <= $( window ).height() &&
                rect.right <= $( window ).width()
            );
        }
    },
    windowScrollToTop: function ()
    {
        window.scrollTo( 0, 0 );
    },
    hideHTMLOverflow: function ()
    {
        $( 'html' ).addClass( 'locked' );
    },
    showHTMLOverflow: function ()
    {
        $( 'html' ).removeClass( 'locked' );
    }
});<|endoftext|>