var model = require('../models');
var Database = require('../persistence/mongo');
var db = new Database();

function getAuthInfo(req) {
  var encoded = req.headers.authorization.split(' ')[1];
  var decoded = new Buffer(encoded, 'base64').toString('utf8');

  var username = decoded.split(':')[0];
  var password = decoded.split(':')[1];
  return {username: username, password: password};
}

module.exports = function (app) {
  return function (server) {
    server.on('connection', function (socket) {
      if(!socket.upgradeReq.headers.authorization || socket.upgradeReq.headers.authorization === undefined){
        socket.send(JSON.stringify({error: "no auth"}));
        return socket.close();
      }
      var userInfo = getAuthInfo(socket.upgradeReq);
      var authInfo = {};

      model.User.findOne({where: {name: userInfo.username}}).then(function (user) {
        if (!user) {
          socket.send(JSON.stringify({error: "auth failure"}));
          return socket.close();
        }
        user.comparePassword(userInfo.password, function (err, result) {
          if (result) {
            socket.send("connection");
            authInfo = result;
          } else {
            socket.send(JSON.stringify({error: "auth failure"}));
            return socket.close();
          }
        });
      });
      socket.on('subscribe', function (topic) {
        db.subscribe({name: authInfo.name, token: authInfo.uid}, function (dbResult) {
          socket.send(JSON.stringify(dbResult));
        });
      });
      return socket.on('disconnect', function () {
        console.log('disconnect');
      });
    })
  };
};

@@ -99,16 +99,58 @@
 abase();
+%0Avar authCheck = require('../auth/basic');
 %0A%0Afuncti
@@ -383,20 +383,16 @@
 return %7B
-user
 name: us
@@ -822,115 +822,174 @@
 %7D;%0A%0A
+%0A
       
-model.User.findOne(%7Bwhere: %7Bname: userInfo.username%7D%7D).then(function (user) %7B%0A        if (!user
+var noUserCB = function () %7B%0A        socket.send(JSON.stringify(%7Berror: %22auth failure%22%7D));%0A        socket.close();%0A      %7D;%0A%0A      var errorCB = function (
 ) %7B%0A
-  
     
@@ -1050,33 +1050,24 @@
 ));%0A        
-  return 
 socket.close
@@ -1080,59 +1080,33 @@
     
-  %7D
+%7D;%0A
 %0A      
-  user.comparePassword(userInfo.password,
+var successCB =
  fun
@@ -1116,13 +1116,8 @@
 on (
-err, 
 resu
@@ -1126,36 +1126,8 @@
 ) %7B%0A
-          if (result) %7B%0A    
     
@@ -1165,20 +1165,16 @@
         
-   
- 
 authInfo
@@ -1194,155 +1194,69 @@
     
-    %7D else %7B%0A            socket.send(JSON.stringify(%7Berror: %22auth failure%22%7D));%0A            return socket.close();%0A          %7D%0A        %7D);%0A      %7D);
+%7D;%0A%0A      authCheck(userInfo, noUserCB, successCB, errorCB);%0A
 %0A   

REFACTOR AUTH: WEBSOCKET