<commit_before>/*
 * Copyright 2014 XWiki SAS
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
define([
    '/common/messages.js',
    '/common/netflux.js',
    '/common/crypto.js',
    '/common/toolbar.js',
    '/common/sharejs_textarea.js',
    '/common/chainpad.js',
    '/bower_components/jquery/dist/jquery.min.js',
], function (Messages, Netflux, Crypto, Toolbar, sharejs) {
    var $ = window.jQuery;
    var ChainPad = window.ChainPad;
    var PARANOIA = true;
    var module = { exports: {} };

    /**
     * If an error is encountered but it is recoverable, do not immediately fail
     * but if it keeps firing errors over and over, do fail.
     */
    var MAX_RECOVERABLE_ERRORS = 15;

    var debug = function (x) { console.log(x); },
        warn = function (x) { console.error(x); },
        verbose = function (x) { console.log(x); };
    verbose = function () {}; // comment out to enable verbose logging

    // ------------------ Trapping Keyboard Events ---------------------- //

    var bindEvents = function (element, events, callback, unbind) {
        for (var i = 0; i < events.length; i++) {
            var e = events[i];
            if (element.addEventListener) {
                if (unbind) {
                    element.removeEventListener(e, callback, false);
                } else {
                    element.addEventListener(e, callback, false);
                }
            } else {
                if (unbind) {
                    element.detachEvent('on' + e, callback);
                } else {
                    element.attachEvent('on' + e, callback);
                }
            }
        }
    };

    var bindAllEvents = function (textarea, docBody, onEvent, unbind)
    {
        /*
            we use docBody for the purposes of CKEditor.
            because otherwise special keybindings like ctrl-b and ctrl-i
            would open bookmarks and info instead of applying bold/italic styles
        */
        if (docBody) {
            bindEvents(docBody,
               ['textInput', 'keydown', 'keyup', 'select', 'cut', 'paste'],
               onEvent,
               unbind);
        }
        bindEvents(textarea,
                   ['mousedown','mouseup','click','change'],
                   onEvent,
                   unbind);
    };

    var getParameterByName = function (name, url) {
        if (!url) { url = window.location.href; }
        name = name.replace(/[\[\]]/g, "\\$&");
        var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
            results = regex.exec(url);
        if (!results) { return null; }
        if (!results[2]) { return ''; }
        return decodeURIComponent(results[2].replace(/\+/g, " "));
    };

    var start = module.exports.start =
        function (config)
    {
        var textarea = config.textarea;
        var websocketUrl = config.websocketURL;
        var webrtcUrl = config.webrtcURL;
        var userName = config.userName;
        var channel = config.channel;
        var cryptKey = config.cryptKey;
        var passwd = 'y';

        // make sure configuration is defined
        config = config || {};

        var doc = config.doc || null;

        // trying to deprecate onRemote, prefer loading it via the conf
        var onRemote = config.onRemote || null;

        // define this in case it gets called before the rest of our stuff is ready.
        var onEvent = function () { };

        var allMessages = [];
        var initializing = true;
        var recoverableErrorCount = 0;
        var bump = function () {};
        var messagesHistory = [];
        var chainpadAdapter = {};
        var realtime;

        var parseMessage = function (msg) {
            var res ={};
            // two or more? use a for
            ['pass','user','channelId','content'].forEach(function(attr){
                var len=msg.slice(0,msg.indexOf(':')),
                // taking an offset lets us slice out the prop
                // and saves us one string copy
                    o=len.length+1,
                    prop=res[attr]=msg.slice(o,Number(len)+o);
                // slice off the property and its descriptor
                msg = msg.slice(prop.length+o);
            });
            // content is the only attribute that's not a string
            res.content=JSON.parse(res.content);
            return res;
        };

        var mkMessage = function (user, channel, content) {
            content = JSON.stringify(content);
            return user.length + ':' + user +
                channel.length + ':' + channel +
                content.length + ':' + content;
        };

        var onPeerMessage = function(toId, type, wc) {
            if(type === 6) {
                messagesHistory.forEach(function(msg) {
                    wc.sendTo(toId, '1:y'+msg);
                });
                wc.sendTo(toId, '0');
            }
        };

        var whoami = new RegExp(userName.replace(/[\/\+]/g, function (c) {
            return '\\' +c;
        }));

        var onMessage = function(peer, msg, wc) {

            if(msg === 0 || msg === '0') {
                onReady(wc);
                return;
            }
            var message = chainpadAdapter.msgIn(peer, msg);

            verbose(message);
            allMessages.push(message);
            if (!initializing) {
                if (PARANOIA) {
                    onEvent();
                }
            }
            realtime.message(message);
            if (/\[5,/.test(message)) { verbose("pong"); }

            if (!initializing) {
                if (/\[2,/.test(message)) {
                    //verbose("Got a patch");
                    if (whoami.test(message)) {
                        //verbose("Received own message");
                    } else {
                        //verbose("Received remote message");
                        // obviously this is only going to get called if
                        if (onRemote) { onRemote(realtime.getUserDoc()); }
                    }
                }
            }
        };

        var userList = {
          onChange : function() {},
          users: []
        };
        var onJoining = function(peer) {
          var list = userList.users;
          if(list.indexOf(peer) === -1) {
            userList.users.push(peer);
          }
          userList.onChange();
        };

        var onLeaving = function(peer) {
          var list = userList.users;
          var index = list.indexOf(peer);
          if(index !== -1) {
            userList.users.splice(index, 1);
          }
          userList.onChange();
        };

        chainpadAdapter = {
            msgIn : function(peerId, msg) {
                var parsed = parseMessage(msg);
                // Remove the password from the message
                var passLen = msg.substring(0,msg.indexOf(':'));
                var message = msg.substring(passLen.length+1 + Number(passLen));
                try {
                    var decryptedMsg = Crypto.decrypt(message, cryptKey);
                    messagesHistory.push(decryptedMsg);
                    return decryptedMsg;
                } catch (err) {
                    return message;
                }

            },
            msgOut : function(msg, wc) {
                var parsed = parseMessage(msg);
                if(parsed.content[0] === 0) { // We're registering : send a REGISTER_ACK to Chainpad
                    onMessage('', '1:y'+mkMessage('', channel, [1,0]));
                    return;
                }
                if(parsed.content[0] === 4) { // PING message from Chainpad
                    parsed.content[0] = 5;
                    onMessage('', '1:y'+mkMessage(parsed.user, parsed.channelId, parsed.content));
                    wc.sendPing();
                    return;
                }
                return Crypto.encrypt(msg, cryptKey);
            }
        };

        var options = {
          key: channel
        };

        var rtc = true;

        if(!getParameterByName("webrtc") || !webrtcUrl) {
          rtc = false;
          options.signaling = websocketUrl;
          options.topology = 'StarTopologyService';
          options.protocol = 'WebSocketProtocolService';
          options.connector = 'WebSocketService';
          options.openWebChannel = true;
        }
        else {
          options.signaling = webrtcUrl;
        }

        var createRealtime = function() {
            return ChainPad.create(userName,
                                        passwd,
                                        channel,
                                        $(textarea).val(),
                                        {
                                        transformFunction: config.transformFunction
                                        });
        };

        var onReady = function(wc) {
            if(config.onInit) {
                config.onInit({
                    myID: wc.myID,
                    realtime: realtime,
                    webChannel: wc,
                    userList: userList
                });
            }
            // Trigger onJoining with our own Cryptpad username to tell the toolbar that we are synced
            onJoining(wc.myID);

            // we're fully synced
            initializing = false;

            // execute an onReady callback if one was supplied
            if (config.onReady) {
                config.onReady();
            }
        }

        var onOpen = function(wc) {
            // Add the handlers to the WebChannel
            wc.onmessage = function(peer, msg) { // On receiving message
                onMessage(peer, msg, wc);
            };
            wc.onJoining = onJoining; // On user joining the session
            wc.onLeaving = onLeaving; // On user leaving the session
            wc.onPeerMessage = function(peerId, type) {
              onPeerMessage(peerId, type, wc);
            };
            if(config.setMyID) {
                config.setMyID({
                    myID: wc.myID
                });
            }
            // Open a Chainpad session
            realtime = createRealtime();

            // On sending message
            realtime.onMessage(function(message) {
                // Prevent Chainpad from sending authentication messages since it is handled by Netflux
                message = chainpadAdapter.msgOut(message, wc);
                if(message) {
                  wc.send(message).then(function() {
                    // Send the message back to Chainpad once it is sent to all peers if using the WebRTC protocol
                    if(rtc) { onMessage(wc.myID, message); }
                  });
                }
            });

            // Get the channel history
            var hc;
            if(rtc) {
              wc.channels.forEach(function (c) { if(!hc) { hc = c; } });
              if(hc) {
                wc.getHistory(hc.peerID);
              }
            }
            else {
              // TODO : Improve WebSocket service to use the latest Netflux's API
              wc.peers.forEach(function (p) { if (!hc || p.linkQuality > hc.linkQuality) { hc = p; } });
              hc.send(JSON.stringify(['GET_HISTORY', wc.id]));
            }

            // Check the connection to the channel
            if(!rtc) {
              // TODO
              // checkConnection(wc);
            }

            bindAllEvents(textarea, doc, onEvent, false);

            sharejs.attach(textarea, realtime);
            bump = realtime.bumpSharejs;

            realtime.start();
        };

        var createRTCChannel = function () {
            // Check if the WebRTC channel exists and create it if necessary
            var webchannel = Netflux.create();
            webchannel.openForJoining(options).then(function(data) {
                onOpen(webchannel);
                onReady(webchannel);
            }, function(error) {
                warn(error);
            });
        };

        var joinChannel = function() {
            // Connect to the WebSocket/WebRTC channel
            Netflux.join(channel, options).then(function(wc) {
                onOpen(wc);
            }, function(error) {
                if(rtc && error.code === 1008) {// Unexisting RTC channel
                    createRTCChannel();
                }
                else { warn(error); }
            });
        };
        joinChannel();

        var checkConnection = function(wc) {
            if(wc.channels && wc.channels.size > 0) {
                var channels = Array.from(wc.channels);
                var channel = channels[0];

                var socketChecker = setInterval(function () {
                    if (channel.checkSocket(realtime)) {
                        warn("Socket disconnected!");

                        recoverableErrorCount += 1;

                        if (recoverableErrorCount >= MAX_RECOVERABLE_ERRORS) {
                            warn("Giving up!");
                            realtime.abort();
                            try { channel.close(); } catch (e) { warn(e); }
                            if (config.onAbort) {
                                config.onAbort({
                                    socket: channel
                                });
                            }
                            if (socketChecker) { clearInterval(socketChecker); }
                        }
                    } else {
                        // it's working as expected, continue
                    }
                }, 200);
            }
        };

        return {
            onEvent: function () {
                onEvent();
            },
            bumpSharejs: function () { bump(); }
        };
    };
    return module.exports;
});
<commit_msg>Fix issue with Chrome and WebRTC<commit_after>/*
 * Copyright 2014 XWiki SAS
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
window.Reflect = { has: (x,y) => { return (y in x); } };
define([
    '/common/messages.js',
    '/common/netflux.js',
    '/common/crypto.js',
    '/common/toolbar.js',
    '/common/sharejs_textarea.js',
    '/common/chainpad.js',
    '/bower_components/jquery/dist/jquery.min.js',
], function (Messages, Netflux, Crypto, Toolbar, sharejs) {
    var $ = window.jQuery;
    var ChainPad = window.ChainPad;
    var PARANOIA = true;
    var module = { exports: {} };

    /**
     * If an error is encountered but it is recoverable, do not immediately fail
     * but if it keeps firing errors over and over, do fail.
     */
    var MAX_RECOVERABLE_ERRORS = 15;

    var debug = function (x) { console.log(x); },
        warn = function (x) { console.error(x); },
        verbose = function (x) { console.log(x); };
    verbose = function () {}; // comment out to enable verbose logging

    // ------------------ Trapping Keyboard Events ---------------------- //

    var bindEvents = function (element, events, callback, unbind) {
        for (var i = 0; i < events.length; i++) {
            var e = events[i];
            if (element.addEventListener) {
                if (unbind) {
                    element.removeEventListener(e, callback, false);
                } else {
                    element.addEventListener(e, callback, false);
                }
            } else {
                if (unbind) {
                    element.detachEvent('on' + e, callback);
                } else {
                    element.attachEvent('on' + e, callback);
                }
            }
        }
    };

    var bindAllEvents = function (textarea, docBody, onEvent, unbind)
    {
        /*
            we use docBody for the purposes of CKEditor.
            because otherwise special keybindings like ctrl-b and ctrl-i
            would open bookmarks and info instead of applying bold/italic styles
        */
        if (docBody) {
            bindEvents(docBody,
               ['textInput', 'keydown', 'keyup', 'select', 'cut', 'paste'],
               onEvent,
               unbind);
        }
        bindEvents(textarea,
                   ['mousedown','mouseup','click','change'],
                   onEvent,
                   unbind);
    };

    var getParameterByName = function (name, url) {
        if (!url) { url = window.location.href; }
        name = name.replace(/[\[\]]/g, "\\$&");
        var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
            results = regex.exec(url);
        if (!results) { return null; }
        if (!results[2]) { return ''; }
        return decodeURIComponent(results[2].replace(/\+/g, " "));
    };

    var start = module.exports.start =
        function (config)
    {
        var textarea = config.textarea;
        var websocketUrl = config.websocketURL;
        var webrtcUrl = config.webrtcURL;
        var userName = config.userName;
        var channel = config.channel;
        var cryptKey = config.cryptKey;
        var passwd = 'y';

        // make sure configuration is defined
        config = config || {};

        var doc = config.doc || null;

        // trying to deprecate onRemote, prefer loading it via the conf
        var onRemote = config.onRemote || null;

        // define this in case it gets called before the rest of our stuff is ready.
        var onEvent = function () { };

        var allMessages = [];
        var initializing = true;
        var recoverableErrorCount = 0;
        var bump = function () {};
        var messagesHistory = [];
        var chainpadAdapter = {};
        var realtime;

        var parseMessage = function (msg) {
            var res ={};
            // two or more? use a for
            ['pass','user','channelId','content'].forEach(function(attr){
                var len=msg.slice(0,msg.indexOf(':')),
                // taking an offset lets us slice out the prop
                // and saves us one string copy
                    o=len.length+1,
                    prop=res[attr]=msg.slice(o,Number(len)+o);
                // slice off the property and its descriptor
                msg = msg.slice(prop.length+o);
            });
            // content is the only attribute that's not a string
            res.content=JSON.parse(res.content);
            return res;
        };

        var mkMessage = function (user, channel, content) {
            content = JSON.stringify(content);
            return user.length + ':' + user +
                channel.length + ':' + channel +
                content.length + ':' + content;
        };

        var onPeerMessage = function(toId, type, wc) {
            if(type === 6) {
                messagesHistory.forEach(function(msg) {
                    wc.sendTo(toId, '1:y'+msg);
                });
                wc.sendTo(toId, '0');
            }
        };

        var whoami = new RegExp(userName.replace(/[\/\+]/g, function (c) {
            return '\\' +c;
        }));

        var onMessage = function(peer, msg, wc) {

            if(msg === 0 || msg === '0') {
                onReady(wc);
                return;
            }
            var message = chainpadAdapter.msgIn(peer, msg);

            verbose(message);
            allMessages.push(message);
            if (!initializing) {
                if (PARANOIA) {
                    onEvent();
                }
            }
            realtime.message(message);
            if (/\[5,/.test(message)) { verbose("pong"); }

            if (!initializing) {
                if (/\[2,/.test(message)) {
                    //verbose("Got a patch");
                    if (whoami.test(message)) {
                        //verbose("Received own message");
                    } else {
                        //verbose("Received remote message");
                        // obviously this is only going to get called if
                        if (onRemote) { onRemote(realtime.getUserDoc()); }
                    }
                }
            }
        };

        var userList = {
          onChange : function() {},
          users: []
        };
        var onJoining = function(peer) {
          var list = userList.users;
          if(list.indexOf(peer) === -1) {
            userList.users.push(peer);
          }
          userList.onChange();
        };

        var onLeaving = function(peer) {
          var list = userList.users;
          var index = list.indexOf(peer);
          if(index !== -1) {
            userList.users.splice(index, 1);
          }
          userList.onChange();
        };

        chainpadAdapter = {
            msgIn : function(peerId, msg) {
                var parsed = parseMessage(msg);
                // Remove the password from the message
                var passLen = msg.substring(0,msg.indexOf(':'));
                var message = msg.substring(passLen.length+1 + Number(passLen));
                try {
                    var decryptedMsg = Crypto.decrypt(message, cryptKey);
                    messagesHistory.push(decryptedMsg);
                    return decryptedMsg;
                } catch (err) {
                    return message;
                }

            },
            msgOut : function(msg, wc) {
                var parsed = parseMessage(msg);
                if(parsed.content[0] === 0) { // We're registering : send a REGISTER_ACK to Chainpad
                    onMessage('', '1:y'+mkMessage('', channel, [1,0]));
                    return;
                }
                if(parsed.content[0] === 4) { // PING message from Chainpad
                    parsed.content[0] = 5;
                    onMessage('', '1:y'+mkMessage(parsed.user, parsed.channelId, parsed.content));
                    wc.sendPing();
                    return;
                }
                return Crypto.encrypt(msg, cryptKey);
            }
        };

        var options = {
          key: channel
        };

        var rtc = true;

        if(!getParameterByName("webrtc") || !webrtcUrl) {
          rtc = false;
          options.signaling = websocketUrl;
          options.topology = 'StarTopologyService';
          options.protocol = 'WebSocketProtocolService';
          options.connector = 'WebSocketService';
          options.openWebChannel = true;
        }
        else {
          options.signaling = webrtcUrl;
        }

        var createRealtime = function() {
            return ChainPad.create(userName,
                                        passwd,
                                        channel,
                                        $(textarea).val(),
                                        {
                                        transformFunction: config.transformFunction
                                        });
        };

        var onReady = function(wc) {
            if(config.onInit) {
                config.onInit({
                    myID: wc.myID,
                    realtime: realtime,
                    webChannel: wc,
                    userList: userList
                });
            }
            // Trigger onJoining with our own Cryptpad username to tell the toolbar that we are synced
            onJoining(wc.myID);

            // we're fully synced
            initializing = false;

            // execute an onReady callback if one was supplied
            if (config.onReady) {
                config.onReady();
            }
        }

        var onOpen = function(wc) {
            // Add the handlers to the WebChannel
            wc.onmessage = function(peer, msg) { // On receiving message
                onMessage(peer, msg, wc);
            };
            wc.onJoining = onJoining; // On user joining the session
            wc.onLeaving = onLeaving; // On user leaving the session
            wc.onPeerMessage = function(peerId, type) {
              onPeerMessage(peerId, type, wc);
            };
            if(config.setMyID) {
                config.setMyID({
                    myID: wc.myID
                });
            }
            // Open a Chainpad session
            realtime = createRealtime();

            // On sending message
            realtime.onMessage(function(message) {
                // Prevent Chainpad from sending authentication messages since it is handled by Netflux
                message = chainpadAdapter.msgOut(message, wc);
                if(message) {
                  wc.send(message).then(function() {
                    // Send the message back to Chainpad once it is sent to all peers if using the WebRTC protocol
                    if(rtc) { onMessage(wc.myID, message); }
                  });
                }
            });

            // Get the channel history
            var hc;
            if(rtc) {
              wc.channels.forEach(function (c) { if(!hc) { hc = c; } });
              if(hc) {
                wc.getHistory(hc.peerID);
              }
            }
            else {
              // TODO : Improve WebSocket service to use the latest Netflux's API
              wc.peers.forEach(function (p) { if (!hc || p.linkQuality > hc.linkQuality) { hc = p; } });
              hc.send(JSON.stringify(['GET_HISTORY', wc.id]));
            }

            // Check the connection to the channel
            if(!rtc) {
              // TODO
              // checkConnection(wc);
            }

            bindAllEvents(textarea, doc, onEvent, false);

            sharejs.attach(textarea, realtime);
            bump = realtime.bumpSharejs;

            realtime.start();
        };

        var createRTCChannel = function () {
            // Check if the WebRTC channel exists and create it if necessary
            var webchannel = Netflux.create();
            webchannel.openForJoining(options).then(function(data) {
                onOpen(webchannel);
                onReady(webchannel);
            }, function(error) {
                warn(error);
            });
        };

        var joinChannel = function() {
            // Connect to the WebSocket/WebRTC channel
            Netflux.join(channel, options).then(function(wc) {
                onOpen(wc);
            }, function(error) {
                if(rtc && error.code === 1008) {// Unexisting RTC channel
                    createRTCChannel();
                }
                else { warn(error); }
            });
        };
        joinChannel();

        var checkConnection = function(wc) {
            if(wc.channels && wc.channels.size > 0) {
                var channels = Array.from(wc.channels);
                var channel = channels[0];

                var socketChecker = setInterval(function () {
                    if (channel.checkSocket(realtime)) {
                        warn("Socket disconnected!");

                        recoverableErrorCount += 1;

                        if (recoverableErrorCount >= MAX_RECOVERABLE_ERRORS) {
                            warn("Giving up!");
                            realtime.abort();
                            try { channel.close(); } catch (e) { warn(e); }
                            if (config.onAbort) {
                                config.onAbort({
                                    socket: channel
                                });
                            }
                            if (socketChecker) { clearInterval(socketChecker); }
                        }
                    } else {
                        // it's working as expected, continue
                    }
                }, 200);
            }
        };

        return {
            onEvent: function () {
                onEvent();
            },
            bumpSharejs: function () { bump(); }
        };
    };
    return module.exports;
});
<|endoftext|>


