<commit_before>import React, {Component} from 'react'
import moment from 'moment'
import StandingOrder from './StandingOrder'

class StandingOrderContainer extends Component {

    constructor(props){
        super(props)
        this.state = {
            orderInstance: props.orderInstance,
            flatOrder: null,
            isLoading: true
        }
        this.orderToState = this.orderToState.bind(this)
        this.handleCancelContract = this.handleCancelContract.bind(this)
        this.handleCollect = this.handleCollect.bind(this)
        this.handleRelabel = this.handleRelabel.bind(this)
        this.handleWithdraw = this.handleWithdraw.bind(this)
        this.handleFund = this.handleFund.bind(this)
    }

    handleCollect() {
        console.log("Collecting funds from contract")
        // return promise
        return this.props.orderInstance.collectFunds({from: this.state.flatOrder.payee})
    }

    handleWithdraw(amount) {
        console.log("Withdrawing " + amount.toString() + " wei from contract")
        // return promise
        return this.props.orderInstance.WithdrawOwnerFunds(amount, {from: this.state.flatOrder.owner})
    }

    handleFund(amount) {
        console.log("Funding contract with " + amount.toString() + " wei")
        // return promise
        return this.props.orderInstance.sendTransaction({
            from: this.state.flatOrder.owner,
            value: amount,
        })
    }

    handleCancelContract() {
        var self=this
        console.log("Cancelling contract (Owner: " + this.props.account)
        this.state.orderInstance.Cancel({from: this.props.account})
            .then(function(result){
                console.log("Successfully cancelled order.")
                // notify parent
                self.props.onRemoveOrder(self.state.orderInstance)
            })
            .catch(function(e){
                console.log("Error while cancelling contract:")
                console.log(e)
            })
    }

    handleRelabel(_label) {
        var self=this
        if (self.props.outgoing) {
            console.log("Setting new owner label " + _label + ", account: " + self.props.account)
            self.state.orderInstance.SetOwnerLabel(_label, {from: self.props.account})
                .then(function (result) {
                    console.log("Successfully set new label.")
                    // update order
                    self.orderToState()
                })
                .catch(function (e) {
                    console.log("Error while setting owner label:")
                    console.log(e)
                })
        }
        else {
            console.log("Setting new payee label " + _label + ", account: " + self.props.account)
            self.state.orderInstance.SetPayeeLabel(_label, {from: self.props.account})
                .then(function (result) {
                    console.log("Successfully set new label.")
                    // update order
                    self.orderToState()
                })
                .catch(function (e) {
                    console.log("Error while setting payee label:")
                    console.log(e)
                })
        }
    }

    orderToState() {
        var self = this

        // indicate that order is loading/updating.
        self.setState({isLoading: true})

        // address is immediately available
        var flatOrder = {
            address: this.state.orderInstance.address
        }

        // get all other info via call() and promises
        var promises = []
        promises.push(this.state.orderInstance.startTime.call().then(function (startTime) {
            flatOrder.startTime = startTime
        }))
        promises.push(this.state.orderInstance.payee.call().then(function (payee) {
            flatOrder.payee = payee
        }))
        promises.push(this.state.orderInstance.owner.call().then(function (owner) {
            flatOrder.owner = owner
        }))
        promises.push(this.state.orderInstance.ownerLabel.call().then(function (ownerLabel) {
            flatOrder.ownerLabel = ownerLabel
        }))
        promises.push(this.state.orderInstance.paymentAmount.call().then(function (amount) {
            flatOrder.paymentAmount = amount
        }))
        promises.push(this.state.orderInstance.paymentInterval.call().then(function (interval) {
            flatOrder.paymentInterval = interval
        }))
        promises.push(this.state.orderInstance.getOwnerFunds.call().then(function (ownerFunds) {
            flatOrder.ownerFunds = ownerFunds
        }))
        promises.push(window.web3.eth.getBalancePromise(this.state.orderInstance.address).then(function (balance) {
            flatOrder.balance = balance
        }))
        promises.push(this.props.orderInstance.getEntitledFunds.call().then(function (entitledFunds) {
            flatOrder.entitledFunds = entitledFunds
        }))
        promises.push(this.props.orderInstance.getUnclaimedFunds.call().then(function (unclaimedFunds) {
            flatOrder.collectibleFunds = unclaimedFunds
        }))
        promises.push(this.state.orderInstance.claimedFunds.call().then(function (claimedFunds) {
            flatOrder.claimedFunds = claimedFunds
        }))

        Promise.all(promises).then(function (results) {
            flatOrder.fundsInsufficient = flatOrder.entitledFunds.gt(flatOrder.collectibleFunds)
            flatOrder.withdrawEnabled = flatOrder.ownerFunds.gt(0)
            flatOrder.cancelEnabled = flatOrder.balance.isZero()
            flatOrder.paymentsCovered = flatOrder.ownerFunds.dividedBy(flatOrder.paymentAmount)
            flatOrder.collectFn = self.handleCollect
            flatOrder.withdrawFn = self.handleWithdraw
            flatOrder.fundFn = self.handleFund
            self.calculateNextPaymentDate(flatOrder)
            self.calculateFailureDate(flatOrder)
            self.setState({
                flatOrder: flatOrder,
                isLoading: false
            })
        }, function(err){
            console.log("Error while retrieving order details:")
            console.log(err)
        })
    }

    // When will the next payment be made
    calculateNextPaymentDate(flatOrder) {
        // If startime is not yet reached the next payment date is the starttime!
        if (Date.now()/1000 < flatOrder.startTime.toNumber()) {
            flatOrder.nextPaymentDate = moment.unix(flatOrder.startTime.toNumber())
            return
        }

        // get seconds elapsed since order startdate
        let secondsElapsed = Math.floor((Date.now()/1000)) - flatOrder.startTime.toNumber()

        // how many paymentIntervals are done
        let donePayments = Math.floor(secondsElapsed / flatOrder.paymentInterval.toNumber())

        // timestamp of last payment
        let lastPayment = window.web3.toBigNumber(donePayments * flatOrder.paymentInterval).plus(flatOrder.startTime).floor()
        flatOrder.lastPaymentDate = moment.unix(lastPayment.toNumber())

        // timestamp of next payment
        let nextPayment = lastPayment.plus(flatOrder.paymentInterval)
        flatOrder.nextPaymentDate = moment.unix(nextPayment.toNumber())
    }

    // When will the last full payment be made
    calculateFailureDate(flatOrder) {
        let secondsToFailure = flatOrder.paymentsCovered.floor() * flatOrder.paymentInterval
        flatOrder.failureDate = flatOrder.nextPaymentDate.clone().add(secondsToFailure, 's')
    }

    componentWillMount() {
        // start filling of flatOrder object
        this.orderToState()
    }

    componentDidMount() {
        // Start listening to new block events and refresh order state
        var self=this
        this.filter = window.web3.eth.filter('latest')
        this.filter.watch(function(error, result){
            self.orderToState()
        })
    }

    componentWillUnmount() {
        // Stop listening to new block events
        this.filter.stopWatching()
    }

    render() {
        return <StandingOrder
            order={this.state.flatOrder}
            onCancelContract={this.handleCancelContract}
            onRelabel={this.handleRelabel}
            outgoing={this.props.outgoing}
            isLoading={this.state.isLoading}
        />
    }
}

export default StandingOrderContainer<commit_msg>Fix order termination.<commit_after>import React, {Component} from 'react'
import moment from 'moment'
import StandingOrder from './StandingOrder'

class StandingOrderContainer extends Component {

    constructor(props){
        super(props)
        this.state = {
            orderInstance: props.orderInstance,
            flatOrder: null,
            isLoading: true
        }
        this.orderToState = this.orderToState.bind(this)
        this.handleCancelContract = this.handleCancelContract.bind(this)
        this.handleCollect = this.handleCollect.bind(this)
        this.handleRelabel = this.handleRelabel.bind(this)
        this.handleWithdraw = this.handleWithdraw.bind(this)
        this.handleFund = this.handleFund.bind(this)
    }

    handleCollect() {
        console.log("Collecting funds from contract")
        // return promise
        return this.props.orderInstance.collectFunds({from: this.state.flatOrder.payee})
    }

    handleWithdraw(amount) {
        console.log("Withdrawing " + amount.toString() + " wei from contract")
        // return promise
        return this.props.orderInstance.WithdrawOwnerFunds(amount, {from: this.state.flatOrder.owner})
    }

    handleFund(amount) {
        console.log("Funding contract with " + amount.toString() + " wei")
        // return promise
        return this.props.orderInstance.sendTransaction({
            from: this.state.flatOrder.owner,
            value: amount,
        })
    }

    handleCancelContract() {
        var self=this
        console.log("Cancelling contract (Owner: " + this.props.account)
        this.state.orderInstance.Terminate({from: this.props.account})
            .then(function(result){
                console.log("Successfully terminated order.")
                // notify parent
                self.props.onRemoveOrder(self.state.orderInstance)
            })
            .catch(function(e){
                console.log("Error while terminating contract:")
                console.log(e)
            })
    }

