在我的nodejs用户身份验证中,取自样板,我的注册工作但不是我的登录

时间:2017-12-14 00:31:54

标签: javascript node.js authentication express-session

我正在为学校的nodejs项目制作一个相当简单的基于会话的用户身份验证,它基于可以在here找到的在线教程中的样板文件。使用mysql和mysql2节点包简单转换到mysql而不是prestege。

一切正常,登录功能似乎不会创建持久会话。您可以注册为新用户,它将带您进入网站的仪表板部分,但登录则不会。登录将控制台登录到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:root@localhost: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: 'user@user.user',
            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 - -

有谁能告诉我为什么我的注册按钮工作但我的登录按钮没有?

1 个答案:

答案 0 :(得分:0)

问题出在我的user.js文件中。我没有及时了解最新的Sequelize instance.method / model处理。

我现有的代码是

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

正确地是

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