/**
 * Created by esso on 04.11.15.
 * Middleware: Controls if request needs token, and if that token is valid.
 * Probably should be replaced with Passport.
 */
var stndResponse = require('../helpers/standardResponses'),
    Tokens = require('../models/tokens'),
    _ = require('underscore');

var LEGAL_PATHS = ['/login', '/invite', '/forgotpassword', '/resetpassword' ];

var validate = function (req, res, next) {
    // If request is not of method OPTIONS or is a request that's legal, check the token
    if (req.method === 'OPTIONS' || isLegalPath(req.path) // Regular methods
        || (req.method === 'POST' &&  (req.path === '/api/users' || req.path === '/api/users/') ) )  // Registration
        return next();
    else if (req.method !== 'OPTIONS' && ( req.body.token || req.query.token) ) {
        var token = (req.body.token ? req.body.token : req.query.token); // Either body-token or query token
        return Tokens.isValid(token, function (tokenIsValid) {
            if (tokenIsValid) {
                return next(); // Go on
            }
            return stndResponse.invalidToken(res); // Invalid token
        });
    }
    return stndResponse.invalidToken(res); // Invalid token
};

var isLegalPath =  function(path){
    if(path === '/api' || path === '/api/') return true;
    return _.each(LEGAL_PATHS, function (item, index) {
        if('/api' + item  === path || '/api' + item  + '/' ===  path) return true;
        if (index +1 === LEGAL_PATHS.length) return false;
    });
};

module.exports = {
    validate: validate
};
@@ -524,230 +524,8 @@
 hod 
-=== 'OPTIONS' %7C%7C isLegalPath(req.path) // Regular methods%0A        %7C%7C (req.method === 'POST' &&  (req.path === '/api/users' %7C%7C req.path === '/api/users/') ) )  // Registration%0A        return next();%0A    else if (req.method 
 !== 
@@ -574,24 +574,24 @@
 .token) ) %7B%0A
+
         var 
@@ -774,32 +774,144 @@
 tokenIsValid) %7B%0A
+                req.body = cleanObjForToken(req.body);%0A                req.query = cleanObjForToken(req.query);%0A
                 
@@ -1030,24 +1030,177 @@
   %7D);%0A    %7D%0A
+    else if (req.method === 'OPTIONS' %7C%7C isLegalPath(req.path)%7C%7C isRegistrationRequest(req) ) // Registration and Regular methods%0A        return next();%0A
     return s
@@ -1541,16 +1541,16 @@
  false;%0A
-
     %7D);%0A
@@ -1553,16 +1553,266 @@
 %7D);%0A%7D;%0A%0A
+var cleanObjForToken = function (obj) %7B%0A    newObj = obj;%0A    delete newObj.token;%0A    return newObj;%0A%7D;%0A%0Avar isRegistrationRequest = function (req) %7B%0A    return req.method === 'POST' &&  (req.path === '/api/users' %7C%7C req.path === '/api/users/')%0A%7D;%0A%0A
 module.e

Clean query and body for token-value in middleware.