    handleRelabel(_label) {
        var self=this
        if (self.props.outgoing) {
            console.log("Setting new owner label " + _label + ", account: " + self.props.account)
            self.state.orderInstance.SetOwnerLabel(_label, {from: self.props.account})
                .then(function (result) {
                    console.log("Successfully set new label.")
                    // update order
                    self.orderToState()
                })
                .catch(function (e) {
                    console.log("Error while setting owner label:")
                    console.log(e)
                })
        }
        else {
            console.log("Setting new payee label " + _label + ", account: " + self.props.account)
            self.state.orderInstance.SetPayeeLabel(_label, {from: self.props.account})
                .then(function (result) {
                    console.log("Successfully set new label.")
                    // update order
                    self.orderToState()
                })
                .catch(function (e) {
                    console.log("Error while setting payee label:")
                    console.log(e)
                })
        }
    }

    orderToState() {
        var self = this

        // indicate that order is loading/updating.
        self.setState({isLoading: true})

        // address is immediately available
        var flatOrder = {
            address: this.state.orderInstance.address
        }

        // get all other info via call() and promises
        var promises = []
        promises.push(this.state.orderInstance.startTime.call().then(function (startTime) {
            flatOrder.startTime = startTime
        }))
        promises.push(this.state.orderInstance.payee.call().then(function (payee) {
            flatOrder.payee = payee
        }))
        promises.push(this.state.orderInstance.owner.call().then(function (owner) {
            flatOrder.owner = owner
        }))
        promises.push(this.state.orderInstance.ownerLabel.call().then(function (ownerLabel) {
            flatOrder.ownerLabel = ownerLabel
        }))
        promises.push(this.state.orderInstance.paymentAmount.call().then(function (amount) {
            flatOrder.paymentAmount = amount
        }))
        promises.push(this.state.orderInstance.paymentInterval.call().then(function (interval) {
            flatOrder.paymentInterval = interval
        }))
        promises.push(this.state.orderInstance.getOwnerFunds.call().then(function (ownerFunds) {
            flatOrder.ownerFunds = ownerFunds
        }))
        promises.push(window.web3.eth.getBalancePromise(this.state.orderInstance.address).then(function (balance) {
            flatOrder.balance = balance
        }))
        promises.push(this.props.orderInstance.getEntitledFunds.call().then(function (entitledFunds) {
            flatOrder.entitledFunds = entitledFunds
        }))
        promises.push(this.props.orderInstance.getUnclaimedFunds.call().then(function (unclaimedFunds) {
            flatOrder.collectibleFunds = unclaimedFunds
        }))
        promises.push(this.state.orderInstance.claimedFunds.call().then(function (claimedFunds) {
            flatOrder.claimedFunds = claimedFunds
        }))

        Promise.all(promises).then(function (results) {
            flatOrder.fundsInsufficient = flatOrder.entitledFunds.gt(flatOrder.collectibleFunds)
            flatOrder.withdrawEnabled = flatOrder.ownerFunds.gt(0)
            flatOrder.cancelEnabled = flatOrder.balance.isZero()
            flatOrder.paymentsCovered = flatOrder.ownerFunds.dividedBy(flatOrder.paymentAmount)
            flatOrder.collectFn = self.handleCollect
            flatOrder.withdrawFn = self.handleWithdraw
            flatOrder.fundFn = self.handleFund
            self.calculateNextPaymentDate(flatOrder)
            self.calculateFailureDate(flatOrder)
            self.setState({
                flatOrder: flatOrder,
                isLoading: false
            })
        }, function(err){
            console.log("Error while retrieving order details:")
            console.log(err)
        })
    }

    // When will the next payment be made
    calculateNextPaymentDate(flatOrder) {
        // If startime is not yet reached the next payment date is the starttime!
        if (Date.now()/1000 < flatOrder.startTime.toNumber()) {
            flatOrder.nextPaymentDate = moment.unix(flatOrder.startTime.toNumber())
            return
        }

        // get seconds elapsed since order startdate
        let secondsElapsed = Math.floor((Date.now()/1000)) - flatOrder.startTime.toNumber()

        // how many paymentIntervals are done
        let donePayments = Math.floor(secondsElapsed / flatOrder.paymentInterval.toNumber())

        // timestamp of last payment
        let lastPayment = window.web3.toBigNumber(donePayments * flatOrder.paymentInterval).plus(flatOrder.startTime).floor()
        flatOrder.lastPaymentDate = moment.unix(lastPayment.toNumber())

        // timestamp of next payment
        let nextPayment = lastPayment.plus(flatOrder.paymentInterval)
        flatOrder.nextPaymentDate = moment.unix(nextPayment.toNumber())
    }

    // When will the last full payment be made
    calculateFailureDate(flatOrder) {
        let secondsToFailure = flatOrder.paymentsCovered.floor() * flatOrder.paymentInterval
        flatOrder.failureDate = flatOrder.nextPaymentDate.clone().add(secondsToFailure, 's')
    }

    componentWillMount() {
        // start filling of flatOrder object
        this.orderToState()
    }

    componentDidMount() {
        // Start listening to new block events and refresh order state
        var self=this
        this.filter = window.web3.eth.filter('latest')
        this.filter.watch(function(error, result){
            self.orderToState()
        })
    }

    componentWillUnmount() {
        // Stop listening to new block events
        this.filter.stopWatching()
    }

    render() {
        return <StandingOrder
            order={this.state.flatOrder}
            onCancelContract={this.handleCancelContract}
            onRelabel={this.handleRelabel}
            outgoing={this.props.outgoing}
            isLoading={this.state.isLoading}
        />
    }
}

export default StandingOrderContainer<|endoftext|>


<commit_before>#!/usr/bin/env node

var app = require('commander')
var async = require('async')
var api = require('./util/api')

app
  .description('Export your data')
  .parse(process.argv)

function progress () {
  process.stderr.write('.')
}

async.waterfall([
  function getUser(callback) {
    api('/user', function (err, res, body) {
      if (err) process.exit(1)

      progress()
      callback(null, {user: body})
    })
  },
  function getLists(data, callback) {
    api('/lists', function (err, res, body) {
      if (err) process.exit(1)

      progress()
      data.user.lists = body
      callback(null, data)
    })
  },
  function embedLists(data, callback) {
    var lists = []
    async.each(data.user.lists, function (list, complete) {
      async.parallel([
        function getTasks (cb) {
          api({url: '/tasks', qs: {list_id: list.id}}, function (err, res, body) {
            progress()
            cb(err, body)
          })
        },
        function getSubtasks (cb) {
          api({url: '/subtasks', qs: {list_id: list.id}}, function (err, res, body) {
            progress()
            cb(err, body)
          })
        },
        function getNotes (cb) {
          api({url: '/notes', qs: {list_id: list.id}}, function (err, res, body) {
            if (err) process.exit(1)

            progress()
            cb(err, body)
          })
        },
        function getFiles (cb) {
          api({url: '/files', qs: {list_id: list.id}}, function (err, res, body) {
            progress()
            cb(err, body)
          })
        }
      ], function (err, results) {
        if (err) process.exit(1)

        var tasks = results[0]
        var subtasks = results[1]
        var notes = results[2]
        var files = results[3]
        tasks.forEach(function (task, index) {
          tasks[index].subtasks = []
          tasks[index].notes = []
          tasks[index].files = []
        })
        subtasks.forEach(function (subtask) {
          tasks.forEach(function (task, index) {
            if (task.id === subtask.task_id) {
              tasks[index].subtasks.push(subtask)
            }
          })
        })
        notes.forEach(function (note) {
          tasks.forEach(function (task, index) {
            if (task.id === note.task_id) {
              tasks[index].notes.push(note)
            }
          })
        })
        files.forEach(function (file) {
          tasks.forEach(function (task, index) {
            if (task.id === file.task_id) {
              tasks[index].files.push(file)
            }
          })
        })
        list.tasks = tasks
        lists.push(list)
        complete()
      })
    }, function (err) {
      if (err) process.exit(1)

      data.user.lists = lists
      callback(err, data)
    })
  }
], function (err, data) {
  if (err) process.exit(1)

  process.stdout.write(JSON.stringify({data: data}, null, 2))
})
<commit_msg>renames function<commit_after>#!/usr/bin/env node

var app = require('commander')
var async = require('async')
var api = require('./util/api')

app
  .description('Export your data')
  .parse(process.argv)

function showProgress () {
  process.stderr.write('.')
}

