'use strict';

const CMDS = require('../utils').COMMANDS;


class Middleware {
    constructor(server) {
        this._middleware = [];
        this.server = server;

        this.addMiddleware(require('./firewall'));
        this.addMiddleware(require('./auth'));
    }

    addMiddleware(middleware) {
        this._middleware.push(middleware);
    }

    /**
     * Handle hanshake pahse of a new connection.
     * We run the socket by all the different 
     * middleware layers.
     * 
     * @param {net.Socket} socket 
     * @return {void}
     */
    handshake(socket) {
        const server = this.server,
            config = this.server.config,
            middleware = this._middleware;

        function reject(msg = 'authentication-failed') {
            server.logger.info('- reject');
            server.onConnectionRejected(socket, msg);
        }

        function connect() {
            server.logger.info('- connect');
            server.onConnectionComplete(socket);
        }

        function step() {
            function next(err) {
                if (err) reject(err);
                else step();
            }
            
            const m = middleware.shift();
            if (m) m(socket, config, next);
            else connect();
        }

        step();
    }
}

module.exports = Middleware;

@@ -52,16 +52,143 @@
 MANDS;%0A%0A
+/**%0A * Middleware manages connection middleware%0A * to accepts connections.%0A * %0A * Default middleware are firewall and auth.%0A */
 %0Aclass M
@@ -199,16 +199,17 @@
 eware %7B%0A
+%0A
     cons
@@ -699,24 +699,33 @@
 e(socket) %7B%0A
+        %0A
         cons
@@ -868,22 +868,18 @@
  = '
-authentication
+middleware
 -fai

fix middleware error message