2017-12-14 3 views
0

私は、オンラインチュートリアルの定型文に基づいて、nodejsプロジェクト用のセッションベースのユーザー認証を簡略化しています。here 。 mysqlとmysql2ノードパッケージを使用してprestegeではなくmysqlに簡単に切り替えます。私のnodejsユーザー認証で、定型票から取得した場合、私の登録は動作しますがログインは無効です

ログイン機能が永続セッションを作成していないと思われるものはすべて動作します。新しいユーザーとして登録すると、ウェブサイトのダッシュボードセクションに移動しますが、ログインすることはできません。ただし、ログインするとgitbashにログが記録されますが、ユーザーは認証されています。私は、ログインするか、新しいユーザーを送信すると

    //server.js 
        var express = require('express'); 
        var bodyParser = require('body-parser'); 
        var cookieParser = require('cookie-parser'); 
        var session = require('express-session'); 
        var morgan = require('morgan'); 
        var User = require('./models/user'); 

        // invoke an instance of express application. 
        var app = express(); 

        // set our application port 
        app.set('port', 9000); 

        // set morgan to log info about our requests for 
        development use. 
        app.use(morgan('dev')); 

        // initialize body-parser to parse incoming parameters 
        requests to req.body 
        app.use(bodyParser.urlencoded({ extended: true })); 

        // initialize cookie-parser to allow us access the 
        cookies stored in the browser. 
        app.use(cookieParser()); 

        // initialize express-session to allow us track the 
        logged-in user across sessions. 
        app.use(session({ 
         key: 'user_sid', 
         secret: 'somerandonstuffs', 
         resave: false, 
         saveUninitialized: false, 
         cookie: { 
          expires: 600000 
         } 
        })); 


        // This middleware will check if user's cookie is still 
        saved in browser and user is not set, then automatically 
        log the user out. 
        // This usually happens when you stop your express 
        server after login, your cookie still remains saved in 
        the browser. 
        app.use((req, res, next) => { 
         if (req.cookies.user_sid && !req.session.user) { 
          res.clearCookie('user_sid');   
         } 
         next(); 
        }); 


        // middleware function to check for logged-in users 
        var sessionChecker = (req, res, next) => { 
         if (req.session.user && req.cookies.user_sid) { 
          res.redirect('/dashboard'); 
         } else { 
          next(); 
         }  
        }; 


        // route for Home-Page 
        app.get('/', sessionChecker, (req, res) => { 
         res.redirect('/login'); 
        }); 


        // route for user signup 
        app.route('/signup') 
         .get(sessionChecker, (req, res) => { 
          res.sendFile(__dirname + '/public/signup.html'); 
         }) 
         .post((req, res) => { 
          User.create({ 
           username: req.body.username, 
           email: req.body.email, 
           password: req.body.password 
          }) 
          .then(user => { 
           req.session.user = user.dataValues; 
           res.redirect('/dashboard'); 
          }) 
          .catch(error => { 
           res.redirect('/signup'); 
          }); 
         }); 


        // route for user Login 
        app.route('/login') 
         .get(sessionChecker, (req, res) => { 
          res.sendFile(__dirname + '/public/login.html'); 
         }) 
         .post((req, res) => { 
          var username = req.body.username, 
           password = req.body.password; 


          User.findOne({ where: { username: username } 
          }).then(function (user) { 
           if (!!uuser) { 
            res.redirect('/dashboard`'); 
           } else if (!user.validPassword(password)) { 
            res.redirect('/dashboard'); 
           } 
           else { 
            req.session.user = user.dataValues; 
            res.redirect('/dashboard'); 
           } 
          }); 
         }); 


        // route for user's dashboard 
        app.get('/dashboard', (req, res) => { 
         if (req.session.user && req.cookies.user_sid) { 
          res.sendFile(__dirname + 
        '/public/dashboard.html'); 
         } else { 
          res.redirect('/login'); 
         } 
        }); 

        app.get('/helloworld', (req, res) => { 
         if (req.session.user && req.cookies.user_sid) { 
          res.sendFile(__dirname + 
        '/public/helloworld.html'); 
         } else { 
          res.redirect('/login'); 
         } 
        }); 


        // route for user logout 
        app.get('/logout', (req, res) => { 
         if (req.session.user && req.cookies.user_sid) { 
          res.clearCookie('user_sid'); 
          res.redirect('/'); 
         } else { 
          res.redirect('/login'); 
         } 
        }); 


        // route for handling 404 requests(unavailable routes) 
        app.use(function (req, res, next) { 
        res.status(404).send("Sorry can't find that!") 
        }); 


        // start the express server 
        app.listen(app.get('port'),() => console.log(`App 
        started on port ${app.get('port')}`)); 