async.waterfall([
  function getUser(callback) {
    api('/user', function (err, res, body) {
      if (err) process.exit(1)

      showProgress()
      callback(null, {user: body})
    })
  },
  function getLists(data, callback) {
    api('/lists', function (err, res, body) {
      if (err) process.exit(1)

      showProgress()
      data.user.lists = body
      callback(null, data)
    })
  },
  function embedLists(data, callback) {
    var lists = []
    async.each(data.user.lists, function (list, complete) {
      async.parallel([
        function getTasks (cb) {
          api({url: '/tasks', qs: {list_id: list.id}}, function (err, res, body) {
            showProgress()
            cb(err, body)
          })
        },
        function getSubtasks (cb) {
          api({url: '/subtasks', qs: {list_id: list.id}}, function (err, res, body) {
            showProgress()
            cb(err, body)
          })
        },
        function getNotes (cb) {
          api({url: '/notes', qs: {list_id: list.id}}, function (err, res, body) {
            if (err) process.exit(1)

            showProgress()
            cb(err, body)
          })
        },
        function getFiles (cb) {
          api({url: '/files', qs: {list_id: list.id}}, function (err, res, body) {
            showProgress()
            cb(err, body)
          })
        }
      ], function (err, results) {
        if (err) process.exit(1)

        var tasks = results[0]
        var subtasks = results[1]
        var notes = results[2]
        var files = results[3]
        tasks.forEach(function (task, index) {
          tasks[index].subtasks = []
          tasks[index].notes = []
          tasks[index].files = []
        })
        subtasks.forEach(function (subtask) {
          tasks.forEach(function (task, index) {
            if (task.id === subtask.task_id) {
              tasks[index].subtasks.push(subtask)
            }
          })
        })
        notes.forEach(function (note) {
          tasks.forEach(function (task, index) {
            if (task.id === note.task_id) {
              tasks[index].notes.push(note)
            }
          })
        })
        files.forEach(function (file) {
          tasks.forEach(function (task, index) {
            if (task.id === file.task_id) {
              tasks[index].files.push(file)
            }
          })
        })
        list.tasks = tasks
        lists.push(list)
        complete()
      })
    }, function (err) {
      if (err) process.exit(1)

      data.user.lists = lists
      callback(err, data)
    })
  }
], function (err, data) {
  if (err) process.exit(1)

  process.stdout.write(JSON.stringify({data: data}, null, 2))
})
<|endoftext|>


<commit_before><commit_msg>fixed #1301<commit_after><|endoftext|>


<commit_before>var React      = require('react');
var Switch     = require('./Switch.react');
var classNames = require('classnames');

var ConnectionForm = require('./ConnectionForm.react');
var Applications   = require('./Applications.react');

var ConnectionsStore = require('../stores/ConnectionsStore');

var ConnectionModal = React.createClass({
  propTypes: {
    title: React.PropTypes.string,
    mode:  React.PropTypes.string
  },
  getInitialState: function () {
    return {
      showSettings:   true,
      showApps:       false,
      showTryIt:      false,
      connection:     this.props.connection || {strategy:'oauth2', options: {scripts: {
        fetchUserProfile: [
                          'function(accessToken, ctx, cb) {',
                          ' // call oauth2 APIwith the accesstoken and create the profile',
                          ' cb(null, profile);',
                          '}'
                          ].join('\n')
      }}, enabled_clients: undefined},
      title:          this.props.title || 'New Connection',
      mode:           this.props.mode || 'create',
      showPrLocation: false,
      showShare:      this.props.mode === 'edit' ? (this.props.connection.isShared === true ? false : true) : false,
      prLocation:     '#',
      sharing:        false,
      saving:         false
    };
  },

  componentDidMount: function () {
    this.setState({
      connectionForm:   React.render(<ConnectionForm defaultValue={this.state.connection} mode={this.state.mode}/>, document.getElementById('connectionForm')),
      applicationsForm: React.render(<Applications defaultValue={this.state.connection.enabled_clients}/>, document.getElementById('applicationsForm'))
    });
  },

  _close: function() {
    React.unmountComponentAtNode(document.getElementById('connectionModal'));
  },

  _showSettings: function () {
    this.setState({
      showSettings: true,
      showApps:     false
    });
  },

  _showApps: function () {
    this.setState({
      showSettings: false,
      showApps:     true
    });
  },

  _showTryIt: function () {
    this.setState({
      showTryIt: true
    });
  },

  _share: function () {
    var connection = this.state.connectionForm.getConnection();

    this.setState({sharing: true});

    ConnectionsStore.share({
      recipe:  connection.name,
      user:    window.env.user,
      content: {
        name:     connection.name,
        strategy: 'oauth2',
        options: {
          authorizationURL: connection.options.authorizationURL,
          tokenURL:         connection.options.tokenURL,
          scope:            connection.options.scope,
          scripts:          {
            fetchUserProfile: connection.options.scripts.fetchUserProfile
          }
        }
      }
    }).then(function (data) {
      this.setState({
        showPrLocation: true,
        showShare:      false,
        prLocation:     data.link,
        sharing:        false
      });
    }.bind(this));
  },

  _save: function () {
    var clients    = this.state.applicationsForm.getSelectedClients();
    var connection = this.state.connectionForm.getConnection();
    var id         = connection.id;
    var isShared   = connection.isShared;

    connection.enabled_clients = Object.keys(clients);
    delete connection.id;
    delete connection.isShared;

    this.setState({saving: true});

    if (this.state.mode === 'create') {
      ConnectionsStore.create(connection)
        .then(function (connection) {
          this._showSettings();
          this._showTryIt();
          this.setState({
            mode:       'edit',
            title:      connection.name,
            showShare:  isShared ? false : true,
            saving:     false
          });

          if (!isShared) {
            this.state.connectionForm.showInfo();
          }

          this.state.connectionForm.setState({
            mode:         'edit',
            defaultValue: connection,
          });

        }.bind(this));
    }

    if (this.state.mode === 'edit') {
      ConnectionsStore.update(id, connection)
        .then(function () {
          this._showSettings();
          this.state.connectionForm.showSuccessMessage();
          this._showTryIt();
          this.state.connectionForm.setState({
            infoStyle: {display: 'none'}
          });
          this.setState({
            saving: false
          });
        }.bind(this));
    }
  },

  generateTryItUrl: function () {
    // // TODO: Extract to Mixin
    return [
      window.env.userUrl + '?',
      'response_type=code',
      '&scope=openid%20profile',
      '&client_id=' + window.env.masterClientId,
      '&prompt=consent',
      '&connection=' + this.state.connection.name,
      '&redirect_uri=https://manage.auth0.com/tester/callback?connection=' + this.state.connection.name
    ].join('');
  },

  render: function () {
    var hide = this.state.mode === 'create';

    return (

              <button onClick={this._close} type="button" className="close">×Close</button>

{this.state.title}

Settings

Apps

                  <form className="connection-form form-horizontal">

                  </form>

                  <form className="connection-form form-horizontal">

                  </form>

                  <button className="btn btn-primary save" onClick={this._save}>
                    Save
                    Saving ...
                  </button>

                    Try

                    Share
                    Sharing ...

                    View PR

    );
  }
});

module.exports = ConnectionModal;
<commit_msg>Fix sharing<commit_after>var React      = require('react');
var Switch     = require('./Switch.react');
var classNames = require('classnames');

var ConnectionForm = require('./ConnectionForm.react');
var Applications   = require('./Applications.react');

var ConnectionsStore = require('../stores/ConnectionsStore');

var ConnectionModal = React.createClass({
  propTypes: {
    title: React.PropTypes.string,
    mode:  React.PropTypes.string
  },
  getInitialState: function () {
    return {
      showSettings:   true,
      showApps:       false,
      showTryIt:      false,
      connection:     this.props.connection || {strategy:'oauth2', options: {scripts: {
        fetchUserProfile: [
                          'function(accessToken, ctx, cb) {',
                          ' // call oauth2 APIwith the accesstoken and create the profile',
                          ' cb(null, profile);',
                          '}'
                          ].join('\n')
      }}, enabled_clients: undefined},
      title:          this.props.title || 'New Connection',
      mode:           this.props.mode || 'create',
      showPrLocation: false,
      showShare:      this.props.mode === 'edit' ? (this.props.connection.isShared === true ? false : true) : false,
      prLocation:     '#',
      sharing:        false,
      saving:         false
    };
  },

  componentDidMount: function () {
    this.setState({
      connectionForm:   React.render(<ConnectionForm defaultValue={this.state.connection} mode={this.state.mode}/>, document.getElementById('connectionForm')),
      applicationsForm: React.render(<Applications defaultValue={this.state.connection.enabled_clients}/>, document.getElementById('applicationsForm'))
    });
  },

  _close: function() {
    React.unmountComponentAtNode(document.getElementById('connectionModal'));
  },

  _showSettings: function () {
    this.setState({
      showSettings: true,
      showApps:     false
    });
  },

  _showApps: function () {
    this.setState({
      showSettings: false,
      showApps:     true
    });
  },

  _showTryIt: function () {
    this.setState({
      showTryIt: true
    });
  },

  _share: function () {
    var connection = this.state.connectionForm.getConnection();

    this.setState({sharing: true});

    ConnectionsStore.share({
      recipe:  connection.name,
      userInfo:    window.env.user,
      content: {
        name:     connection.name,
        strategy: 'oauth2',
        options: {
          authorizationURL: connection.options.authorizationURL,
          tokenURL:         connection.options.tokenURL,
          scope:            connection.options.scope,
          scripts:          {
            fetchUserProfile: connection.options.scripts.fetchUserProfile
          }
        }
      }
    }).then(function (data) {
      this.setState({
        showPrLocation: true,
        showShare:      false,
        prLocation:     data.link,
        sharing:        false
      });
    }.bind(this));
  },

  _save: function () {
    var clients    = this.state.applicationsForm.getSelectedClients();
    var connection = this.state.connectionForm.getConnection();
    var id         = connection.id;
    var isShared   = connection.isShared;

    connection.enabled_clients = Object.keys(clients);
    delete connection.id;
    delete connection.isShared;

    this.setState({saving: true});

    if (this.state.mode === 'create') {
      ConnectionsStore.create(connection)
        .then(function (connection) {
          this._showSettings();
          this._showTryIt();
          this.setState({
            mode:       'edit',
            title:      connection.name,
            showShare:  isShared ? false : true,
            saving:     false
          });

          if (!isShared) {
            this.state.connectionForm.showInfo();
          }

          this.state.connectionForm.setState({
            mode:         'edit',
            defaultValue: connection,
          });

        }.bind(this));
    }

    if (this.state.mode === 'edit') {
      ConnectionsStore.update(id, connection)
        .then(function () {
          this._showSettings();
          this.state.connectionForm.showSuccessMessage();
          this._showTryIt();
          this.state.connectionForm.setState({
            infoStyle: {display: 'none'}
          });
          this.setState({
            saving: false
          });
        }.bind(this));
    }
  },

  generateTryItUrl: function () {
    // // TODO: Extract to Mixin
    return [
      window.env.userUrl + '?',
      'response_type=code',
      '&scope=openid%20profile',
      '&client_id=' + window.env.masterClientId,
      '&prompt=consent',
      '&connection=' + this.state.connection.name,
      '&redirect_uri=https://manage.auth0.com/tester/callback?connection=' + this.state.connection.name
    ].join('');
  },

  render: function () {
    var hide = this.state.mode === 'create';

    return (

              <button onClick={this._close} type="button" className="close">×Close</button>

{this.state.title}

Settings

Apps

                  <form className="connection-form form-horizontal">

                  </form>

                  <form className="connection-form form-horizontal">

                  </form>

                  <button className="btn btn-primary save" onClick={this._save}>
                    Save
                    Saving ...
                  </button>

                    Try

                    Share
                    Sharing ...

                    View PR

    );
  }
});

