Saturday 10 June 2017

passport module on node.js - Reference Error: LocalStrategy is not defined

When I try to run my code it gives me Reference Error: LocalStrategy is not defined.

This is my first time using node.js and I hit a wall with this. I appreciate the help in advance.

I put all the code in one snippet so you can go through it easily. I have tried other posts for fixes but have been unsuccessful.

/***********
   Modules
***********/

//Load the express library
var express = require('express');
//Create a new variable called “app”; we pass on the express() method.
var app = express();
//Set Port
var port = 7878;
var mongoose = require('mongoose'); //Place this on top; Loads mongoose library
var bodyParser = require('body-parser');
var passport = require('passport');
var LocalStratgy = require('passport-local').Strategy;

/*Body parser*///whenever you do a post request from the form, it gets the data through a URL encoded format.
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use('/js', express.static(__dirname + '/js'));

/*Initialize Passport*/
app.use(passport.initialize());
app.use(passport.session());

/***********
  Database
***********/

/*Database connection - MongoDB*/

//Created from the command earlier. Ensure this is done on the first_db instance
var usr = 'admin';
var pwd = '123456';

var dbHost = 'localhost';
var dbPort = '27017';
var database = 'first_db';

var url = 'mongodb://' + usr + ':' + pwd + '@' + dbHost + ':' + dbPort + '/' + database;
console.log('mongodb connection = ' + url);

mongoose.connect(url, function(err) {
    if(err) {
        console.log('connection error: ', err);
    } else {
        console.log('connection successful');
    }
});

/***********
   Models
***********/

//User model
//Define our fields for the table
var UserSchema = new mongoose.Schema({
     user_id: mongoose.Schema.ObjectId,
     username: String,
     password: String
   });
//Create model object
var User = mongoose.model('user', UserSchema);


/***********
   Routes
***********/
var bcrypt = require('bcrypt-nodejs'); //should be placed on top
//Renders our html file
app.get('/', function (req, res, next) {
  res.sendFile( __dirname + '/index.html');
});
//render register.html when /register is called
app.get('/register', function (req, res, next) {
  res.sendFile( __dirname + '/register.html');
});

app.get('/home', function (req, res, next) {
    res.sendFile(__dirname + '/home.html');
});

app.post('/login', passport.authenticate('local'),
    function(req, res) {
        res.redirect('/home');
});

/* Login logic for passport.authenticate*/
passport.use(new LocalStrategy(
    function(username, password, done) {
        User.findOne({ username: username }, function (err, user) {
            if(user !== null) {
                var isPasswordCorrect = bcrypt.compareSync(password, user.password);
                if(isPasswordCorrect) {
                    console.log("Username and password correct!");
                    return done(null, user);
                } else {
                    console.log("Password incorrect!");
                    return done(null, false);
                }
           } else {
               console.log("Username does not exist!");
               return done(null, false);
           }
       });
    }
));

/**********
Serialize and Deserialize here for passport.authenticate
**********/
passport.serializeUser(function(user, done) {
    done(null, user);
});

passport.deserializeUser(function(user, done) {
    done(err, user);
});

app.post('/register', function (req, res, next) {
    var password = bcrypt.hashSync(req.body.password);
    req.body.password = password;

    User.create(req.body, function(err, saved) {
        if(err) {
            console.log(err);
            res.json({ message : err });
        } else {
            res.json({ message : "User successfully registered!"});
        }
    });
});

app.listen(port, '0.0.0.0', function() {
 console.log('Server running at port ' + port);
});


via ThatMoose

No comments:

Post a Comment