2017-06-10 7 views
0

イム呼び出さ表現し、私は非常識な私を運転問題を抱えている:ルート/既存のプロジェクトに取り組んで二回

のルートが呼ばれる任意の経路があまりにも取る際にこの問題が発生し、二回または多分より呼ばなっています私はルートが少ない中で(高速応答しない場合、問題は、このファイルにダイナミックルーティングの試みはconsole.log(タッチ)が二回呼び出されるという事実で

  var express = require('express'); 
      var recaptcha = require('express-recaptcha'); 
      //Site key, Secret key 
      recaptcha.init('xxxxx', 'yyyyy'); 
      /** 
      * Routes middleware 
      * Check all requests 
      */ 
      module.exports = function(app, passport, memoryCache) { 

       var router = express.Router(); 
       var config = require('app/config/settings.js'); 

       router.use(function(req, res, next) { 

       console.log("touch"); 
       console.log(req.url); 
       /** 
       * Make visible req/res on template layout 
       */ 
       res.locals.req = req; 
       res.locals.res = res; 
       /** 
       * Url filter 
       */ 
       var aryUrl = req.path.split('/').filter(Boolean); 

       try { 

        var root = ''; 
        var controller = ''; 
        var controllerPrototype = ''; 
        var module = ''; 
        var method = ''; 
        var url = ''; 
        var itemId = ''; 
        var privacity = ''; 
        var session = ''; 

        switch (req.originalMethod) { 
        case 'GET': 
         method = 'get'; 
         break; 
        case 'POST': 
         method = 'post'; 
         break; 
        case 'PUT': 
         method = 'put'; 
         break; 
        case 'DELETE': 
         method = 'delete'; 
         break; 
        } 

        if (aryUrl.length == 0) { 
        root = '/'; 
        } else { 
        root = aryUrl[0]; 
        } 

        switch (root) { 
        case '/': 
         privacity = 'private'; 
         session = 'General'; 
         module = 'app/controllers/indexController'; 
         controller = 'index'; 
         controllerPrototype = 'root'; 
         url = '/'; 

         break; 
        case 'index': 
         privacity = 'private'; 
         session = 'General'; 
         module = 'app/controllers/indexController'; 
         controller = 'index'; 
         controllerPrototype = aryUrl[1]; 
         url = '/index/' + aryUrl[1]; 

         break; 
        case 'evaluaciones': 
         privacity = 'private'; 
         session = 'PortalEval'; 
         module = 'app/controllers/view-private/portalEvaluacionController'; 
         controller = 'portalEvaluacion'; 
         controllerPrototype = 'view'; 
         url = '/evaluaciones'; 

         if (aryUrl.length == 2) { 
          if (aryUrl[1] === 'antesdelcurso' || aryUrl[1] === 'despuesdelcurso') { 
           url = url + '/' + aryUrl[1]; 
          } else { 
           controller = ''; 
          } 
         } 
         break; 
        case 'relatores': 
         privacity = 'private'; 
         session = 'RelatorEval'; 
         module = 'app/controllers/portalRelatoresIndexController'; 
         controller = 'portalRelatores'; 
         controllerPrototype = 'view'; 
         url = '/relatores'; 
         break; 
        case 'api-pc': 
         privacity = 'public'; 
         session = (req.user)? req.user.tipoSession : ''; 
         var ctrl = aryUrl[1].replace(/\W+(.)/g, function(x, chr) { 
         return chr.toUpperCase(); 
         }); 
         ctrl = 'api' + ctrl.charAt(0).toUpperCase() + ctrl.slice(1); 

         module = 'app/controllers/api-public/' + ctrl + 'Controller'; 
         controller = ctrl; 

         if (aryUrl.length == 4) { 
         itemId = '/:id'; 
         } 

         controllerPrototype = aryUrl[2]; 

         url = '/api-pc/' + aryUrl[1] + '/' + aryUrl[2] + itemId; 

         break; 
        case 'api-pt': 
         privacity = 'private'; 
         session = (req.user)? req.user.tipoSession : ''; 
         var ctrl = aryUrl[1].replace(/\W+(.)/g, function(x, chr) { 
         return chr.toUpperCase(); 
         }); 
         ctrl = 'api' + ctrl.charAt(0).toUpperCase() + ctrl.slice(1); 

         module = 'app/controllers/api-private/' + ctrl + 'Controller'; 
         controller = ctrl; 

         if (aryUrl.length == 4) { 
         itemId = '/:id'; 
         } 

         controllerPrototype = aryUrl[2]; 

         url = '/api-pt/' + aryUrl[1] + '/' + aryUrl[2] + itemId; 

         break; 
        case 'view-pc': 
         privacity = 'public'; 
         session = (req.user)? req.user.tipoSession : ''; 
         var ctrl = aryUrl[1].replace(/\W+(.)/g, function(x, chr) { 
         return chr.toUpperCase(); 
         }); 

         module = 'app/controllers/view-public/' + ctrl + 'Controller'; 
         controller = ctrl; 

         if (aryUrl.length == 4) { 
         itemId = '/:id'; 
         } 

         controllerPrototype = aryUrl[2]; 

         url = '/view-pc/' + aryUrl[1] + '/' + aryUrl[2] + itemId; 

         break; 
        case 'view-pt': 
         privacity = 'private'; 
         session = (req.user)? req.user.tipoSession : ''; 
         var ctrl = aryUrl[1].replace(/\W+(.)/g, function(x, chr) { 
         return chr.toUpperCase(); 
         }); 

         module = 'app/controllers/view-private/' + ctrl + 'Controller'; 
         controller = ctrl; 

         if (aryUrl.length == 4) { 
         itemId = '/:id'; 
         } 

         controllerPrototype = aryUrl[2]; 

         url = '/view-pt/' + aryUrl[1] + '/' + aryUrl[2] + itemId; 

         break; 
        case 'auth': 
         /** 
         * Local Login 
         */ 
         var successGetLog = function(req, res) { 
         res.render('login/get.html', { 
          layout: 'layout/auth.html', 
          entorno: config.config_entorno.empresa, 
          message: req.flash('loginMessage'), 
          loginAttempts: req.flash('loginAttempts') 
         }); 
         }; 

         var successPostLog = function (req, res) { 
         var loginAttempts = res.locals.req.user.loginAttempts; 
         if (loginAttempts >= 4){ 
          recaptcha.verify(req, function(error){ 
          if(error){ //Falla de verificacion de captcha 
           res.render('login/get.html', { 
           layout: 'layout/auth.html', 
           entorno: config.config_entorno.empresa, 
           message: req.flash('loginMessage'), 
           loginAttempts: loginAttempts, 
           captcha:recaptcha.render() 
           }); 
          } else { //Exito de verificacion de captcha 
           res.redirect('/'); 
          } 
          }); 
         } else { 
          res.redirect('/'); 
         } 
         }; 

         var successGetLogout = function(req, res) { 
         req.logout(); 
         res.redirect('/'); 
         }; 

         router.route('/auth/login').get(successGetLog); 

         router.route('/auth/login').post(passport.authenticate("local-login", {failureRedirect: '/auth/logout'}), successPostLog); 

         router.route('/auth/logout').get(successGetLogout); 

         /** 
         * Encuesta Local Login 
         */ 
         var successGetPortalLog = function(req, res) { 
          if (req.query.rut != undefined || req.query.token == 'bciboost') { 
           if (req.query.rut != undefined && req.query.token == 'bciboost') { 
            console.log('casi'); 
            req.body = { 
             rut: req.query.rut, 
             password: 'null' 
            }; 
            passport.authenticate('portaleval-link-login', function(err, user, info) { 
             if (err) { 
              return next(err); 
             } 
             if (!user) { 
              res.render('portalevaluacionapp/portal_evaluacion_login.html', { 
               layout: 'layout/empty.html', 
               entorno: config.config_entorno.empresa, 
               message: req.flash('loginMessage'), 
               access: req.path, 
              }); 
             } 
             req.logIn(user, function(err) { 
              if (err) { 
               return next(err); 
              } 
              if (user) { 
               res.redirect('/evaluaciones'); 
              } 
             }); 
            })(req, res, next); 
           } else { 
            res.render('portalevaluacionapp/portal_evaluacion_login.html', { 
             layout: 'layout/empty.html', 
             entorno: config.config_entorno.empresa, 
             message: 'Existe un problema al iniciar sesión', 
             access: req.path, 
            }); 
           } 
          } else { 
           if (Object.keys(req.session.passport).length !== 0 && req.session.passport.constructor === Object && req.path === '/auth/evaluaciones' && req.session.passport.user.type === 'PortalEval') { 
            res.redirect('/evaluaciones'); 
           } else { 
            res.render('portalevaluacionapp/portal_evaluacion_login.html', { 
             layout: 'layout/empty.html', 
             entorno: config.config_entorno.empresa, 
             message: req.flash('loginMessage'), 
             access: req.path, 
            }); 
           }; 
          } 
         } 

         var successPostPortalLog = function(req, res) { 
         res.redirect(req.path.replace('/auth', '')); 
         }; 

         var successGetPortalLogout = function(req, res) { 
          req.logout(); 
          res.redirect(req.path.replace('/logout', '')); 
         }; 

         var successGetPortalRelatorLogout = function(req, res) { 
          req.logout(); 
          res.redirect("/auth/relatores"); 
         }; 

         if (req.path === '/auth/evaluaciones' || req.path === '/auth/evaluaciones/antesdelcurso' || req.path === '/auth/evaluaciones/despuesdelcurso') { 
         var rutAux = req.body.rut; 
         req.body = { 
          rut: (typeof rutAux === 'undefined' || rutAux === '')? 'null': req.body.rut, 
          password: 'null' 
         }; 
         } 

         router.route('/auth/evaluaciones').get(successGetPortalLog); 
         router.route('/auth/evaluaciones/antesdelcurso').get(successGetPortalLog); 
         router.route('/auth/evaluaciones/despuesdelcurso').get(successGetPortalLog); 

         router.route('/auth/evaluaciones').post(passport.authenticate("portaleval-login", {failureRedirect: '/auth/evaluaciones'}), successPostPortalLog); 
         router.route('/auth/evaluaciones/antesdelcurso').post(passport.authenticate("portaleval-login", {failureRedirect: '/auth/evaluaciones'}), successPostPortalLog); 
         router.route('/auth/evaluaciones/despuesdelcurso').post(passport.authenticate("portaleval-login", {failureRedirect: '/auth/evaluaciones'}), successPostPortalLog); 

         router.route('/auth/evaluaciones/logout').get(successGetPortalLogout); 
         router.route('/auth/evaluaciones/logout/antesdelcurso').get(successGetPortalLogout); 
         router.route('/auth/evaluaciones/logout/despuesdelcurso').get(successGetPortalLogout); 

         var successGetRelatorLog = function(req, res) { 
          res.render('portalrelatoresapp/portal_relatores_login.html', { 
           layout: 'layout/empty.html', 
           entorno: config.config_entorno.empresa, 
           message: req.flash('loginMessage'), 
           access: req.path, 
          }); 
         }; 


         var successPostRelatorPortalLog = function(req, res) { 
         res.redirect(req.path.replace('/auth', '')); 
         }; 




         router.route('/auth/relatores').get(successGetRelatorLog); 
         router.route('/auth/relatores').post(passport.authenticate("portalrelatores-login", {failureRedirect: '/auth/relatores'}), successPostPortalLog); 
         router.route('/auth/relatores/logout').get(successGetPortalRelatorLogout); 



         break; 
        default: 

         break; 
        } 

        if (controller != '') { 
        var controllerDynamic = require(module); 

        controllerDynamic.req = req; 
        controllerDynamic.res = res; 

        /** 
        * Auth validation 
        */ 
        if (privacity == 'private') { 
         if (req.isAuthenticated()) { 
         if (session == 'General') { 
          if (controllerDynamic.auth.indexOf('PortalEval') != -1) { 
          var err = new Error(402); 
          throw err; 
          } 
         } else 
         if (session == 'PortalEval') { 
          if (controllerDynamic.auth.indexOf('General') != -1) { 
           var err = new Error(401); 
           throw err; 
          } 
         } else 
         if (session == 'RelatorEval') { 
          if (controllerDynamic.auth.indexOf('General') != -1) { 
           var err = new Error(401); 
           throw err; 
          } 
         } 
      //============================================================================== 
         else 
         if (session == 'PortalRelator') { 
          if (controllerDynamic.auth.indexOf('PortalRelator') == -1) { 
          var err = new Error(402); 
          throw err; 
          } 
         } 
      //============================================================================== 
         else { 
          var err = new Error(404); 
          throw err; 
         } 
         } else { 
         if (controllerDynamic.auth.indexOf('PortalEval') != -1) { 
          var err = new Error(402); 
          throw err; 
         } else 
         if (controllerDynamic.auth.indexOf('General') != -1) { 
          var err = new Error(401); 
          throw err; 
         } else { 
          var err = new Error(404); 
          throw err; 
         } 
         } 
        } 

        /** 
        * Check the "auth" atribute of a controller 
        */ 
        // if (controllerDynamic.auth.indexOf(controllerPrototype) != -1) { 

        // } 

        /** 
        * Final validation 
        */ 
        var isValid = true; 
        if (aryUrl.length > 4) { 
         isValid = false; 
        } 

        if (method == '') { 
         isValid = false; 
        } 

        if (typeof controllerDynamic[controllerPrototype] !== "function") { 
         isValid = false; 
        } 

        if (isValid) { 
         router.route(url)[method](function(ctrlReq, ctrlRes){ 
          controllerDynamic[controllerPrototype](ctrlReq, ctrlRes); 
         }); 
        } else { 
         res.status(404).send('Not found'); 
       } 
        } 

        next(); 

       } catch (e) { 
        if (e.message == 401) { 
        res.status(401).redirect('/auth/login'); 
        } else 
        if (e.message == 402) { 
        res.status(401).redirect('/auth' + url); 
        } else { 
        res.status(404).send('Not found 2'); 
        } 
       } 
       }); 

       app.use('/', router); 
      }; 

だと思う

を応答が長いです8分以上)何が起こっているのか分かりませんでした