module.exports = ConnectionModal;
<|endoftext|>


<commit_before>'use strict'

import React, { Component } from 'react'
import ReactCSS from 'reactcss'
import dynamics from 'dynamics.js'
import ReactDOM from 'react-dom'
import { readArmored, encrypt, decrypt, sign, verify } from '../../utils/pgp'

import { Icon } from '../common/index'

import colors from '../../assets/styles/variables/colors'

class ComposerForm extends Component {

  classes() {
    return {
      'default': {
        wrap: {
          position: 'fixed',
          top: '0px',
          right: '0px',
          bottom: '0px',
          left: '0px',
          zIndex: '13',
          flexDirection: 'column',
          display: 'flex',
          background: '#37373C',
        },
        head: {
          background: '#2B272C',
          fontWeight: '300',
          padding: '20px',
        },

        title: {
          fontSize: '20px',
        },
        icon: {
          width: '20px',
          marginRight: '10px',
          display: 'inline-block',
          verticalAlign: 'middle',
        },
        subtitle: {
          fontSize: '16px',
          color: 'rgba(255,255,255,.7)',
          marginTop: '10px',
        },
        text: {
          flex: '1',
          position: 'relative',
          margin: '0 20px',
        },
        textarea: {
          Absolute: '23px auto 10px auto',
          border: 'none',
          outline: 'none',
          width: '100%',
          boxSizing: 'border-box',
          padding: '10px 3%',
          color: '#333',
          borderRadius: '2px',
          fontSize: '14px',
          fontFamily: 'Andale Mono',
        },
        actions: {
          marginTop: '-10px',
          height: '40px',
          padding: '20px',
        },
        confirm: {
          color: '#fff',
          padding: '10px 20px',
          borderRadius: '5px',
          backgroundColor: colors.primary,
          textDecoration: 'none',
          cursor: 'pointer',
          textAlign: 'center',
          display: 'block',
        },
      },
    }
  }

  // componentWillReceiveProps(nextProps) {
  //   if (!this.props.isShowingComposerForm && nextProps.isShowingComposerForm) {
  //     dynamics.animate(this.refs.wrap, {
  //       translateY: 0,
  //       opacity: 1,
  //     }, {
  //       type: dynamics.spring,
  //       duration: 100,
  //       frequency: 110,
  //       friction: 400,
  //     })
  //   }
  // }

  _pgp = (pgpFn, ...options) => {
    return () => {
      const data = this.refs.textarea.value
      const output = pgpFn(data, ...options)
      return output
    }
  }

  readKey = this._pgp(readArmored)

  handleAddKey = async () => {
    const key = await this.readKey()
    await this.props.addKey(key)
  }

  handleEncrypt = async () => {
    const encryptMessage = await this._pgp(encrypt, this.props.selectedKeychain, this.props.alias.privateKeyArmored)()
    this.props.setOutput(encryptMessage)
  }

  handleDecrypt = async () => {
    const message = await this._pgp(decrypt, this.props.alias.privateKeyArmored)()
    this.props.setOutput(message)
  }

  handleSign = async () => {
    const signedMessage = await this._pgp(sign, this.props.alias.privateKeyArmored)()
    this.props.setOutput(signedMessage)
  }

  handleVerify = async () => {
    const match = await this._pgp(verify, this.props.keychain)()
    this.props.setOutput(`Signed message is verified to match: ${match.name} <${match.email}>`)
  }

  getProps = () => {
    return {
      'encrypt': {
        title: 'Encrypt',
        subtitle: 'a message read by / only those that you select / an exclusive club',
        acceptLabel: 'Encrypt',
        onAccept: this.handleEncrypt,
        placeholder: 'Write a Message',
      },
      'decrypt': {
        title: 'Decrypt',
        subtitle: 'unlock a message / only one way to find out / what secrets it holds',
        acceptLabel: 'Decrypt',
        onAccept: this.handleDecrypt,
        placeholder: 'Message to Decrypt',
        icon: 'decrypt',
      },
      'sign': {
        title: 'Sign',
        subtitle: 'sign a new message / so all your pals can be sure / that it’s really you',
        acceptLabel: 'Sign',
        onAccept: this.handleSign,
        placeholder: 'Message to Sign',
        icon: 'sign',
      },
      'verify': {
        title: 'Verify',
        subtitle: 'make sure a message / is by who claimed to write it / verify that shit',
        acceptLabel: 'Verify',
        onAccept: this.handleVerify,
        placeholder: 'Message to Verify',
        icon: 'verify',
      },
      'add key': {
        title: 'Add Key',
        subtitle: 'add a brand new key / to your ever-expanding / magical keychain',
        acceptLabel: 'Add',
        onAccept: this.handleAddKey,
        placeholder: 'Key to add to keychain',
        icon: 'add-key',
      },
    }[this.props.composerType] || {}
  }

  componentWillReceiveProps = (nextProps) => {
    if (nextProps.isShowingComposer) {
      const textarea = ReactDOM.findDOMNode(this.refs.textarea)
      textarea.value = ''
      textarea.focus()
    }
  }

  render() {
    const props = this.getProps()

    return (

              <Icon name={ props.icon } color={ colors.primary } />

            { props.title }

{ props.subtitle }

          <textarea is="textarea" ref="textarea" placeholder={ props.placeholder } onKeyDown={ this.props.handleKeyDown } />

          { this.props.isGeneratingKey ? (
            Generating Key... Pls wait
          ) : (
            { props.acceptLabel }
          ) }

    )
  }
}

export default ReactCSS(ComposerForm)
<commit_msg>Update composer form<commit_after>'use strict'

import React, { Component } from 'react'
import ReactCSS from 'reactcss'
import dynamics from 'dynamics.js'
import ReactDOM from 'react-dom'
import { readArmored, encrypt, decrypt, sign, verify } from '../../utils/pgp'

import { Icon } from '../common/index'

import colors from '../../assets/styles/variables/colors'

class ComposerForm extends Component {

  classes() {
    return {
      'default': {
        wrap: {
          position: 'fixed',
          top: '0px',
          right: '0px',
          bottom: '0px',
          left: '0px',
          zIndex: '13',
          flexDirection: 'column',
          display: 'flex',
          background: '#37373C',
        },
        head: {
          background: '#2B272C',
          fontWeight: '300',
          padding: '20px',
        },

        title: {
          fontSize: '20px',
        },
        icon: {
          width: '20px',
          marginRight: '10px',
          display: 'inline-block',
          verticalAlign: 'middle',
        },
        subtitle: {
          fontSize: '16px',
          color: 'rgba(255,255,255,.7)',
          marginTop: '10px',
        },
        text: {
          flex: '1',
          position: 'relative',
          margin: '0 20px',
        },
        textarea: {
          Absolute: '23px auto 10px auto',
          border: 'none',
          outline: 'none',
          width: '100%',
          boxSizing: 'border-box',
          padding: '10px 3%',
          color: '#333',
          borderRadius: '2px',
          fontSize: '14px',
          fontFamily: 'Andale Mono',
        },
        actions: {
          marginTop: '-10px',
          height: '40px',
          padding: '20px',
        },
        confirm: {
          color: '#fff',
          padding: '10px 20px',
          borderRadius: '5px',
          backgroundColor: colors.primary,
          textDecoration: 'none',
          cursor: 'pointer',
          textAlign: 'center',
          display: 'block',
        },
      },
    }
  }

  // componentWillReceiveProps(nextProps) {
  //   if (!this.props.isShowingComposerForm && nextProps.isShowingComposerForm) {
  //     dynamics.animate(this.refs.wrap, {
  //       translateY: 0,
  //       opacity: 1,
  //     }, {
  //       type: dynamics.spring,
  //       duration: 100,
  //       frequency: 110,
  //       friction: 400,
  //     })
  //   }
  // }