<commit_before>import bcrypt from 'bcrypt';
import { sign, verify } from 'jsonwebtoken';
import models from '../models';

const { User } = models;

/**
 * Finds a user by supplied credentials
 * @param {string} email The user's email
 * @param {string} password The user's password
 * @returns {Promise} resolved/rejected state
 */
export function findByEmailAndPassword(email, password) {
  return User.findOne({
    where: {
      email
    }
  })
    .then((user) => {
      if (!user) {
        return Promise.reject();
      }

      return bcrypt.compare(password, user.password)
        .then((isMatch) => {
          if (!isMatch) {
            return Promise.reject();
          }
          return Promise.resolve(user);
        })
        .catch(() => Promise.reject());
    });
}

/**
 * Finds a user by token
 * @param {string} token The user's token stored in the database
 * @returns {Promise | Object} resolved/rejected
 */
export function findByToken(token) {
  try {
    const decoded = verify(token, process.env.SECRET);
    return User.findOne({
      where: {
        $or: [{
          id: decoded.id
        }, {
          email: decoded.email
        }, {
          username: decoded.username
        }]
      }
    });
  } catch (error) {
    return Promise.reject(error);
  }
}

/**
 * Generates jsonwebtoken token for authentication
 * @param {string} id User's id stored in the database
 * @param {string} email User's email stored in the database
 * @returns {string} jsonwebtoken token
 */
