验证后,车把没有改变

时间:2018-10-25 19:16:44

标签: javascript node.js express

此文件是我的header.hbs

 <!doctype html>
    <html class="no-js" lang="">

    <head>
      <meta charset="utf-8">
      <meta http-equiv="x-ua-compatible" content="ie=edge">
      <title>{{ title }}</title>
      <meta name="description" content="">
      <meta name="viewport" content="width=device-width, initial-scale=1">

      <link rel="apple-touch-icon" href="apple-touch-icon.png">
      <!-- Place favicon.ico in the root directory -->
      <link rel="stylesheet" 
      href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0- 
      alpha.6/css/bootstrap.min.css" integrity="sha384- 
      rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ"
        crossorigin="anonymous">
      </head>

    <body>
      <!--[if lt IE 8]>
                <p class="browserupgrade">You are using an 
    <strong>outdated</strong> browser. Please <a 
    href="http://browsehappy.com/">upgrade your browser</a> to improve your 
    experience.</p>
            <![endif]-->
      <div class="container">
        <div class="header clearfix">
          <nav>
            <ul class="nav nav-pills float-right">
              <li class="nav-item">
                <a class="nav-link" href="/">Home <span class="sr-only">     (current)</span></a>
              </li>
              {{#if isAuthenticated}}
              <li class="nav-item">
                <a class="nav-link" href="/profile">Profile</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="/logout">Logout</a>
              </li>
              {{else}}
              <li class="nav-item">
                <a class="nav-link" href="/register">Register</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="/login">Login</a>
              </li>
            {{/if}}
            </ul>
          </nav>
          <h3 class="text-muted">Project name</h3>
        </div>

这是我的app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var expressValidator = require('express-validator');


// Authentication Packages
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var MySQLStore = require('express-mysql-session')(session);
var bcrypt = require('bcrypt');


var index = require('./routes/index');
var users = require('./routes/users');

var app = express();

require('dotenv').config();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(expressValidator());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

//storing the session in the database
var options = {
  host: process.env.DB_HOST,
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  database : process.env.DB_NAME
};

var sessionStore = new MySQLStore(options);

app.use(session({
  secret: 'fa6737b131bf59613f73afc6416d4ee6',
  resave: false,
  store: sessionStore,
  saveUninitialized: false,
  //cookie: { secure: true } //uncomment if it is https
}));
app.use(passport.initialize());
app.use(passport.session());

//authentication for the hbs
app.use((req,res,next)=>{
  res.locals.isAutheticated = req.isAuthenticated();
  next();
});

app.use('/', index);
app.use('/users', users);

passport.use(new LocalStrategy(
  function(username, password, done) {
   //console.log(username);
   //console.log(password);
   const db = require('./db');

   db.query('SELECT id, password FROM users WHERE username = ?',[username], 
(err,results,fields)=>{
      if(err){done(err);}
      if(results.length === 0){done(null,false);} 
      else{
        //console.log(results[0].password.toString());
        const hash = results[0].password.toString();

        bcrypt.compare(password, hash, (err,response)=>{
          if (response == true){
            return done(null, {user_id:results[0].id}); 
          }
          else{
            return done(null,false);
          }
        });
      }
  });
  }
));

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});


// Handlebars default config
const hbs = require('hbs');
const fs = require('fs');

const partialsDir = __dirname + '/views/partials';

const filenames = fs.readdirSync(partialsDir);

filenames.forEach(function (filename) {
  const matches = /^([^.]+).hbs$/.exec(filename);
  if (!matches) {
    return;
  }
  const name = matches[1];
  const template = fs.readFileSync(partialsDir + '/' + filename, 'utf8');
  hbs.registerPartial(name, template);
});

hbs.registerHelper('json', function(context) {
    return JSON.stringify(context, null, 2);
});


module.exports = app;