  _pgp = (pgpFn, ...options) => {
    return () => {
      const data = this.refs.textarea.value
      const output = pgpFn(data, ...options)
      return output
    }
  }

  readKey = this._pgp(readArmored)

  getRandomInt = (min, max) => {
    return Math.floor(Math.random() * (max - min + 1)) + min
  }

  handleAddKey = async () => {
    const avatar = this.getRandomInt(1, 23)
    let key = await this.readKey()
    key.avatar = avatar

    console.log(key)
    await this.props.addKey(key)
  }

  handleEncrypt = async () => {
    const encryptMessage = await this._pgp(encrypt, this.props.selectedKeychain, this.props.alias.privateKeyArmored)()
    this.props.setOutput(encryptMessage)
  }

  handleDecrypt = async () => {
    const message = await this._pgp(decrypt, this.props.alias.privateKeyArmored)()
    this.props.setOutput(message)
  }

  handleSign = async () => {
    const signedMessage = await this._pgp(sign, this.props.alias.privateKeyArmored)()
    this.props.setOutput(signedMessage)
  }

  handleVerify = async () => {
    const match = await this._pgp(verify, this.props.keychain)()
    this.props.setOutput(`Signed message is verified to match: ${match.name} <${match.email}>`)
  }

  getProps = () => {
    return {
      'encrypt': {
        title: 'Encrypt',
        subtitle: 'a message read by / only those that you select / an exclusive club',
        acceptLabel: 'Encrypt',
        onAccept: this.handleEncrypt,
        placeholder: 'Write a Message',
      },
      'decrypt': {
        title: 'Decrypt',
        subtitle: 'unlock a message / only one way to find out / what secrets it holds',
        acceptLabel: 'Decrypt',
        onAccept: this.handleDecrypt,
        placeholder: 'Message to Decrypt',
        icon: 'decrypt',
      },
      'sign': {
        title: 'Sign',
        subtitle: 'sign a new message / so all your pals can be sure / that it’s really you',
        acceptLabel: 'Sign',
        onAccept: this.handleSign,
        placeholder: 'Message to Sign',
        icon: 'sign',
      },
      'verify': {
        title: 'Verify',
        subtitle: 'make sure a message / is by who claimed to write it / verify that shit',
        acceptLabel: 'Verify',
        onAccept: this.handleVerify,
        placeholder: 'Message to Verify',
        icon: 'verify',
      },
      'add key': {
        title: 'Add Key',
        subtitle: 'add a brand new key / to your ever-expanding / magical keychain',
        acceptLabel: 'Add',
        onAccept: this.handleAddKey,
        placeholder: 'Key to add to keychain',
        icon: 'add-key',
      },
    }[this.props.composerType] || {}
  }

  componentWillReceiveProps = (nextProps) => {
    if (nextProps.isShowingComposer) {
      const textarea = ReactDOM.findDOMNode(this.refs.textarea)
      textarea.value = ''
      textarea.focus()
    }
  }

  render() {
    const props = this.getProps()

    return (

              <Icon name={ props.icon } color={ colors.primary } />

            { props.title }

{ props.subtitle }

          <textarea is="textarea" ref="textarea" placeholder={ props.placeholder } onKeyDown={ this.props.handleKeyDown } />

          { this.props.isGeneratingKey ? (
            Generating Key... Pls wait
          ) : (
            { props.acceptLabel }
          ) }

    )
  }
}

export default ReactCSS(ComposerForm)
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

const placeholderUrl = chrome.extension.getURL('about-flash.html')
const adobeRegex = new RegExp('//(get\\.adobe\\.com/([a-z_-]+/)*flashplayer|www\\.macromedia\\.com/go/getflash|www\\.adobe\\.com/go/getflash)', 'i')

function isAdobeLink (href) {
  if (typeof href !== 'string') {
    return false
  }
  return adobeRegex.test(href)
}

// Open flash links in the same tab so we can intercept them correctly
(function () {
  function replaceAdobeLinks () {
    Array.from(document.querySelectorAll('a[target="_blank"]')).forEach((elem) => {
      const href = elem.getAttribute('href')
      if (isAdobeLink(href)) {
        elem.setAttribute('target', '')
      }
    })
  }
  setTimeout(() => {
    var observer = new window.MutationObserver(function (mutations) {
      replaceAdobeLinks()
    })
    replaceAdobeLinks()
    observer.observe(document.documentElement, {
      childList: true,
      subtree: true
    })
  }, 1000)
})()

/**
 * Whether a src is a .swf file.
 * If so, returns the origin of the file. Otherwise returns false.
 * @param {string} src
 * @return {boolean|string}
 */
function isSWF (src) {
  if (!src) {
    return false
  }
  let a = document.createElement('a')
  a.href = src
  if (a.pathname && a.pathname.toLowerCase().endsWith('.swf')) {
    return a.origin
  } else {
    return false
  }
}

/**
 * Gets all Flash object descendants of an element.
 * Reference:
 * https://helpx.adobe.com/flash/kb/flash-object-embed-tag-attributes.html
 * @param {Element} elem - HTML element to search
 * @return {Array.<Element>}
 */
function getFlashObjects (elem) {
  let results = [] // Array.<{element: Element, origin: string}>
  Array.from(elem.getElementsByTagName('embed')).forEach((el) => {
    let origin = isSWF(el.getAttribute('src'))
    if (origin) {
      results.push({
        element: el,
        origin
      })
    }
  })

  Array.from(elem.getElementsByTagName('object')).forEach((el) => {
    // Skip objects that are contained in other flash objects
    /*
    for (let i = 0; i < results.length; i++) {
      if (results[i].element.contains(el)) {
        return
      }
    }
    */
    let origin = isSWF(el.getAttribute('data'))
    if (origin) {
      results.push({
        element: el,
        origin
      })
    } else {
      // See example at
      // https://helpx.adobe.com/animate/kb/object-tag-syntax.html
      Array.from(el.getElementsByTagName('param')).forEach((param) => {
        let name = param.getAttribute('name')
        let origin = isSWF(param.getAttribute('value'))
        if (name && ['movie', 'src'].includes(name.toLowerCase()) &&
            origin) {
          results.push({
            element: el,
            origin
          })
        }
      })
    }
  })

  // Some sites have custom Flash placeholders which we should replace with our
  // own.
  Array.from(elem.querySelectorAll('a > img')).forEach((el) => {
    let href = el.parentNode ? el.parentNode.href : null
    if (isAdobeLink(href)) {
      results.push({
        element: el
      })
    }
  })

  return results
}

/**
 * Inserts Flash placeholders.
 * @param {Element} elem - HTML element to search
 */
function insertFlashPlaceholders (elem) {
  const minWidth = 200
  const minHeight = 100
  let flashObjects = getFlashObjects(elem)
  flashObjects.forEach((obj) => {
    let el = obj.element
    let pluginRect = el.getBoundingClientRect()
    let height = el.getAttribute('height') || pluginRect.height
    let width = el.getAttribute('width') || pluginRect.width
    if (height > minHeight && width > minWidth) {
      let parent = el.parentNode
      if (!parent) {
        return
      }
      let iframe = document.createElement('iframe')
      let hash = window.location.origin
      if (chrome.contentSettings.flashEnabled == 'allow') {
        hash = hash + '#flashEnabled'
      }
      iframe.setAttribute('src', [placeholderUrl, hash].join('#'))
      iframe.setAttribute('style', `width: ${width}px; height: ${height}px`)
      parent.replaceChild(iframe, el)
    } else {
      // Note when elements are too small so we can improve the heuristic.
      console.log('got too-small Flash element', obj, height, width)
    }
  })
}

if (chrome.contentSettings.flashActive != 'allow' ||
    chrome.contentSettings.flashEnabled != 'allow') {
  insertFlashPlaceholders(document.documentElement)
  setTimeout(() => {
    var observer = new window.MutationObserver(function (mutations) {
      insertFlashPlaceholders(document.documentElement)
    })

    insertFlashPlaceholders(document.documentElement)
    observer.observe(document.documentElement, {
      childList: true,
      subtree: true
    })
  }, 1000)
}
<commit_msg>Only strip Adobe link target=_blank if Flash is enabled and inactive<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

const placeholderUrl = chrome.extension.getURL('about-flash.html')
const adobeRegex = new RegExp('//(get\\.adobe\\.com/([a-z_-]+/)*flashplayer|www\\.macromedia\\.com/go/getflash|www\\.adobe\\.com/go/getflash)', 'i')

function isAdobeLink (href) {
  if (typeof href !== 'string') {
    return false
  }
  return adobeRegex.test(href)
}

// Open flash links in the same tab so we can intercept them correctly
if (chrome.contentSettings.flashActive != 'allow' &&
    chrome.contentSettings.flashEnabled == 'allow') {
  (function () {
    function replaceAdobeLinks () {
      Array.from(document.querySelectorAll('a[target="_blank"]')).forEach((elem) => {
        const href = elem.getAttribute('href')
        if (isAdobeLink(href)) {
          elem.setAttribute('target', '')
        }
      })
    }
    setTimeout(() => {
      var observer = new window.MutationObserver(function (mutations) {
        replaceAdobeLinks()
      })
      replaceAdobeLinks()
      observer.observe(document.documentElement, {
        childList: true,
        subtree: true
      })
    }, 1000)
  })()
}