export function generateAuthToken(id, email) {
  return sign({
    id,
    email
  }, process.env.SECRET, { expiresIn: '72 hours' });
}

/**
 * Verify jsonwebtoken token to check if it is valid
 * @param {string} token jsonwebtoken token
 * @returns {Object} valid or not valid state
 */
export function verifyToken(token) {
  const status = {
    error: '',
    ok: false
  };

  try {
    const decoded = verify(token, process.env.SECRET);

    if (decoded) {
      status.ok = true;
      return status;
    }
  } catch (error) {
    const { name } = error;

    switch (name) {
      case 'TokenExpiredError':
        status.error = 'Token expired';
        return status;
      case 'JsonWebTokenError':
        status.error = 'Invalid token signature';
        return status;
      default:
        return status;
    }
  }
}
<commit_msg>remove username check in findByToken method<commit_after>import bcrypt from 'bcrypt';
import { sign, verify } from 'jsonwebtoken';
import models from '../models';

const { User } = models;

/**
 * Finds a user by supplied credentials
 * @param {string} email The user's email
 * @param {string} password The user's password
 * @returns {Promise} resolved/rejected state
 */
export function findByEmailAndPassword(email, password) {
  return User.findOne({
    where: {
      email
    }
  })
    .then((user) => {
      if (!user) {
        return Promise.reject();
      }

      return bcrypt.compare(password, user.password)
        .then((isMatch) => {
          if (!isMatch) {
            return Promise.reject();
          }
          return Promise.resolve(user);
        })
        .catch(() => Promise.reject());
    });
}