ありがとうございました!

+0

あなたのコード例で一般公開されたので、あなたのGoogleアカウントであなたのrecaptchaの資格情報を再生成する必要があります... – mscdex

+0

この長いコードでは、インデントの数が多いため、特別なコードエディタで表示することなく、インデントあたり2スペースでは不可能です。それは単にここでは機能しません。 – jfriend00

+0

うーん...うわー?これは私がそれに入りたくないような長くて蛇行するコードです。私はあなたがExpressのドキュメントを読んで、たぶんいくつかのチュートリアルをやり直し、やり直すべきだと思います。このアプローチでは、フレームワークのすべての利点をきちんと避けています。 – Paul

答えて

0

他のルートハンドラの一部である条件の中にルート定義を入れるのは間違っており、決してうまくいかないでしょう。 router.xxx()は、そのサーバー上のすべてのユーザーに対してサーバー全体にわたって定義されています。だから、他のルートハンドラーの内部にそれらを置くことは間違っている。それはルートがすべてのユーザーにヒットするたびに何度も繰り返し定義されるため、ルート定義が重複してしまうため、すべてのユーザー(要求を行ったユーザーだけでなく)に影響を与えます。 do(これはおそらくこのユーザーからの将来の要求に影響を与えます)。

このコードは長すぎて、文書化が不十分で間違っているため、ルートの仕組みを完全に再設計して再考する必要があるため、修正するための簡単な提案はありません。さらに、あなたはコードが何をすべきか記述していません。