/**
 * Whether a src is a .swf file.
 * If so, returns the origin of the file. Otherwise returns false.
 * @param {string} src
 * @return {boolean|string}
 */
function isSWF (src) {
  if (!src) {
    return false
  }
  let a = document.createElement('a')
  a.href = src
  if (a.pathname && a.pathname.toLowerCase().endsWith('.swf')) {
    return a.origin
  } else {
    return false
  }
}

/**
 * Gets all Flash object descendants of an element.
 * Reference:
 * https://helpx.adobe.com/flash/kb/flash-object-embed-tag-attributes.html
 * @param {Element} elem - HTML element to search
 * @return {Array.<Element>}
 */
function getFlashObjects (elem) {
  let results = [] // Array.<{element: Element, origin: string}>
  Array.from(elem.getElementsByTagName('embed')).forEach((el) => {
    let origin = isSWF(el.getAttribute('src'))
    if (origin) {
      results.push({
        element: el,
        origin
      })
    }
  })

  Array.from(elem.getElementsByTagName('object')).forEach((el) => {
    // Skip objects that are contained in other flash objects
    /*
    for (let i = 0; i < results.length; i++) {
      if (results[i].element.contains(el)) {
        return
      }
    }
    */
    let origin = isSWF(el.getAttribute('data'))
    if (origin) {
      results.push({
        element: el,
        origin
      })
    } else {
      // See example at
      // https://helpx.adobe.com/animate/kb/object-tag-syntax.html
      Array.from(el.getElementsByTagName('param')).forEach((param) => {
        let name = param.getAttribute('name')
        let origin = isSWF(param.getAttribute('value'))
        if (name && ['movie', 'src'].includes(name.toLowerCase()) &&
            origin) {
          results.push({
            element: el,
            origin
          })
        }
      })
    }
  })

  // Some sites have custom Flash placeholders which we should replace with our
  // own.
  Array.from(elem.querySelectorAll('a > img')).forEach((el) => {
    let href = el.parentNode ? el.parentNode.href : null
    if (isAdobeLink(href)) {
      results.push({
        element: el
      })
    }
  })

  return results
}

/**
 * Inserts Flash placeholders.
 * @param {Element} elem - HTML element to search
 */
function insertFlashPlaceholders (elem) {
  const minWidth = 200
  const minHeight = 100
  let flashObjects = getFlashObjects(elem)
  flashObjects.forEach((obj) => {
    let el = obj.element
    let pluginRect = el.getBoundingClientRect()
    let height = el.getAttribute('height') || pluginRect.height
    let width = el.getAttribute('width') || pluginRect.width
    if (height > minHeight && width > minWidth) {
      let parent = el.parentNode
      if (!parent) {
        return
      }
      let iframe = document.createElement('iframe')
      let hash = window.location.origin
      if (chrome.contentSettings.flashEnabled == 'allow') {
        hash = hash + '#flashEnabled'
      }
      iframe.setAttribute('src', [placeholderUrl, hash].join('#'))
      iframe.setAttribute('style', `width: ${width}px; height: ${height}px`)
      parent.replaceChild(iframe, el)
    } else {
      // Note when elements are too small so we can improve the heuristic.
      console.log('got too-small Flash element', obj, height, width)
    }
  })
}

if (chrome.contentSettings.flashActive != 'allow' ||
    chrome.contentSettings.flashEnabled != 'allow') {
  insertFlashPlaceholders(document.documentElement)
  setTimeout(() => {
    var observer = new window.MutationObserver(function (mutations) {
      insertFlashPlaceholders(document.documentElement)
    })

    insertFlashPlaceholders(document.documentElement)
    observer.observe(document.documentElement, {
      childList: true,
      subtree: true
    })
  }, 1000)
}
<|endoftext|>


<commit_before>'use strict'

import React, { Component } from 'react'
import ReactCSS from 'reactcss'
import dynamics from 'dynamics.js'
import ReactDOM from 'react-dom'
import { readArmored, encrypt, decrypt, sign, verify } from '../../utils/pgp'

import { Icon } from '../common/index'

import colors from '../../assets/styles/variables/colors'

class ComposerForm extends Component {

  classes() {
    return {
      'default': {
        wrap: {
          position: 'fixed',
          top: '0px',
          right: '0px',
          bottom: '0px',
          left: '0px',
          zIndex: '13',
          flexDirection: 'column',
          display: 'flex',
          background: '#37373C',
        },
        head: {
          background: '#2B272C',
          fontWeight: '300',
          padding: '20px',
        },

        title: {
          fontSize: '20px',
        },
        icon: {
          width: '20px',
          marginRight: '10px',
          display: 'inline-block',
          verticalAlign: 'middle',
        },
        subtitle: {
          fontSize: '16px',
          color: 'rgba(255,255,255,.7)',
          marginTop: '10px',
        },
        text: {
          flex: '1',
          position: 'relative',
          margin: '0 20px',
        },
        textarea: {
          Absolute: '23px auto 10px auto',
          border: 'none',
          outline: 'none',
          width: '100%',
          boxSizing: 'border-box',
          padding: '10px 3%',
          color: '#333',
          borderRadius: '2px',
          fontSize: '14px',
          fontFamily: 'Andale Mono',
        },
        actions: {
          marginTop: '-10px',
          height: '40px',
          padding: '20px',
        },
        confirm: {
          color: '#fff',
          padding: '10px 20px',
          borderRadius: '5px',
          backgroundColor: colors.primary,
          textDecoration: 'none',
          cursor: 'pointer',
          textAlign: 'center',
          display: 'block',
        },
      },
    }
  }

  // componentWillReceiveProps(nextProps) {
  //   if (!this.props.isShowingComposerForm && nextProps.isShowingComposerForm) {
  //     dynamics.animate(this.refs.wrap, {
  //       translateY: 0,
  //       opacity: 1,
  //     }, {
  //       type: dynamics.spring,
  //       duration: 100,
  //       frequency: 110,
  //       friction: 400,
  //     })
  //   }
  // }

  _pgp = (pgpFn, ...options) => {
    return () => {
      const data = this.refs.textarea.value
      const output = pgpFn(data, ...options)
      return output
    }
  }

  readKey = this._pgp(readArmored)

  getRandomInt = (min, max) => {
    return Math.floor(Math.random() * (max - min + 1)) + min
  }

  handleAddKey = async () => {
    const avatar = this.getRandomInt(1, 23)
    let key = await this.readKey()
    key.avatar = avatar

    console.log(key)
    await this.props.addKey(key)
  }

  handleEncrypt = async () => {
    const encryptMessage = await this._pgp(encrypt, this.props.selectedKeychain, this.props.alias.privateKeyArmored)()
    this.props.setOutput(encryptMessage)
  }

  handleDecrypt = async () => {
    const message = await this._pgp(decrypt, this.props.alias.privateKeyArmored)()
    this.props.setOutput(message)
  }

  handleSign = async () => {
    const signedMessage = await this._pgp(sign, this.props.alias.privateKeyArmored)()
    this.props.setOutput(signedMessage)
  }

  handleVerify = async () => {
    const match = await this._pgp(verify, this.props.keychain)()
    this.props.setOutput(`Signed message is verified to match: ${match.name} <${match.email}>`)
  }

  getProps = () => {
    return {
      'encrypt': {
        title: 'Encrypt',
        subtitle: 'a message read by / only those that you select / an exclusive club',
        acceptLabel: 'Encrypt',
        onAccept: this.handleEncrypt,
        placeholder: 'Write a Message',
      },
      'decrypt': {
        title: 'Decrypt',
        subtitle: 'unlock a message / only one way to find out / what secrets it holds',
        acceptLabel: 'Decrypt',
        onAccept: this.handleDecrypt,
        placeholder: 'Message to Decrypt',
        icon: 'decrypt',
      },
      'sign': {
        title: 'Sign',
        subtitle: 'sign a new message / so all your pals can be sure / that it’s really you',
        acceptLabel: 'Sign',
        onAccept: this.handleSign,
        placeholder: 'Message to Sign',
        icon: 'sign',
      },
      'verify': {
        title: 'Verify',
        subtitle: 'make sure a message / is by who claimed to write it / verify that shit',
        acceptLabel: 'Verify',
        onAccept: this.handleVerify,
        placeholder: 'Message to Verify',
        icon: 'verify',
      },
      'add key': {
        title: 'Add Key',
        subtitle: 'add a brand new key / to your ever-expanding / magical keychain',
        acceptLabel: 'Add',
        onAccept: this.handleAddKey,
        placeholder: 'Key to add to keychain',
        icon: 'add-key',
      },
    }[this.props.composerType] || {}
  }

  componentWillReceiveProps = (nextProps) => {
    if (nextProps.isShowingComposer) {
      const textarea = ReactDOM.findDOMNode(this.refs.textarea)
      textarea.value = ''
      textarea.focus()
    }
  }

  render() {
    const props = this.getProps()

    return (

              <Icon name={ props.icon } color={ colors.primary } />

            { props.title }

{ props.subtitle }

          <textarea is="textarea" ref="textarea" placeholder={ props.placeholder } onKeyDown={ this.props.handleKeyDown } />

          { this.props.isGeneratingKey ? (
            Generating Key... Pls wait
          ) : (
            { props.acceptLabel }
          ) }

    )
  }
}