/**
 * Finds a user by token
 * @param {string} token The user's token stored in the database
 * @returns {Promise | Object} resolved/rejected
 */
export function findByToken(token) {
  try {
    const decoded = verify(token, process.env.SECRET);
    return User.findOne({
      where: {
        $or: [{
          id: decoded.id
        }, {
          email: decoded.email
        }]
      }
    });
  } catch (error) {
    return Promise.reject(error);
  }
}

/**
 * Generates jsonwebtoken token for authentication
 * @param {string} id User's id stored in the database
 * @param {string} email User's email stored in the database
 * @returns {string} jsonwebtoken token
 */
export function generateAuthToken(id, email) {
  return sign({
    id,
    email
  }, process.env.SECRET, { expiresIn: '72 hours' });
}

/**
 * Verify jsonwebtoken token to check if it is valid
 * @param {string} token jsonwebtoken token
 * @returns {Object} valid or not valid state
 */
export function verifyToken(token) {
  const status = {
    error: '',
    ok: false
  };

  try {
    const decoded = verify(token, process.env.SECRET);

    if (decoded) {
      status.ok = true;
      return status;
    }
  } catch (error) {
    const { name } = error;

    switch (name) {
      case 'TokenExpiredError':
        status.error = 'Token expired';
        return status;
      case 'JsonWebTokenError':
        status.error = 'Invalid token signature';
        return status;
      default:
        return status;
    }
  }
}
<|endoftext|>


<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';
var DebugLogtron = require('debug-logtron');
var TChannelJSON = require('../../as/json');
var HyperbahnClient = require('../../hyperbahn/index.js');
var series = require('run-series');

module.exports = runTests;

if (require.main === module) {
    runTests(require('../lib/hyperbahn-cluster.js'));
}

function send(opts, done) {
    var tchannelJSON = TChannelJSON({
        logger: opts.logger
    });
    tchannelJSON.send(opts.bob.clientChannel.request({
        timeout: 500,
        serviceName: opts.steve.serviceName
    }), 'echo', null, 'hello', function onResponse(err, res) {
        if (opts.errOk) {
            err = null;
        }

        if (err) {
            opts.assert.end(err);
        }

        done(err, res);
    });
}

function waitFor(t) {
    return function wait(done) {
        setTimeout(done, 500);
    };
}

function runTests(HyperbahnCluster) {
    HyperbahnCluster.test('rps counter works', {
        size: 1,
        remoteConfig: {
            'rateLimiting.enabled': true,
            'rateLimiting.rateLimiterBuckets': 2,
            'rateLimiting.exemptServices': [
                'hyperbahn',
                'ringpop'
            ]
        }
    }, function t(cluster, assert) {
        var steve = cluster.remotes.steve;
        var bob = cluster.remotes.bob;

        var steveHyperbahnClient = new HyperbahnClient({
            reportTracing: false,
            serviceName: steve.serviceName,
            callerName: 'forward-test',
            hostPortList: cluster.hostPortList,
            tchannel: steve.channel,
            logger: DebugLogtron('hyperbahnClient')
        });
        steveHyperbahnClient.once('advertised', onAdvertised);
        steveHyperbahnClient.advertise();
        function onAdvertised() {
            var opts = {
                logger: cluster.logger,
                bob: bob,
                steve: steve,
                assert: assert
            };
            series([
                send.bind(null, opts),
                send.bind(null, opts),
                send.bind(null, opts),
                function check(done) {
                    cluster.apps.forEach(function (app) {
                        var relayChannel = app.clients.tchannel;
                        assert.equals(relayChannel.handler.rateLimiter.totalRequestCounter.rps, 3, 'total request');
                        assert.equals(relayChannel.handler.rateLimiter.counters.steve.rps, 3, 'request for steve');
                    });
                    done();
                }
            ], function done() {
                steveHyperbahnClient.destroy();
                assert.end();
            });
        }
    });

    HyperbahnCluster.test('rps counter works in 1.5 seconds', {
        size: 1,
        remoteConfig: {
            'rateLimiting.enabled': true,
            'rateLimiting.rateLimiterBuckets': 2,
            'rateLimiting.exemptServices': [
                'hyperbahn',
                'ringpop'
            ]
        }
    }, function t(cluster, assert) {
        var steve = cluster.remotes.steve;
        var bob = cluster.remotes.bob;

        var steveHyperbahnClient = new HyperbahnClient({
            reportTracing: false,
            serviceName: steve.serviceName,
            callerName: 'forward-test',
            hostPortList: cluster.hostPortList,
            tchannel: steve.channel,
            logger: DebugLogtron('hyperbahnClient')
        });
        steveHyperbahnClient.once('advertised', onAdvertised);
        steveHyperbahnClient.advertise();

        function onAdvertised() {
            var opts = {
                logger: cluster.logger,
                bob: bob,
                steve: steve,
                assert: assert
            };
            series([
                send.bind(null, opts),
                send.bind(null, opts),
                waitFor(500),
                send.bind(null, opts),
                function check1(done) {
                    cluster.apps.forEach(function (app) {
                        var relayChannel = app.clients.tchannel;
                        var rateLimiter = relayChannel.handler.rateLimiter;
                        assert.equals(rateLimiter.totalRequestCounter.rps, 3, 'check1: total request');
                        assert.equals(rateLimiter.counters.steve.rps, 3, 'check1: request for steve');
                    });
                    done();
                },

                waitFor(500),
                send.bind(null, opts),
                function check2(done) {
                    cluster.apps.forEach(function (app) {
                        var relayChannel = app.clients.tchannel;
                        var rateLimiter = relayChannel.handler.rateLimiter;
                        assert.equals(rateLimiter.totalRequestCounter.rps, 2, 'check2: total request');
                        assert.equals(rateLimiter.counters.steve.rps, 2, 'check2: request for steve');
                    });
                    done();
                }
            ], function done() {
                steveHyperbahnClient.destroy();
                assert.end();
            });
        }
    });

    HyperbahnCluster.test('service rate limiting works', {
        size: 1,
        kValue: 2,
        remoteConfig: {
            'rateLimiting.enabled': true,
            'rateLimiting.rateLimiterBuckets': 2,
            'rateLimiting.exemptServices': [
                'hyperbahn',
                'ringpop'
            ],
            'rateLimiting.rpsLimitForServiceName': {
                'steve': 2
            }
        }
    }, function t(cluster, assert) {
        var steve = cluster.remotes.steve;
        var bob = cluster.remotes.bob;

        var steveHyperbahnClient = new HyperbahnClient({
            reportTracing: false,
            serviceName: steve.serviceName,
            callerName: 'forward-test',
            hostPortList: cluster.hostPortList,
            tchannel: steve.channel,
            logger: DebugLogtron('hyperbahnClient')
        });
        steveHyperbahnClient.once('advertised', onAdvertised);
        steveHyperbahnClient.advertise();

        function onAdvertised() {
            var opts = {
                logger: cluster.logger,
                bob: bob,
                steve: steve,
                assert: assert
            };
            series([
                send.bind(null, opts),
                send.bind(null, opts),
                send.bind(null, opts),
                function sendError(done) {
                    var tchannelJSON = TChannelJSON({
                        logger: cluster.logger
                    });
                    tchannelJSON.send(bob.clientChannel.request({
                        timeout: 5000,
                        serviceName: steve.serviceName
                    }), 'echo', null, 'hello', function onResponse(err, res) {
                        assert.ok(err && err.type === 'tchannel.busy' &&
                            err.message === 'steve is rate-limited by the rps of 2',
                            'should be rate limited');
                        done();
                    });
                }
            ], function done() {
                steveHyperbahnClient.destroy();
                assert.end();
            });
        }
    });

    HyperbahnCluster.test('total rate limiting works', {
        size: 5,
        kValue: 1,
        remoteConfig: {
            'rateLimiting.enabled': true,
            'rateLimiting.rateLimiterBuckets': 2,
            'rateLimiting.totalRpsLimit': 2,
            'rateLimiting.exemptServices': [
                'hyperbahn',
                'ringpop'
            ]
        }
    }, function t(cluster, assert) {
        var steve = cluster.remotes.steve;
        var bob = cluster.remotes.bob;

        var steveHyperbahnClient = new HyperbahnClient({
            reportTracing: false,
            serviceName: steve.serviceName,
            callerName: 'forward-test',
            hostPortList: cluster.hostPortList,
            tchannel: steve.channel,
            logger: DebugLogtron('hyperbahnClient')
        });
        steveHyperbahnClient.once('advertised', onAdvertised);
        steveHyperbahnClient.advertise();

        function onAdvertised() {
            var opts = {
                logger: cluster.logger,
                bob: bob,
                steve: steve,
                assert: assert
            };
            series([
                send.bind(null, opts),
                send.bind(null, opts),
                waitFor(500),
                send.bind(null, opts),
                function sendError(done) {
                    var tchannelJSON = TChannelJSON({
                        logger: cluster.logger
                    });
                    tchannelJSON.send(bob.clientChannel.request({
                        timeout: 5000,
                        serviceName: steve.serviceName
                    }), 'echo', null, 'hello', function onResponse(err, res) {
                        assert.ok(err && err.type === 'tchannel.busy' &&
                            err.message === 'hyperbahn node is rate-limited by the total rps of 2',
                            'should be rate limited');
                        done();
                    });
                }
            ], function done() {
                steveHyperbahnClient.destroy();
                assert.end();
            });
        }
    });

    HyperbahnCluster.test('service exempt works', {
        size: 1,
        kValue: 1,
        remoteConfig: {
            'rateLimiting.enabled': true,
            'rateLimiting.rateLimiterBuckets': 2,
            'rateLimiting.totalRpsLimit': 2,
            'rateLimiting.exemptServices': [
                'hyperbahn',
                'ringpop',
                'bob'
            ]
        }
    }, function t(cluster, assert) {
        var steve = cluster.remotes.steve;
        var bob = cluster.remotes.bob;

        var steveHyperbahnClient = new HyperbahnClient({
            reportTracing: false,
            serviceName: steve.serviceName,
            callerName: 'forward-test',
            hostPortList: cluster.hostPortList,
            tchannel: steve.channel,
            logger: DebugLogtron('hyperbahnClient')
        });
        steveHyperbahnClient.once('advertised', onAdvertised);
        steveHyperbahnClient.advertise();

        function onAdvertised() {
            var opts = {
                logger: cluster.logger,
                bob: bob,
                steve: steve,
                assert: assert
            };
            var opts2 = {
                logger: cluster.logger,
                bob: bob,
                steve: steve,
                assert: assert,
                errOk: true
            };
            series([
                send.bind(null, opts),
                send.bind(null, opts),
                send.bind(null, opts2),
                function sendLast(done) {
                    var tchannelJSON = TChannelJSON({
                        logger: cluster.logger
                    });
                    tchannelJSON.send(steve.clientChannel.request({
                        timeout: 5000,
                        serviceName: bob.serviceName
                    }), 'echo', null, 'hello', function onResponse(err, res) {
                        assert.ok(!err, 'should be no error');
                        assert.equals(res.body, 'hello', 'body should be "hello"');
                        done();
                    });
                }
            ], function done() {
                steveHyperbahnClient.destroy();
                assert.end();
            });
        }
    });
}
<commit_msg>update the test for rate limiter counter stats<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';
var DebugLogtron = require('debug-logtron');
var TChannelJSON = require('../../as/json');
var HyperbahnClient = require('../../hyperbahn/index.js');
var series = require('run-series');