这是我的index.js

    var express = require('express');
    var router = express.Router();
    var expressValidator = require('express-validator');
    var passport = require('passport');
    const bcrypt = require('bcrypt');
    const saltRounds = 10;


    /* GET home page. */
    router.get('/', (req, res) => {
      console.log(req.user);
      console.log(req.isAuthenticated());
      res.render('home', {
        title: 'Home'
      });
    });

    router.get('/profile', authenticationMiddleware(),(req,res)=>{
      res.render('profile',{title:'Profile'});
    });

    router.get('/login', (req,res)=>{
      res.render('login',{title:'login'});
    });

    router.post('/login', passport.authenticate('local', {
      successRedirect:'/profile',
      failureRedirect:'/login'
    }));

    router.get('/logout', (req,res)=>{
      req.logout();
      req.session.destroy();
      res.redirect('/');
    });

    router.get('/register', function (req, res, next) {
      res.render('register', {
        title: 'Registration'
      });
    });

    router.post('/register', function (req, res, next) {
      //using express validator to validate the data 
      req.checkBody('username', 'Username field cannot be empty.').notEmpty();
      req.checkBody('username', 'Username must be between 4-15 characters 
    long.').len(4, 15);
      req.checkBody('email', 'The email you entered is invalid, please try 
    again.').isEmail();
      req.checkBody('email', 'Email address must be between 4-100 characters 
    long, please try again.').len(4, 100);
      req.checkBody('password', 'Password must be between 8-100 characters 
    long.').len(8, 100);
      req.checkBody("password", "Password must include one lowercase character, 
    one uppercase character, a number, and a special character.").matches(/^(? 
   =.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.* )(?=.*[^a-zA-Z0-9]).{8,}$/, "i");
      req.checkBody('passwordMatch', 'Password must be between 8-100 characters 
    long.').len(8, 100);
      req.checkBody('passwordMatch', 'Passwords do not match, please try 
    again.').equals(req.body.password);
      const errors = req.validationErrors();
      if (errors) {
       // console.log(`errors:${JSON.stringify(errors)}`);
        res.render('register', {
          title: 'Registration Error',
          errors: errors
        });
      } else {
        //storing the data comming form post resquest 
        const username = req.body.username;
        const email = req.body.email;
        const password = req.body.password;

        const db = require('../db.js');

        bcrypt.hash(password, saltRounds, function (err, hash) {
          // Store hash in your password DB.
          let sql = "INSERT INTO users(username,email,password) VALUES (?,?,?)";
          db.query(sql, [username, email, hash], (error, result, fields) => {
            if (error) throw error;

            db.query('SELECT LAST_INSERT_ID() as user_id', (error, result, 
    field) => {
              if (error) throw error;

              const user_id = result[0];
             // console.log(result[0]);
              req.login(user_id, (err) => {
                res.redirect("/");
              });
            });

          });
        });
      }
    });

    passport.serializeUser(function (user_id, done) {
      done(null, user_id);
    });

    passport.deserializeUser(function (user_id, done) {
      done(null, user_id);
    });

    function authenticationMiddleware() {
      return (req, res, next) => {
      //  console.log(`req.session.passport.user: 
    ${JSON.stringify(req.session.passport)}`);

        if (req.isAuthenticated()) return next();
        res.redirect('/login')
      }
    }
    module.exports = router;

这是我的终端机
POST /登录302 103.029 ms-60
GET / profile 304 47.276 ms--

当我登录或注册时,我的车把应该根据身份验证来更改导航栏,但是它并没有改变,并且我没有看到任何错误,因此我尝试包含所有代码并注释掉了所有细节。需要帮助

1 个答案:

答案 0 :(得分:0)

在app.js上,我所做的全部更改,

<label>
  <input type="checkbox"/>
  <div class="card">
    <div class="front">
      <span class="fa-stack fa-5x">
        <i class="far fa-circle fa-stack-2x icon-background"></i>
        <i class="fa fa-user fa-1x icon-color" aria-hidden="true"></i>
      </span>
      <h2 class="title">My Information</h2>
    </div>
    <div class="back">
      <h3>Header</h3>
      <h5>Subheader</h5>
      <p>Info</p>
      <p>Info</p>
      <p>Info</p>
      <p>Info</p>
      <p>Info</p>
      <p>Info</p>
      <p>Info</p>
      <p>Info</p>
      <p>Info</p>
      <p>Info</p>
    </div>
  </div>
</label>

它奏效了,我,因为您使用的是回调函数,所以必须使用条件,而不仅仅是分配值。