export default ReactCSS(ComposerForm)
<commit_msg>Update composer form styles<commit_after>'use strict'

import React, { Component } from 'react'
import ReactCSS from 'reactcss'
import dynamics from 'dynamics.js'
import ReactDOM from 'react-dom'
import { readArmored, encrypt, decrypt, sign, verify } from '../../utils/pgp'

import { Icon } from '../common/index'
import ComposerFormSubmit from './ComposerFormSubmit'

import colors from '../../assets/styles/variables/colors'

class ComposerForm extends Component {

  classes() {
    return {
      'default': {
        wrap: {
          position: 'fixed',
          top: '0px',
          right: '0px',
          bottom: '0px',
          left: '0px',
          zIndex: '13',
          flexDirection: 'column',
          display: 'flex',
          background: '#37373C',
        },
        head: {
          background: '#2B272C',
          fontWeight: '300',
          padding: '10px 20px',
          paddingTop: '35px',
        },

        title: {
          fontSize: '20px',
          fontWeight: '400',
        },
        icon: {
          width: '20px',
          marginRight: '10px',
          display: 'inline-block',
          verticalAlign: 'middle',
        },
        subtitle: {
          fontSize: '16px',
          color: 'rgba(255,255,255,.7)',
          marginTop: '6px',
          marginBottom: '3px',
          lineHeight: '23px',
        },
        text: {
          flex: '1',
          position: 'relative',
          margin: '0 20px',
          marginTop: '-10px',
        },
        textarea: {
          Absolute: '23px auto 10px auto',
          border: 'none',
          outline: 'none',
          width: '100%',
          boxSizing: 'border-box',
          padding: '10px 3%',
          color: '#333',
          borderRadius: '2px',
          fontSize: '14px',
          fontFamily: 'Andale Mono',
          marginTop: '5px',
        },
        actions: {
          marginTop: '-18px',
          height: '55px',
          padding: '20px',
        },
        confirm: {
          color: '#fff',
          padding: '10px 20px',
          borderRadius: '5px',
          backgroundColor: colors.primary,
          textDecoration: 'none',
          cursor: 'pointer',
          textAlign: 'center',
          display: 'block',
        },
        cancel: {
          color: 'rgba(255,255,255,.4)',
          textAlign: 'center',
          display: 'block',
          marginTop: '7px',
          cursor: 'pointer',
        },
      },
    }
  }

  // componentWillReceiveProps(nextProps) {
  //   if (!this.props.isShowingComposerForm && nextProps.isShowingComposerForm) {
  //     dynamics.animate(this.refs.wrap, {
  //       translateY: 0,
  //       opacity: 1,
  //     }, {
  //       type: dynamics.spring,
  //       duration: 100,
  //       frequency: 110,
  //       friction: 400,
  //     })
  //   }
  // }

  _pgp = (pgpFn, ...options) => {
    return () => {
      const data = this.refs.textarea.value
      const output = pgpFn(data, ...options)
      return output
    }
  }

  readKey = this._pgp(readArmored)

  getRandomInt = (min, max) => {
    return Math.floor(Math.random() * (max - min + 1)) + min
  }

  handleAddKey = async () => {
    const avatar = this.getRandomInt(1, 23)
    let key = await this.readKey()
    key.avatar = avatar

    console.log(key)
    await this.props.addKey(key)
  }

  handleEncrypt = async () => {
    const encryptMessage = await this._pgp(encrypt, this.props.selectedKeychain, this.props.alias.privateKeyArmored)()
    this.props.setOutput(encryptMessage)
  }

  handleDecrypt = async () => {
    const message = await this._pgp(decrypt, this.props.alias.privateKeyArmored)()
    this.props.setOutput(message)
  }

  handleSign = async () => {
    const signedMessage = await this._pgp(sign, this.props.alias.privateKeyArmored)()
    this.props.setOutput(signedMessage)
  }

  handleVerify = async () => {
    const match = await this._pgp(verify, this.props.keychain)()
    this.props.setOutput(`Signed message is verified to match: ${match.name} <${match.email}>`)
  }

  getProps = () => {
    return {
      'encrypt': {
        title: 'Encrypt',
        subtitle: 'Encrypting creates a locked message for your recipients.',
        acceptLabel: 'Encrypt',
        onAccept: this.handleEncrypt,
        placeholder: 'Write a message',
        icon: 'encrypt',
      },
      'decrypt': {
        title: 'Decrypt',
        subtitle: 'Decrypting a message lets you read for you.',
        acceptLabel: 'Decrypt',
        onAccept: this.handleDecrypt,
        placeholder: 'Paste an encrypted message',
        icon: 'decrypt',
      },
      'sign': {
        title: 'Sign',
        subtitle: 'Signing a message lets others know that it’s really you.',
        acceptLabel: 'Sign',
        onAccept: this.handleSign,
        placeholder: 'Write a message',
        icon: 'sign',
      },
      'verify': {
        title: 'Verify',
        subtitle: 'Verifying confirms who authored a message is as they claim.',
        acceptLabel: 'Verify',
        onAccept: this.handleVerify,
        placeholder: 'Paste a signed message',
        icon: 'verify',
      },
      'add key': {
        title: 'Add Key',
        subtitle: 'Add someone’s public key to your buddies list.',
        acceptLabel: 'Add',
        onAccept: this.handleAddKey,
        placeholder: 'Paste a public key',
        icon: 'add-key',
      },
    }[this.props.composerType] || {}
  }

  componentWillReceiveProps = (nextProps) => {
    if (nextProps.isShowingComposer) {
      const textarea = ReactDOM.findDOMNode(this.refs.textarea)
      textarea.value = ''
      textarea.focus()
    }
  }

  render() {
    const props = this.getProps()

    return (

              <Icon name={ props.icon } color={ colors.primary } />

            { props.title }

{ props.subtitle }

          <textarea is="textarea" ref="textarea" placeholder={ props.placeholder } onKeyDown={ this.props.handleKeyDown } />

          { this.props.isGeneratingKey ? (
            Generating Key... Pls wait
          ) : (
            <ComposerFormSubmit
              onClick={ props.onAccept }
              value={ props.acceptLabel }
            />
          ) }
          nevermind

    )
  }
}

export default ReactCSS(ComposerForm)
<|endoftext|>


<commit_before>import Ember from 'ember';

var Router = Ember.Router.extend({
  location: IliosENV.locationType
});
Router.map(function() {
  this.resource('dashboard', function() {
    this.route('day');
    this.route('week');
    this.route('month');
    this.route('year');
  });
  this.resource('programs', function(){
    this.route('new');
    this.resource('program', { path: ':program_id' }, function(){
      this.route('index');
      this.route('edit');
      this.route('newyear');
      this.resource('programyear', { path: 'year/:program_year_id' }, function(){
        this.route('index');
        this.route('managecompetencies');
        this.route('manageobjectives');
        this.route('managedirectors');
        this.route('managetopics');
        this.route('managestewardingschools');
      });
    });
  });
});

export default Router;
<commit_msg>Fix pluralization on program years route<commit_after>import Ember from 'ember';

var Router = Ember.Router.extend({
  location: IliosENV.locationType
});
Router.map(function() {
  this.resource('dashboard', function() {
    this.route('day');
    this.route('week');
    this.route('month');
    this.route('year');
  });
  this.resource('programs', function(){
    this.route('new');
    this.resource('program', { path: ':program_id' }, function(){
      this.route('index');
      this.route('edit');
      this.route('newyear');
      this.resource('programyear', { path: 'years/:program_year_id' }, function(){
        this.route('index');
        this.route('managecompetencies');
        this.route('manageobjectives');
        this.route('managedirectors');
        this.route('managetopics');
        this.route('managestewardingschools');
      });
    });
  });
});

export default Router;
<|endoftext|>