module.exports = runTests;

if (require.main === module) {
    runTests(require('../lib/hyperbahn-cluster.js'));
}

function send(opts, done) {
    var tchannelJSON = TChannelJSON({
        logger: opts.logger
    });
    tchannelJSON.send(opts.bob.clientChannel.request({
        timeout: 500,
        serviceName: opts.steve.serviceName
    }), 'echo', null, 'hello', function onResponse(err, res) {
        if (opts.errOk) {
            err = null;
        }

        if (err) {
            opts.assert.end(err);
        }

        done(err, res);
    });
}

function waitFor(t) {
    return function wait(done) {
        setTimeout(done, 500);
    };
}

function runTests(HyperbahnCluster) {
    HyperbahnCluster.test('rps counter works', {
        size: 1,
        remoteConfig: {
            'rateLimiting.enabled': true,
            'rateLimiting.rateLimiterBuckets': 2,
            'rateLimiting.exemptServices': [
                'hyperbahn',
                'ringpop'
            ]
        }
    }, function t(cluster, assert) {
        var steve = cluster.remotes.steve;
        var bob = cluster.remotes.bob;

        var steveHyperbahnClient = new HyperbahnClient({
            reportTracing: false,
            serviceName: steve.serviceName,
            callerName: 'forward-test',
            hostPortList: cluster.hostPortList,
            tchannel: steve.channel,
            logger: DebugLogtron('hyperbahnClient')
        });
        steveHyperbahnClient.once('advertised', onAdvertised);
        steveHyperbahnClient.advertise();
        function onAdvertised() {
            var opts = {
                logger: cluster.logger,
                bob: bob,
                steve: steve,
                assert: assert
            };
            series([
                send.bind(null, opts),
                send.bind(null, opts),
                send.bind(null, opts),
                function check(done) {
                    cluster.apps.forEach(function (app) {
                        var relayChannel = app.clients.tchannel;
                        assert.equals(relayChannel.handler.rateLimiter.totalRequestCounter.rps, 3, 'total request');
                        assert.equals(relayChannel.handler.rateLimiter.counters.steve.rps, 3, 'request for steve');
                        assert.equals(relayChannel.handler.rateLimiter.counters['bob~~steve'].rps, 3, 'request for bob~~steve');
                    });
                    done();
                }
            ], function done() {
                steveHyperbahnClient.destroy();
                assert.end();
            });
        }
    });

    HyperbahnCluster.test('rps counter works in 1.5 seconds', {
        size: 1,
        remoteConfig: {
            'rateLimiting.enabled': true,
            'rateLimiting.rateLimiterBuckets': 2,
            'rateLimiting.exemptServices': [
                'hyperbahn',
                'ringpop'
            ]
        }
    }, function t(cluster, assert) {
        var steve = cluster.remotes.steve;
        var bob = cluster.remotes.bob;

        var steveHyperbahnClient = new HyperbahnClient({
            reportTracing: false,
            serviceName: steve.serviceName,
            callerName: 'forward-test',
            hostPortList: cluster.hostPortList,
            tchannel: steve.channel,
            logger: DebugLogtron('hyperbahnClient')
        });
        steveHyperbahnClient.once('advertised', onAdvertised);
        steveHyperbahnClient.advertise();

        function onAdvertised() {
            var opts = {
                logger: cluster.logger,
                bob: bob,
                steve: steve,
                assert: assert
            };
            series([
                send.bind(null, opts),
                send.bind(null, opts),
                waitFor(500),
                send.bind(null, opts),
                function check1(done) {
                    cluster.apps.forEach(function (app) {
                        var relayChannel = app.clients.tchannel;
                        var rateLimiter = relayChannel.handler.rateLimiter;
                        assert.equals(rateLimiter.totalRequestCounter.rps, 3, 'check1: total request');
                        assert.equals(rateLimiter.counters.steve.rps, 3, 'check1: request for steve');
                        assert.equals(relayChannel.handler.rateLimiter.counters['bob~~steve'].rps, 3, 'check1: request for bob~~steve');
                    });
                    done();
                },

                waitFor(500),
                send.bind(null, opts),
                function check2(done) {
                    cluster.apps.forEach(function (app) {
                        var relayChannel = app.clients.tchannel;
                        var rateLimiter = relayChannel.handler.rateLimiter;
                        assert.equals(rateLimiter.totalRequestCounter.rps, 2, 'check2: total request');
                        assert.equals(rateLimiter.counters.steve.rps, 2, 'check2: request for steve');
                        assert.equals(relayChannel.handler.rateLimiter.counters['bob~~steve'].rps, 2, 'check2: request for bob~~steve');
                    });
                    done();
                }
            ], function done() {
                steveHyperbahnClient.destroy();
                assert.end();
            });
        }
    });

    HyperbahnCluster.test('service rate limiting works', {
        size: 1,
        kValue: 2,
        remoteConfig: {
            'rateLimiting.enabled': true,
            'rateLimiting.rateLimiterBuckets': 2,
            'rateLimiting.exemptServices': [
                'hyperbahn',
                'ringpop'
            ],
            'rateLimiting.rpsLimitForServiceName': {
                'steve': 2
            }
        }
    }, function t(cluster, assert) {
        var steve = cluster.remotes.steve;
        var bob = cluster.remotes.bob;

        var steveHyperbahnClient = new HyperbahnClient({
            reportTracing: false,
            serviceName: steve.serviceName,
            callerName: 'forward-test',
            hostPortList: cluster.hostPortList,
            tchannel: steve.channel,
            logger: DebugLogtron('hyperbahnClient')
        });
        steveHyperbahnClient.once('advertised', onAdvertised);
        steveHyperbahnClient.advertise();

        function onAdvertised() {
            var opts = {
                logger: cluster.logger,
                bob: bob,
                steve: steve,
                assert: assert
            };
            series([
                send.bind(null, opts),
                send.bind(null, opts),
                send.bind(null, opts),
                function sendError(done) {
                    var tchannelJSON = TChannelJSON({
                        logger: cluster.logger
                    });
                    tchannelJSON.send(bob.clientChannel.request({
                        timeout: 5000,
                        serviceName: steve.serviceName
                    }), 'echo', null, 'hello', function onResponse(err, res) {
                        assert.ok(err && err.type === 'tchannel.busy' &&
                            err.message === 'steve is rate-limited by the rps of 2',
                            'should be rate limited');
                        done();
                    });
                }
            ], function done() {
                steveHyperbahnClient.destroy();
                assert.end();
            });
        }
    });

    HyperbahnCluster.test('total rate limiting works', {
        size: 5,
        kValue: 1,
        remoteConfig: {
            'rateLimiting.enabled': true,
            'rateLimiting.rateLimiterBuckets': 2,
            'rateLimiting.totalRpsLimit': 2,
            'rateLimiting.exemptServices': [
                'hyperbahn',
                'ringpop'
            ]
        }
    }, function t(cluster, assert) {
        var steve = cluster.remotes.steve;
        var bob = cluster.remotes.bob;

        var steveHyperbahnClient = new HyperbahnClient({
            reportTracing: false,
            serviceName: steve.serviceName,
            callerName: 'forward-test',
            hostPortList: cluster.hostPortList,
            tchannel: steve.channel,
            logger: DebugLogtron('hyperbahnClient')
        });
        steveHyperbahnClient.once('advertised', onAdvertised);
        steveHyperbahnClient.advertise();

        function onAdvertised() {
            var opts = {
                logger: cluster.logger,
                bob: bob,
                steve: steve,
                assert: assert
            };
            series([
                send.bind(null, opts),
                send.bind(null, opts),
                waitFor(500),
                send.bind(null, opts),
                function sendError(done) {
                    var tchannelJSON = TChannelJSON({
                        logger: cluster.logger
                    });
                    tchannelJSON.send(bob.clientChannel.request({
                        timeout: 5000,
                        serviceName: steve.serviceName
                    }), 'echo', null, 'hello', function onResponse(err, res) {
                        assert.ok(err && err.type === 'tchannel.busy' &&
                            err.message === 'hyperbahn node is rate-limited by the total rps of 2',
                            'should be rate limited');
                        done();
                    });
                }
            ], function done() {
                steveHyperbahnClient.destroy();
                assert.end();
            });
        }
    });

    HyperbahnCluster.test('service exempt works', {
        size: 1,
        kValue: 1,
        remoteConfig: {
            'rateLimiting.enabled': true,
            'rateLimiting.rateLimiterBuckets': 2,
            'rateLimiting.totalRpsLimit': 2,
            'rateLimiting.exemptServices': [
                'hyperbahn',
                'ringpop',
                'bob'
            ]
        }
    }, function t(cluster, assert) {
        var steve = cluster.remotes.steve;
        var bob = cluster.remotes.bob;

        var steveHyperbahnClient = new HyperbahnClient({
            reportTracing: false,
            serviceName: steve.serviceName,
            callerName: 'forward-test',
            hostPortList: cluster.hostPortList,
            tchannel: steve.channel,
            logger: DebugLogtron('hyperbahnClient')
        });
        steveHyperbahnClient.once('advertised', onAdvertised);
        steveHyperbahnClient.advertise();

        function onAdvertised() {
            var opts = {
                logger: cluster.logger,
                bob: bob,
                steve: steve,
                assert: assert
            };
            var opts2 = {
                logger: cluster.logger,
                bob: bob,
                steve: steve,
                assert: assert,
                errOk: true
            };
            series([
                send.bind(null, opts),
                send.bind(null, opts),
                send.bind(null, opts2),
                function sendLast(done) {
                    var tchannelJSON = TChannelJSON({
                        logger: cluster.logger
                    });
                    tchannelJSON.send(steve.clientChannel.request({
                        timeout: 5000,
                        serviceName: bob.serviceName
                    }), 'echo', null, 'hello', function onResponse(err, res) {
                        assert.ok(!err, 'should be no error');
                        assert.equals(res.body, 'hello', 'body should be "hello"');
                        done();
                    });
                }
            ], function done() {
                steveHyperbahnClient.destroy();
                assert.end();
            });
        }
    });
}
<|endoftext|>


