2017-12-14 2 views
0

Ich mache eine ziemlich einfache sessionsbasierte Benutzerauth für ein nodejs Projekt für die Schule basierend auf einem Textbaustein aus einem Online-Tutorial, das gefunden werden kann here . Einfacher Wechsel zu mysql anstelle von prestege mit mysql und mysql2 Knotenpaketen.In meiner nodejs Benutzerauthentifizierung, von boilerplate übernommen, funktioniert meine Registrierung, aber nicht mein Login

Alles funktioniert ERWARTEN Sie, dass die Login-Funktion keine dauerhafte Sitzung zu erstellen scheint. Sie können sich als neuer Benutzer registrieren und es wird Sie zum Dashboard-Bereich der Website führen, aber einloggen nicht. Durch die Anmeldung wird das Protokoll auf gitbash umgestellt. Der Benutzer wird jedoch authentifiziert.

    //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')}`)); 

Platzhalter

   //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> 

Meine gitbash folgendes zurückgibt, wenn ich eine Anmeldung oder neue Benutzer senden. Der Versuch, einloggen oder registrieren kehrt diese auf meinem 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 - - 

mir jemand kann sagen, warum meine Registrationstaste funktioniert, aber meine Login-Button nicht?

+0

Ihre client Login-Funktion leer ist. – Paul

+0

Es sollte nicht notwendig sein, soweit ich das beurteilen kann, das war nur übrig gebliebenen Code von mir versucht, Problem zu lösen und Haus nicht vollständig zu reinigen. Wenn der Registrierungsbutton wie er ist und die Aktion = '/ Anmeldung' funktioniert, kann ich keinen Grund sehen, warum der action = '/ login' Button nicht funktioniert. –

+0

Weil es durch den Submit-Button aufgerufen wird. Wenn Sie nichts tun, blockiert es wahrscheinlich die Submit-Aktion. – Paul

Antwort

0

Das Problem war in meiner user.js-Datei. Ich war nicht auf dem neuesten Sequelize-Instanz.Method/Modell-Handling.

Mein vorhandenen Code war

    // 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); 
        } 
        }  
        }); 

Korrekt ist es

 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); 
     } 
Verwandte Themen