<commit_before>define(['app', 'lodash', 'scbd-angularjs-services/extended-route',  'scbd-angularjs-services/authentication'], function(app, _) { 'use strict';

    app.config(['extendedRouteProvider', '$locationProvider', function($routeProvider, $locationProvider) {

        $locationProvider.html5Mode(true);
        $locationProvider.hashPrefix('!');

        $routeProvider.
            when('/',                         { templateUrl: 'views/schedule/conference.html',                resolveController: true, resolveUser: true, resolve : { securized : securize(['Administrator','EunoAdministrator']) } }).
            when('/home',                     { redirectTo: '/' }).
            when('/cctv/feeds',               { templateUrl: 'views/cctv/feeds.html',                  resolveController: true, resolveUser: true, reloadOnSearch : false, resolve : { securized : securize(['Administrator','EunoAdministrator']) } }).
            when('/cctv/frames',              { templateUrl: 'views/cctv/frames.html',                 resolveController: true, resolveUser: true, reloadOnSearch : false, resolve : { securized : securize(['Administrator','EunoAdministrator']) } }).
            when('/schedule/location',        { templateUrl: 'views/schedule/location.html',           resolveController: true, resolveUser: true }).
            when('/schedule/conference',      { templateUrl: 'views/schedule/conference.html',         resolveController: true, resolveUser: true }).
            when('/side-events',              { templateUrl: 'views/side-events.html',                 resolveController: true, resolveUser: true, resolve : { securized : securize(['Administrator','EunoAdministrator']) } }).
            when('/admin/reservation/types',  { templateUrl: 'views/admin/reservation-types.html',     resolveController: true, resolveUser: true, resolve : { securized : securize(['Administrator','EunoAdministrator']) } }).
            when('/404', { templateUrl: 'views/404.html' }).
            when('/403', { templateUrl: 'views/403.html' }).
            otherwise({ redirectTo: '/404' });
    }]);

    //============================================================
    //
    //
    //============================================================
    function securize(roles) {

        return ['$location', '$window', '$q','authentication', function ($location, $window, $q, authentication) {
            //return true; // TEMPORARY DISABLED SECURIZE TO PREVENT LOOPING
            return authentication.getUser().then(function (user) {

                if (!user.isAuthenticated) {
                    var returnUrl = $window.encodeURIComponent($window.location.href);
                    $window.location.href = 'https://accounts.cbd.int/signin?returnUrl=' + returnUrl; // force sign in
                    return $q(function () {});
                }
                else if (roles && !_.isEmpty(roles) && _.isEmpty(_.intersection(roles, user.roles))) {
                    $location.url('/403'); // not authorized
                }

                return user;
            });
        }];
    }
});
<commit_msg>Use apiUrl for authentication redirection<commit_after>define(['app', 'lodash', 'scbd-angularjs-services/extended-route',  'scbd-angularjs-services/authentication'], function(app, _) { 'use strict';

    app.config(['extendedRouteProvider', '$locationProvider', function($routeProvider, $locationProvider) {

        $locationProvider.html5Mode(true);
        $locationProvider.hashPrefix('!');

        $routeProvider.
            when('/',                         { templateUrl: 'views/schedule/conference.html',                resolveController: true, resolveUser: true, resolve : { securized : securize(['Administrator','EunoAdministrator']) } }).
            when('/home',                     { redirectTo: '/' }).
            when('/cctv/feeds',               { templateUrl: 'views/cctv/feeds.html',                  resolveController: true, resolveUser: true, reloadOnSearch : false, resolve : { securized : securize(['Administrator','EunoAdministrator']) } }).
            when('/cctv/frames',              { templateUrl: 'views/cctv/frames.html',                 resolveController: true, resolveUser: true, reloadOnSearch : false, resolve : { securized : securize(['Administrator','EunoAdministrator']) } }).
            when('/schedule/location',        { templateUrl: 'views/schedule/location.html',           resolveController: true, resolveUser: true }).
            when('/schedule/conference',      { templateUrl: 'views/schedule/conference.html',         resolveController: true, resolveUser: true }).
            when('/side-events',              { templateUrl: 'views/side-events.html',                 resolveController: true, resolveUser: true, resolve : { securized : securize(['Administrator','EunoAdministrator']) } }).
            when('/admin/reservation/types',  { templateUrl: 'views/admin/reservation-types.html',     resolveController: true, resolveUser: true, resolve : { securized : securize(['Administrator','EunoAdministrator']) } }).
            when('/404', { templateUrl: 'views/404.html' }).
            when('/403', { templateUrl: 'views/403.html' }).
            otherwise({ redirectTo: '/404' });
    }]);

    //============================================================
    //
    //
    //============================================================
    function securize(roles) {

        return ['$location', '$window', '$q','authentication', 'apiUrl', function ($location, $window, $q, authentication, apiUrl) {

            return authentication.getUser().then(function (user) {

                if (!user.isAuthenticated) {

                    var accountsUrl = apiUrl.devAccountsUrl() || 'https://accounts.cbd.int';
                    var returnUrl   = $window.encodeURIComponent($window.location.href);

                    $window.location.href = accountsUrl+'/signin?returnUrl=' + returnUrl; // force sign in

                    return $q(function () {});
                }
                else if (roles && !_.isEmpty(roles) && _.isEmpty(_.intersection(roles, user.roles))) {
                    $location.url('/403'); // not authorized
                }

                return user;
            });
        }];
    }
});
<|endoftext|>


<commit_before>angular.module('teamform-login-app', ['teamform-db', 'current-user'])
.controller('LoginCtrl', ['$scope', 'teamformDb', 'currentUser', LoginCtrl]);

function LoginCtrl($scope, teamformDb, currentUser, $window) {
    var vm = this;
    vm.errorMsg = '';
    vm.login = login;
    vm.saveNewFBUser = saveNewFBUser;
    vm.setMessage = setMessage;
    $scope.user = {
      username: '',
      email: '',
      pass: '',
      confirmpass: ''
    };
    $scope.newerrorMsg ='default';

    function login() {
        vm.errorMsg = '';
        teamformDb.loginWithFacebook().then(function(result) {
          // This gives you a Facebook Access Token. You can use it to access the Facebook API.
          var token = result.credential.accessToken;
          var user = result.user;
          saveNewFBUser(user, token);
        }).catch(function(error) {
          // Handle Errors here.
          // var errorCode = error.code;
          var errorMessage = error.message;
          // var email = error.email;
          // var credential = error.credential;
          setMessage(errorMessage);
          $scope.$apply();
        });
    }

    function saveNewFBUser(user, token) {
      teamformDb.saveNewFBUser(
        user.uid,
        user.displayName,
        user.email,
        user.photoURL,
        token,
        user.refreshToken,
        function() {
          var savedUser = teamformDb.getUser(user.uid);
          currentUser.setCurrentUser(savedUser);
          setTimeout(function() {
            window.location.href= "index.html";
          }, 1000);
        }
        );
    }

    function setMessage(msg) {
      vm.errorMsg = msg;
    }

    //angularjs version for register() with bugs
    $scope.newregister = function(){
      if($scope.user.pass==$scope.user.confirmpass && $scope.user.username!=''){
        setTimeout(function() {
            window.location.href= "registersuccessfu_page.html";
          }, 1000);
      }

    }

}

// function newregister ($username, $pass, $confirmpass){
//       if($pass==$confirmpass && $username!=''){
//         window.open('index.html','_self');
//       }

//     }
<commit_msg>Remove unused function that causing a degrade in coverage<commit_after>angular.module('teamform-login-app', ['teamform-db', 'current-user'])
.controller('LoginCtrl', ['$scope', 'teamformDb', 'currentUser', LoginCtrl]);

function LoginCtrl($scope, teamformDb, currentUser, $window) {
    var vm = this;
    vm.errorMsg = '';
    vm.login = login;
    vm.saveNewFBUser = saveNewFBUser;
    vm.setMessage = setMessage;
    $scope.user = {
      username: '',
      email: '',
      pass: '',
      confirmpass: ''
    };
    $scope.newerrorMsg ='default';

    function login() {
        vm.errorMsg = '';
        teamformDb.loginWithFacebook().then(function(result) {
          // This gives you a Facebook Access Token. You can use it to access the Facebook API.
          var token = result.credential.accessToken;
          var user = result.user;
          saveNewFBUser(user, token);
        }).catch(function(error) {
          // Handle Errors here.
          // var errorCode = error.code;
          var errorMessage = error.message;
          // var email = error.email;
          // var credential = error.credential;
          setMessage(errorMessage);
          $scope.$apply();
        });
    }

    function saveNewFBUser(user, token) {
      teamformDb.saveNewFBUser(
        user.uid,
        user.displayName,
        user.email,
        user.photoURL,
        token,
        user.refreshToken,
        function() {
          var savedUser = teamformDb.getUser(user.uid);
          currentUser.setCurrentUser(savedUser);
          setTimeout(function() {
            window.location.href= "index.html";
          }, 1000);
        }
        );
    }

    function setMessage(msg) {
      vm.errorMsg = msg;
    }

}
<|endoftext|>


<commit_before>import React from 'react';
import { Route, IndexRoute } from 'react-router';

import { asyncComponent } from './utils/asyncComponent'; /* for show loading component */

import Root from './components/Root';
import Posts from './components/Pages/Posts';
import About from './components/Pages/About';

export default (
  <Route path="/" component={Root}>
    <IndexRoute component={Posts} />
    { /* async component */}
    <Route path="/async-example" getComponent={(location, callback) =>
      __CLIENT__
        ? asyncComponent(require.ensure([], require => callback('', require('./components/Pages/AsyncExample').default), 'async-example'))
        : callback()
    } />

    <Route path="/posts" component={Posts} />
    <Route path="/about" component={About} />
  </Route>
);
<commit_msg>small update ssr async page<commit_after>import React from 'react';
import { Route, IndexRoute } from 'react-router';

import { asyncComponent } from './utils/asyncComponent'; /* for show loading component */

import Root from './components/Root';
import Posts from './components/Pages/Posts';
import About from './components/Pages/About';

export default (
  <Route path="/" component={Root}>
    <IndexRoute component={Posts} />
    { /* async component */}
    <Route path="/async-example" getComponent={(location, callback) =>
      __CLIENT__
        ? asyncComponent(require.ensure([], require => callback('', require('./components/Pages/AsyncExample').default), 'async-example'))
        : callback('', require('./components/Pages/AsyncExample').default)
    } />

    <Route path="/posts" component={Posts} />
    <Route path="/about" component={About} />
  </Route>
);
<|endoftext|>