<commit_before>'use strict';

var kbox = require('../../lib/kbox.js');
var fw = kbox.install.framework;
var chai = require('chai');
var expect = chai.expect;

describe('install framework module', function() {

  before(function(beforeDone) {
    fw.registerStep(function(step) {
      step.name = 'a';
      step.description = 'step a';
      step.deps = ['b'];
      step.all = function(state) {
        state.foo += step.name;
      };
    });
    fw.registerStep(function(step) {
      step.name = 'b';
      step.description = 'step b';
      step.deps = [];
      step.all = function(state) {
        state.foo = step.name;
      };
    });
    fw.registerStep(function(step, done) {
      step.name = 'c';
      step.description = 'step c';
      step.deps = ['a', 'd'];
      step.all = function(state, next) {
        state.foo += step.name;
        setTimeout(function() {
          next();
        }, 300);
      };
      done();
    });
    fw.registerStep(function(step, done) {
      step.name = 'd';
      step.description = 'step d';
      step.deps = ['a'];
      step.all = function(state, next) {
        state.foo += step.name;
        next();
      };
      done();
    });
    fw.registerStep(function(step, done) {
      step.name = 'e';
      step.description = 'step e';
      step.deps = [];
      step.all.win32 = function(state, next) {
        state.foo += step.name;
        next();
      };
      done();
    });
    fw.registerStep(function(step, done) {
      step.name = 'f';
      step.description = 'step f';
      step.deps = ['a'];
      step.all.linux = function(state, next) {
        state.foo += step.name;
        next();
      };
      done();
      beforeDone();
    });
  });

  describe('#getSteps', function() {

    it('should sort steps based upon dependencies.', function() {
      var steps = fw.getSteps('darwin');
      expect(steps.length).to.equal(4);
      expect(steps[0].name).to.equal('b');
      expect(steps[1].name).to.equal('a');
      expect(steps[2].name).to.equal('d');
      expect(steps[3].name).to.equal('c');
    });

    it('should handle win32 correctly.', function() {
      var steps = fw.getSteps('win32');
      expect(steps.length).to.equal(5);
      expect(steps[0].name).to.equal('b');
      expect(steps[1].name).to.equal('a');
      expect(steps[2].name).to.equal('d');
      expect(steps[3].name).to.equal('c');
      expect(steps[4].name).to.equal('e');
    });

  });

  describe('#getInstall', function() {

    it('should run the correct steps in the correct order.', function(done) {
      var install = fw.getInstall('darwin');
      var preStepLog = '';
      fw.events.on('pre-step', function(step) {
        preStepLog += step.name;
      });
      var postStepLog = '';
      fw.events.on('post-step', function(step) {
        postStepLog += step.name;
      });
      install(function(err, state) {
        expect(err).to.equal(undefined);
        expect(state.foo).to.equal('badc');
        expect(preStepLog).to.equal('badc');
        expect(postStepLog).to.equal('badc');
        done();
      });
    });

  });

});
<commit_msg>Fixing unit tests for install/framework<commit_after>'use strict';