ルート定義の最初の原則に戻り、サーバーの初期化時に1回確立される1組のルート定義について考えてみましょう。特定のユーザーのためにある状態を設定して、そのユーザーの将来のルートで異なることが起こるようにするには、ユーザーごとにセッションを設定することを検討する必要があります。そのユーザのセッションオブジェクト内の情報に関する既存のルートベース内の条件付き動作を使用する。

既存のルート内で新しいルートを定義すると、ルートハンドラが重複してしまい、現在のユーザーだけに影響が及ぶことはありません。ルートハンドラは、サーバーに対してグローバルであり、現在のユーザーだけでなくすべてのユーザーに適用されるため、ユーザーごとの状態を設定することはできません。ユーザーごとのセッションオブジェクト(エクスプレスセッションモジュールが作成するセッションオブジェクトなど)内に状態を設定し、現在のユーザーのセッションの状態に基づいて既存のルートハンドラー内で条件を使用します。セッション状態は一般に、ユーザが既に認証されているかどうか、または必要とされる他のアプリケーション固有の状態とともに含まれます。

また、クライアントがパスを含むURLを指定する場合、通常はサーバー側のロジックがステートレスであるように設計することをお勧めします。これは通常、より堅牢で拡張性が高く、 /パラメータは、ユーザがやっていることを含むサーバ側の状態ではなく、何をしようとしているのかに関するものです。あなたの最初の選択肢は、それがクライアント上で維持されることです。明らかに認証されているかどうかなどの一部の状態はサーバー上で管理する必要がありますが、他の多くの状態では維持できません。たとえば、クライアントが5ステップのプロセスの途中にある場合、サーバが現在のステップを追跡する必要はありません。クライアントは次のステップのURLを要求するだけで、クライアントがその情報を送信すると、サーバーは送信された内容を検証して正当なものであるかどうかを確認し、それに応じて次のステップのページを返します。

+0

@garyv - これはあなたの質問に答えましたか? – jfriend00

関連する問題