プレースホルダ

   //user.js 
            var Sequelize = require('sequelize'); 
          var bcrypt = require('bcrypt'); 


          //create sequelize instance with local database 
          var sequelize = new 

       Sequelize('mysql://root:[email protected]:8889/authsystem'); 

          // setup User model and its fields. 
          var User = sequelize.define('users', { 
           username: { 
            type: Sequelize.STRING, 
            unique: true, 
            allowNull: false 
           }, 
           email: { 
            type: Sequelize.STRING, 
            unique: true, 
            allowNull: false 
           }, 
           password: { 
            type: Sequelize.STRING, 
            allowNull: false 
           } 
          }, { 
           hooks: { 
           beforeCreate: (user) => { 
            const salt = bcrypt.genSaltSync(); 
            user.password = 
           bcrypt.hashSync(user.password, salt); 
           } 
           }, 
           instanceMethods: { 
           validPassword: function(password) { 
            return bcrypt.compareSync(password, 
           this.password); 
           } 
           }  
          }); 

          // create all the defined tables in the 
          specified database. 
          sequelize.sync() 
           .then(() => console.log('users table has 
          been successfully created, if one doesn\'t 
          exist')) 
           .catch(error => console.log('This error 
          occured', error)); 

          // export User model for use in other files. 
          module.exports = User; 

login.htmlと

 //login.html 

      <html> 
       <head> 
        <title>Login Here</title> 
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> 
       </head> 
       <body class="container"> 
        <div class="page-header"> 
         <h1>Simple Auth-System</h1> 
        </div> 

        <nav class="navbar navbar-default"> 
         <div class="container-fluid"> 
          <!-- Collect the nav links, forms, and other content for toggling --> 
          <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> 
           <ul class="nav navbar-nav"> 
            <li><a href="/">Home</a></li> 
            <li><a href="/signup">Sign Up</a></li> 
            <li><a href="/dashboard">Dashboard</a></li> 
           </ul> 

           <ul class="nav navbar-nav navbar-right"> 
            <li><a href="/login">Log In</a></li> 
            <li><a href="/logout">Log Out</a></li> 
            <li><a href="/helloworld">hello world</a></li> 

           </ul> 
          </div><!-- /.navbar-collapse --> 
         </div><!-- /.container-fluid --> 
        </nav> 

        <div class="container row"> 
         <div class="jumbotron col-sm-4 pull-center"> 
          <form action="/login" method="post"> 
           <div> 
            <label>Username:</label> 
            <input type="text" name="username"/> 
           </div> 
           <div> 
            <label>Password:</label> 
            <input type="password" name="password"/> 
           </div> 
           <div> 
            <input class="btn btn-primary" type="submit" value="Log In" onclick="login()"/> 
            <script> 
            function login(){ 
            }; 
            console.log(login); 
            </script> 
           </div> 
          </form>     
         </div>   
        </div> 
       </body> 
      </html> 

signup.html

//signup.html 

      <html> 
       <head> 
        <title>Login Here</title> 
        <link rel="stylesheet" 





href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" 
       integrity="sha384- 
     BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" 
        crossorigin="anonymous"> 
       </head> 
       <body class="container"> 
        <div class="page-header"> 
         <h1>Simple Auth-System</h1> 
        </div> 

        <nav class="navbar navbar-default"> 
         <div class="container-fluid"> 
          <!-- Collect the nav links, forms, and other 
         content for toggling --> 
          <div class="collapse navbar-collapse" id="bs- 
       example-navbar-collapse-1"> 
           <ul class="nav navbar-nav"> 
            <li><a href="/">Home</a></li> 
            <li><a href="/signup">Sign Up</a></li> 
            <li><a href="/dashboard">Dashboard</a> 
        </li> 
           </ul> 

           <ul class="nav navbar-nav navbar-right"> 
            <li><a href="/login">Log In</a></li> 
            <li><a href="/logout">Log Out</a></li> 
            <li><a href="/helloworld">hello 
         world</a></li> 

           </ul> 
          </div><!-- /.navbar-collapse --> 
         </div><!-- /.container-fluid --> 
        </nav> 

        <div class="container row"> 
         <div class="jumbotron col-sm-4 pull-center"> 
          <form action="/signup" method="post"> 
           <div> 
            <label>Username:</label> 
            <input type="text" name="username"/> 
           </div> 
           <div> 
            <label>Email:</label> 
            <input type="text" name="email"/> 
           </div>  
           <div> 
            <label>Password:</label> 
            <input type="password" name="password"/> 
           </div> 
           <div> 
            <input class="btn btn-primary" 
       type="submit" value="Sign Up"/> 
           </div> 
          </form>     
         </div>   
        </div> 
       </body> 
      </html> 

私gitbashは以下のものを返します。私の登録ボタンが私のログインボタン働いていないが、なぜ私のgitbashにこの

    $ node server.js 
      sequelize deprecated String based operators are now deprecated. 
    Please use Symbol based operators for better security, read more at 
    http://docs.sequelizejs.com/manual/tutorial/querying.html#operators 
    node_modules\sequelize\lib\sequelize.js:236:13 
      App started on port 9000 
      Executing (default): CREATE TABLE IF NOT EXISTS `users` (`id` 
INTEGER NOT NULL auto_increment , `username` VARCHAR(255) NOT NULL UNIQUE, 
    `email` VARCHAR(255) NOT NULL UNIQUE, `password` VARCHAR(255) NOT NULL, 
     `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, UNIQUE 
    `users_username_unique` (`username`), UNIQUE `users_email_unique` 
    (`email`), PRIMARY KEY (`id`)) ENGINE=InnoDB; 
      Executing (default): SHOW INDEX FROM `users` 
      users table has been successfully created, if one doesn't exist 
      GET/302 15.479 ms - 56 
      GET /login 304 4.091 ms - - 
      GET/302 1.330 ms - 56 
      GET /login 304 2.898 ms - - 
      Executing (default): SELECT `id`, `username`, `email`, 
    `password`, `createdAt`, `updatedAt` FROM `users` AS `users` WHERE 
     `users`.`username` = 'user' LIMIT 1; 
      { id: 25, 
      username: 'user', 
      email: '[email protected]', 
      password: 
     '$2a$10$X9NEv1MqFffh77BV2lIYLedqYWRUzDM3WlAfzJ9R4Q0oWVDvABqx2', 
      createdAt: 2017-12-14T02:08:25.000Z, 
      updatedAt: 2017-12-14T02:08:25.000Z } 
      ------------------------ 
      POST /login/verify 302 43.584 ms - 58 
      GET /signup 304 1.038 ms - - 

をリターンをログインまたはサインアップしようとすると は誰も教えてもらえますか?

+0

です

 // setup User model and its fields. var User = sequelize.define('users', { username: { type: Sequelize.STRING, unique: true, allowNull: false }, email: { type: Sequelize.STRING, unique: true, allowNull: false }, password: { type: Sequelize.STRING, allowNull: false } }, { hooks: { beforeCreate: (user) => { const salt = bcrypt.genSaltSync(); user.password = bcrypt.hashSync(user.password, salt); } }, instanceMethods: { validPassword: function(password) { return bcrypt.compareSync(password, this.password); } } }); 

ました。 – Paul

+0

私が言うことができる限りでは、それは問題解決に努め、完全に家を掃除しようとしている残ったコードである必要はありません。登録ボタンがそのまま動作し、action = '/ signup'が動作する場合、action = '/ login'ボタンが表示されない理由はありません。 –

+0

送信ボタンによって呼び出されているためです。何もしないことによって、おそらく送信アクションをブロックしている可能性があります。 – Paul

答えて

0

問題は私のuser.jsファイルにあります。私は最新のSequelize instance.method/modelの取り扱いに関して最新ではありませんでした。

私の既存のコードが正しく、それはあなたのクライアント側のログイン機能が空白の

 const user = sequelize.define('users', { 
      username: { 
       type: Sequelize.STRING, 
       unique: true, 
       allowNull: false 
      }, 
      email: { 
       type: Sequelize.STRING, 
       unique: true, 
       allowNull: false 
      }, 
      password: { 
       type: Sequelize.STRING, 
       allowNull: false 
      } 
     }, { 
      hooks: { 
       beforeCreate: (user) => { 
        const salt = bcrypt.genSaltSync(); 
        user.password = bcrypt.hashSync(user.password, salt); 
       } 
      } 
     }) 

     user.prototype.validPassword = function (password) { 
      return bcrypt.compareSync(password, this.password); 
     } 
関連する問題