var kbox = require('../../lib/kbox.js');
var fw = kbox.install.framework;
var chai = require('chai');
var expect = chai.expect;

describe('install framework module', function() {

  before(function(beforeDone) {
    fw.registerStep(function(step) {
      step.name = 'a';
      step.description = 'step a';
      step.deps = ['b'];
      step.all = function(state) {
        state.foo += step.name;
      };
    });
    fw.registerStep(function(step) {
      step.name = 'b';
      step.description = 'step b';
      step.deps = [];
      step.all = function(state) {
        state.foo = step.name;
      };
    });
    fw.registerStep(function(step, done) {
      step.name = 'c';
      step.description = 'step c';
      step.deps = ['a', 'd'];
      step.all = function(state, next) {
        state.foo += step.name;
        setTimeout(function() {
          next();
        }, 300);
      };
      done();
    });
    fw.registerStep(function(step, done) {
      step.name = 'd';
      step.description = 'step d';
      step.deps = ['a'];
      step.all = function(state, next) {
        state.foo += step.name;
        next();
      };
      done();
    });
    fw.registerStep(function(step, done) {
      step.name = 'e';
      step.description = 'step e';
      step.deps = [];
      step.all.win32 = function(state, next) {
        state.foo += step.name;
        next();
      };
      done();
    });
    fw.registerStep(function(step, done) {
      step.name = 'f';
      step.description = 'step f';
      step.deps = ['a'];
      step.all.linux = function(state, next) {
        state.foo += step.name;
        next();
      };
      done();
      beforeDone();
    });
  });

  describe('#getSteps', function() {

    it('should sort steps based upon dependencies.', function() {
      var steps = fw.getSteps('darwin');
      expect(steps.length).to.equal(4);
      expect(steps[0].name).to.equal('b');
      expect(steps[1].name).to.equal('a');
      expect(steps[2].name).to.equal('d');
      expect(steps[3].name).to.equal('c');
    });

    it('should handle win32 correctly.', function() {
      var steps = fw.getSteps('win32');
      expect(steps.length).to.equal(5);
      expect(steps[0].name).to.equal('b');
      expect(steps[1].name).to.equal('a');
      expect(steps[2].name).to.equal('d');
      expect(steps[3].name).to.equal('c');
      expect(steps[4].name).to.equal('e');
    });

  });

  describe('#getInstall', function() {

    it('should run the correct steps in the correct order.', function(done) {
      var install = fw.getInstall('darwin');
      var state = {};
      var preStepLog = '';
      fw.events.on('pre-step', function(step) {
        preStepLog += step.name;
      });
      var postStepLog = '';
      fw.events.on('post-step', function(step) {
        postStepLog += step.name;
      });
      fw.events.on('error', function(err) {
        throw err;
      });
      fw.events.on('end', function(state) {
        expect(state.foo).to.equal('badc');
        expect(preStepLog).to.equal('badc');
        expect(postStepLog).to.equal('badc');
        done();
      });
      install(state);
    });

  });

});
<|endoftext|>


<commit_before>function queryStatus(appendix, secret)
{
    jQuery.ajax({
        url:    '/api/extendedgitgraph::status?secret='+secret,
        success: function(result)
        {
            let ajaxOutput = $('#egg_ajaxOutput');
            ajaxOutput.val(result + '\r\n' + appendix);
            ajaxOutput.scrollTop(ajaxOutput[0].scrollHeight);
        },
        async:   true
    });
}

function startAjaxRefresh(secret)
{
    $('#egg_ajaxOutput').val("Started.");
    val = setInterval(function(){ queryStatus('', secret); }, 500);

    jQuery.ajax({
        url:    '/api/extendedgitgraph::refresh?secret='+secret,
        success: function(result)
        {
            clearInterval(val);
            queryStatus('Finished.', secret);
        },
        error: function( jqXHR, textStatus, errorThrown)
        {
            clearInterval(val);
            queryStatus('AN ERROR OCCURED:' + '\r\n' + textStatus, secret);
        },
        async:   true
    });
}

function startAjaxRedraw(secret)
{
    $('#egg_ajaxOutput').val("Started.");
    val = setInterval(function(){ queryStatus('', secret); }, 500);

    jQuery.ajax({
        url:    '/api/extendedgitgraph::redraw?secret='+secret,
        success: function(result)
        {
            clearInterval(val);
            queryStatus('Finished.', secret);
        },
        error: function( jqXHR, textStatus, errorThrown)
        {
            clearInterval(val);
            queryStatus('AN ERROR OCCURED:' + '\r\n' + textStatus, secret);
        },
        async:   true
    });
}

function startAjaxReplace(target, url)
{
    $(target).html("Waiting ...");
    jQuery.ajax({
        url:    url,
        success: function(result)
        {
            $(target).html(result);
        },
        error: function( jqXHR, textStatus, errorThrown)
        {
            $(target).html('AN ERROR OCCURED:' + '
' + textStatus);
        },
        async:   true
    });
}

function showSelfTestOutput(id1, id2)
{
    if (!$(id1).hasClass('consistency_result_fin')) return;

    if ($(id2).hasClass('generic_nodisplay'))
    {
        $('.selftest_outputchild').addClass('generic_nodisplay');
        $(id2).removeClass('generic_nodisplay');
    }
    else
    {
        $('.selftest_outputchild').addClass('generic_nodisplay');
    }

}

function refreshConsistencyDisplaySequential(skip)
{
    let i = 0;
    for (let apibutton of $('.selftest_sequential .consistence_ajax_handler').toArray())
    {
        if (i++ !== skip) continue;

        const filter = $(apibutton).data('filter');
        const outdiv = $($(apibutton).data('stid'));

        $(apibutton).removeClass('consistency_result_intermed');
        $(apibutton).addClass('consistency_result_running');

        $.ajax('/api/site::selftest?filter=' + filter)
            .done((data, status, xhr) =>
            {
                let json = JSON.parse(data);
                $(apibutton).removeClass('consistency_result_intermed');
                $(apibutton).removeClass('consistency_result_running');
                $(apibutton).addClass('consistency_result_fin');

                if (json.result === 0) $(apibutton).addClass('consistency_result_ok');
                if (json.result === 1) $(apibutton).addClass('consistency_result_warn');
                if (json.result === 2) $(apibutton).addClass('consistency_result_err');

                $(apibutton).text(json.message);
                //$(apibutton).attr('title', json.long);
                outdiv.text(json.long);

                setTimeout(() => refreshConsistencyDisplaySequential(skip+1), 10);
            })
            .fail((xhr, status, err) =>
            {
                $(apibutton).removeClass('consistency_result_intermed');
                $(apibutton).removeClass('consistency_result_running');

                $(apibutton).addClass('consistency_result_err');
                $(apibutton).addClass('consistency_result_fin');
                $(apibutton).text(("" + err).substr(0, 48));

                //$(apibutton).attr('title', json.long);
                outdiv.text(err);

                setTimeout(() => refreshConsistencyDisplaySequential(skip+1), 10);
            });

    }
}

function refreshConsistencyDisplayParallel()
{
    for (let apibutton of $('.selftest_parallel .consistence_ajax_handler').toArray())
    {
        const filter = $(apibutton).data('filter');

        $(apibutton).removeClass('consistency_result_intermed');
        $(apibutton).addClass('consistency_result_running');

        $.ajax('/api/site::selftest?filter=' + filter)
            .done((data, status, xhr) =>
            {
                let json = JSON.parse(data);

                if (json.result === 0) $(apibutton).addClass('consistency_result_ok');
                if (json.result === 1) $(apibutton).addClass('consistency_result_warn');
                if (json.result === 2) $(apibutton).addClass('consistency_result_err');

                $(apibutton).removeClass('consistency_result_running');

                $(apibutton).text(json.message);
                $(apibutton).attr('title', json.long);
            })
            .fail((xhr, status, err) =>
            {
                $(apibutton).removeClass('consistency_result_intermed');
                $(apibutton).removeClass('consistency_result_running');

                $(apibutton).addClass('consistency_result_err');
                $(apibutton).text(err);
            });
    }
}

$(function()
{
    for (let apibutton of $('.selftest_sequential').toArray()) setTimeout(() => refreshConsistencyDisplaySequential(0), 200);
    for (let apibutton of $('.selftest_parallel').toArray())   setTimeout(() => refreshConsistencyDisplayParallel(), 200);
});<commit_msg>fix admin.js<commit_after>function queryStatus(appendix, secret)
{
    jQuery.ajax({
        url:    '/api/extendedgitgraph::status?secret='+secret,
        success: function(result)
        {
            let ajaxOutput = $('#egg_ajaxOutput');
            ajaxOutput.val(result + '\r\n' + appendix);
            ajaxOutput.scrollTop(ajaxOutput[0].scrollHeight);
        },
        async:   true
    });
}

function startAjaxRefresh(secret)
{
    $('#egg_ajaxOutput').val("Started.");
    val = setInterval(function(){ queryStatus('', secret); }, 500);

    jQuery.ajax({
        url:    '/api/extendedgitgraph::refresh?secret='+secret,
        success: function(result)
        {
            clearInterval(val);
            queryStatus('Finished.', secret);
        },
        error: function( jqXHR, textStatus, errorThrown)
        {
            clearInterval(val);
            queryStatus('AN ERROR OCCURED:' + '\r\n' + textStatus, secret);
        },
        async:   true
    });
}

function startAjaxRedraw(secret)
{
    $('#egg_ajaxOutput').val("Started.");
    val = setInterval(function(){ queryStatus('', secret); }, 500);

    jQuery.ajax({
        url:    '/api/extendedgitgraph::redraw?secret='+secret,
        success: function(result)
        {
            clearInterval(val);
            queryStatus('Finished.', secret);
        },
        error: function( jqXHR, textStatus, errorThrown)
        {
            clearInterval(val);
            queryStatus('AN ERROR OCCURED:' + '\r\n' + textStatus, secret);
        },
        async:   true
    });
}

function startAjaxReplace(target, url)
{
    $(target).html("Waiting ...");
    jQuery.ajax({
        url:    url,
        success: function(result)
        {
            $(target).html(result);
        },
        error: function( jqXHR, textStatus, errorThrown)
        {
            $(target).html('AN ERROR OCCURED:' + '
' + textStatus);
        },
        async:   true
    });
}

function showSelfTestOutput(id1, id2)
{
    if (!$(id1).hasClass('consistency_result_fin')) return;

    if ($(id2).hasClass('generic_nodisplay'))
    {
        $('.selftest_outputchild').addClass('generic_nodisplay');
        $(id2).removeClass('generic_nodisplay');
    }
    else
    {
        $('.selftest_outputchild').addClass('generic_nodisplay');
    }

}

function refreshConsistencyDisplaySequential(skip)
{
    let i = 0;
    for (let apibutton of $('.selftest_sequential .consistence_ajax_handler').toArray())
    {
        if (i++ !== skip) continue;

        const filter = $(apibutton).data('filter');
        const outdiv = $($(apibutton).data('stid'));

        $(apibutton).removeClass('consistency_result_intermed');
        $(apibutton).addClass('consistency_result_running');

        $.ajax('/api/site::selftest?filter=' + filter)
            .done((data, status, xhr) =>
            {
                let json = JSON.parse(data);
                $(apibutton).removeClass('consistency_result_intermed');
                $(apibutton).removeClass('consistency_result_running');
                $(apibutton).addClass('consistency_result_fin');

                if (json.result === 0) $(apibutton).addClass('consistency_result_ok');
                if (json.result === 1) $(apibutton).addClass('consistency_result_warn');
                if (json.result === 2) $(apibutton).addClass('consistency_result_err');

                $(apibutton).text(json.message);
                //$(apibutton).attr('title', json.long);
                outdiv.text(json.long);

                setTimeout(() => refreshConsistencyDisplaySequential(skip+1), 10);
            })
            .fail((xhr, status, err) =>
            {
                $(apibutton).removeClass('consistency_result_intermed');
                $(apibutton).removeClass('consistency_result_running');

                $(apibutton).addClass('consistency_result_err');
                $(apibutton).addClass('consistency_result_fin');
                $(apibutton).text(("" + err).substr(0, 48));

                //$(apibutton).attr('title', json.long);
                outdiv.text(err);

                setTimeout(() => refreshConsistencyDisplaySequential(skip+1), 10);
            });

    }
}

function refreshConsistencyDisplayParallel()
{
    for (let apibutton of $('.selftest_parallel .consistence_ajax_handler').toArray())
    {
        const filter = $(apibutton).data('filter');

        $(apibutton).removeClass('consistency_result_intermed');
        $(apibutton).addClass('consistency_result_running');

        $.ajax('/api/site::selftest?filter=' + filter)
            .done((data, status, xhr) =>
            {
                let json = JSON.parse(data);

                if (json.result === 0) $(apibutton).addClass('consistency_result_ok');
                if (json.result === 1) $(apibutton).addClass('consistency_result_warn');
                if (json.result === 2) $(apibutton).addClass('consistency_result_err');

                $(apibutton).removeClass('consistency_result_running');
                $(apibutton).addClass('consistency_result_fin');

                $(apibutton).text(json.message);
                $(apibutton).attr('title', json.long);
            })
            .fail((xhr, status, err) =>
            {
                $(apibutton).removeClass('consistency_result_intermed');
                $(apibutton).removeClass('consistency_result_running');

                $(apibutton).addClass('consistency_result_err');
                $(apibutton).addClass('consistency_result_fin');
                $(apibutton).text(err);
            });
    }
}

$(function()
{
    for (let apibutton of $('.selftest_sequential').toArray()) setTimeout(() => refreshConsistencyDisplaySequential(0), 200);
    for (let apibutton of $('.selftest_parallel').toArray())   setTimeout(() => refreshConsistencyDisplayParallel(), 200);
});<|endoftext|>


<commit_before>/**
 * The Footer view.
 */
define([
  'jquery',
  'backbone',
  'underscore',
  'mps',
  'slick'
], function($,Backbone, _,mps, slick) {

  'use strict';

  var FooterView = Backbone.View.extend({

    el: '#footerView',

    initialize: function() {
      // CACHE
      this.$logos = $('#footer-logos');

      // this.$logos.slick({
      //   infinite: true,
      //   slidesToShow: 5,
      //   slidesToScroll: 5,
      //   speed: 500,
      //   autoplay: true,
      //   autoplaySpeed: 3000
      // });
    },

  });

  return FooterView;

});
<commit_msg>testing deploy IV<commit_after>/**
 * The Footer view.
 */
define([
  'jquery',
  'backbone'
  // 'slick'
], function($,Backbone) {

  'use strict';

  var FooterView = Backbone.View.extend({

    el: '#footerView',

    initialize: function() {
      // CACHE
      this.$logos = $('#footer-logos');

      // this.$logos.slick({
      //   infinite: true,
      //   slidesToShow: 5,
      //   slidesToScroll: 5,
      //   speed: 500,
      //   autoplay: true,
      //   autoplaySpeed: 3000
      // });
    },

  });

  return FooterView;

});
<|endoftext|>