User authentication using passport.js giving error - javascript

I'm very new to node.js and passport.js. I was trying to learn how to make an authentication app using this video, but I keep getting this error after reaching 31:04 in the video.
"TypeError: Cannot read property 'name' of undefined at
Authenticator.use"
This is my app.js file:
var express = require('express');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var expressSession = require('express-session');
var passport = require('passport');
var passportLocal = require('passport-local');
var app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
secret: process.env.SESSION_SECRET
app.use(expressSession({ || 'secret',
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(passportLocal.Strategy(function(username, password, done){
//connect to a real db here
if(username===password){
done(null,{id: username, name: username});
//these actually have to bbe pulled from the db
}
else{
done(null,null);
}
}));
app.get('/', function(req, res){
res.render('index',{
isAuthenticated: req.isAuthenticated(),
user: req.user
});
});
app.get('/login', function(req, res){
res.render('login');
});
app.post('/login', passport.authenticate('local' , function(req,res){
res.redirect('/');
}));
var port = process.env.PORT || 1337;
app.listen(port, function(err,res){
if(err)
console.log(err);
else
console.log('server started on localhost:'+ port +' /');
});

You have to call the new operator:
passport.use(new passportLocal.Strategy(function(username, password, done){
//connect to a real db here
if(username===password){
done(null,{id: username, name: username});
//these actually have to bbe pulled from the db
}
else{
done(null,null);
}
}));
I believe this is your problem.

Related

Passport session doesn't retain after post

I'm new to Node.js app, and I writing authentication by passport. I can login and authentication routine works fine. However, after post, isAuthenticated() return false and redirect to index page. It seems like the user session is gone after doing post.
Could anybody tell me how to fix it? Here's my code.
app.js
var createError = require('http-errors');
var express = require('express');
const expressLayouts = require('express-ejs-layouts');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
var flash = require('connect-flash');
const session = require('express-session')
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy
var manageRouter = require('./routes/manage');
var app = express();
app.use(fileUpload());
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('tiny'));
app.use(expressLayouts);
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static('public'));
app.use(flash());
app.use(cookieParser('remote_teach'));
app.use(bodyParser.json());
app.use(session({
secret: "remote_teach",
resave: true,
saveUninitialized: true,
cookie: {maxAge: 60 * 60 * 24 * 1000}
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(function(req, res, next){
if (req.user && req.isAuthenticated()) {
res.locals["login"] = true;
}
return next();
});
app.use('/manage', manageRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
console.log("404");
next(createError(404));
});
module.exports = app;
route/manage.js
var express = require('express');
var router = express.Router();
var file_system = require('file-system');
var fs = require('fs');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const bcrypt = require('bcryptjs');
var md5 = require('md5');
const { encrypt, decrypt, randomString } = require('../crypto');
const db_configure = require('../configure');
var rootDirectory = 'public/data/';
// 資料庫
var mysql = require('mysql');
var connection = mysql.createConnection({
host : db_configure.db_host,
port : db_configure.db_port,
user : db_configure.db_user,
password : db_configure.db_pwd,
database : db_configure.db_name
});
// 顯示登入頁面
router.get('/login', function(req, res, next){
if (req.isAuthenticated()) {
res.redirect('/manage/index');
}else{
res.render('manage/login');
}
});
// Passport JS 登入驗證
passport.use(new LocalStrategy(
{
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true
},
// Verify Callback
function(req, email, passwd, done) {
//verrify if the user is existed
})
);
passport.serializeUser(function(user, done) {
done(null, user.user_id)
});
passport.deserializeUser(function(id, done) {
//select user and deserialize
done(null, user);
});
router.post('/login', passport.authenticate('local', { successRedirect: '/manage',
failureRedirect: '/',
failureFlash: true})
);
router.post('/user/create', isAuthenticated, function(req, res, next){
var name = req.body.name;
var email = req.body.email;
var password = md5(req.body.password);
connection.query('INSERT INTO users (name, email, password) VALUES (?, ?, ?)',[name, email, password], function (error, results, fields){
if (error){
console.log(error);
}
res.redirect('/manage/users');
});
});
function isAuthenticated(req, res, next) {
if (req.user && req.isAuthenticated()) {
return next();
}
return res.redirect('/');
}
module.exports = router;

Node.js passport local authentication is not calling the middleware

I´m trying to use local authentication with passport. According to the passport doc everything seems easy, but for some reason when I call the passport.authenticate the middleware is not running. Just nothing happens.
When I submit the signup form, the post signup function is called.I got the "Received" in my browser, however, I cannot see any console.log that I have in the passport.use callback.
Server:
const express = require('express');
const morgan = require('morgan');
const expressHandleBars = require('express-handlebars');
const path = require('path');
const flash = require('connect-flash');
const session = require('express-session');
const mysqlStore = require('express-mysql-session');
const passport = require('passport');
const { database } = require('./keys');
// Initializations
const app = express();
require('./lib/passport');
// Setting
app.set('port', process.env.PORT || 4000);
app.set('views', path.join(__dirname, 'views'));
app.engine('.hbs', expressHandleBars({
defaultLayout: 'main',
layoutsDir: path.join(app.get('views'), 'layouts'),
partialsDir: path.join(app.get('views'), 'partials'),
extname: '.hbs',
helpers: require('./lib/handlebars')
}));
app.set('view engine', '.hbs')
// Middleware
app.use(session({
secret: 'whatever',
resave: false,
saveUninitialized: false,
store: new mysqlStore(database)
}));
app.use(morgan('dev'));
app.use(express.urlencoded({extended: false}));
app.use(express.json());
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
// Global variables
app.use((req, res, next) => {
app.locals.success = req.flash('success');
next();
});
// Routes
app.use(require('./routes'));
app.use(require('./routes/authentication'));
app.use('/links', require('./routes/links'));
// Public
app.use(express.static(path.join('__dirname', 'public')));
// Starting the server
app.listen(app.get('port'), () => {
console.log('Server on port', app.get('port'));
});
Passport config file (lib/passport.js):
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const pool = require('../database');
const helpers = require('./helpers');
passport.use('local-signup', new LocalStrategy({
usernameField: 'username',
passwordField: 'password',
passReqToCallback: true
}, async function(req, username, password, done) {
console.log("Authenticated!!");
console.log(req.body);
}
));
Router calling authenticate (routes/authenticate.js):
const express = require('express');
const passport = require('passport');
const router = express.Router();
router.get('/signup', (req, res) => {
res.render('auth/signup');
});
router.post('/signup', (req, res) => {
passport.authenticate('local-signup', {
successRedirect: '/profile',
failureRedirect: '/signupFailure',
failureFlash: true
}, (req, res) => {
res.send("Authenticating");
});
//console.log(req.body);
res.send('Received');
});
router.get('/profile', (req, res) => {
res.send('This is your profile');
});
module.exports = router;
Passport.authenticate() returns a middleware function, you're not calling it.
passport.authenticate('local-signup', {
successRedirect: '/profile',
failureRedirect: '/signupFailure',
failureFlash: true
}, (req, res) => {
res.send("Authenticating");
})(req, res)

TypeError: req.flash is not a function (NodeJs)

Working with Registration in a Site. For the register Form,Validation is done using mongoose models and trying to Use Flash to display the error message in the Form.
But struct at this error
TypeError: res.flash is not a function
at /home/work/first-node-app/firstnode/routes/index.js:35:11
My Code snippets Follows below
App.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var mongoose = require('mongoose');
var passport = require('passport');
var session = require('express-session');
var flash = require('connect-flash');
var indexRouter = require('./routes/index');
var commonKeys = require('./config/config');
var app = express();
//connect mongoDb
mongoose.connect('mongodb://localhost:27017/db', { useNewUrlParser: true });
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// required for passport session
app.use(session({
secret: 'secrettexthere',
saveUninitialized: true,
resave: true,
// using store session on MongoDB using express-session + connect
}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use('/', indexRouter);
module.exports = app;
Index.js
var express = require('express');
var router = express.Router();
var passport = require('passport');
var User = require('../models/user-model');
var Local = require('../config/passport-local');
router.get('/register', function(req, res){
res.render('public/register',{title:'Register'});
});
router.post('/register', function(req,res,next){
User.create({name:req.body.name, password:req.body.password, email : req.body.email}, function(err, user){
if (err) {
console.log('Error Inserting New Data');
if (err.name == 'ValidationError') {
for (field in err.errors) {
res.flash(field, err.errors[field].message);
}
res.render('public/register');
}
}
if(user) {
res.send('user registered');
}
})
});
module.exports = router;
Can anyone point out the error in this code snippets, as am new to Nodejs and Trying to work out the Form validation. The validation Works fine and the console displays the error but i can't pass that using flash. Can anyone Help me? And its much appreciated if you confirm my approach to code Nodejs is in correct way.
Use req.flash() in place of res.flash. Refer here for more clarification.

Node.js Problems setting up Passport with Express and Mongoose

I'm new to Node.js. Trying to set up user account creation and log in using Passport. I can't ge it work. I am getting Unauthorized message although I am logging in with an existing user and pass. My code so far:
var express = require('express');
var http = require('http');
var path = require('path');
var request = require('request');
var app = express();
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var MongoClient = require('mongodb').MongoClient;
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.bodyParser());
app.use(app.router);
app.enable('trust proxy');
if ('development' == app.get('env')) {
}
var httpserver = http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
passportLocalMongoose = require('passport-local-mongoose');
/* Database has _id field but i guess i don't need to add anything here?*/
var Accoun = new Schema({
username: String,
password: String
});
/* Database collection is called 'users'*/
Accoun.plugin(passportLocalMongoose);
var Account = mongoose.model('users', Accoun);
passport.use(new LocalStrategy(Account.authenticate()));
passport.serializeUser(Account.serializeUser());
passport.deserializeUser(Account.deserializeUser());
mongoose.connect('xxxmyconnectionstring');
app.get('/', function(req, res) {
res.render('login.html');
});
app.post('/login', passport.authenticate('local'), function(req, res) {
res.redirect('/myteam.html');
});
I need some expert help...
Regards,
I believe you need a successRedirect and failureRedirect in your app.post.

PassportJs, local strategy cannot be found

I am new to javascript and node. I followed the guide from passportJS and I am getting the error "local strategy cannot be found". I do not know why. my code, basically taken from the website at this point.
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path')
, mongoose = require('mongoose')
, passport = require('passport')
, LocalStrategy = require('passport-local').Strategy;
app.use(passport.initialize());
//to configure the passport
app.use(new LocalStrategy({
usernameField: 'username',
passwordField: 'password'
},
function(username, password, done){
console.log(username);
console.log(password);
People.findOne({username:username},
function(err, user){
if(err){return done(err); }
if(!user){
return done(null, false, {message:
'Incorrect username'});
}
if(!user.validPassword(password)){
return done(null, false, {message:
'Incorrect Password'});
}
return done(null, user);
});
}
));
//route to authenticate the user
app.post('/login',
passport.authenticate('local', { successRedirect:'/accessed',
failureRedirect: '/access'})
);
My error is that "local strategy not found", I looked inside the local-strategy module and found the function that defines it. So I assume the error lies somewhere in the way I am attempting to access that variable.
My server is set up like
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(passport.initialize());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
Here's a boilerplate for using passport-local. The order in which the middleware is configured matters. It also implements serializeUser/deserializeUser which seem to be missing from your code.
var express = require('express')
, http = require('http')
, path = require('path')
, passport = require('passport')
, LocalStrategy = require('passport-local').Strategy;
var app = express();
passport.use(new LocalStrategy(function(username, password, done) {
// insert your MongoDB check here. For now, just a simple hardcoded check.
if (username === 'foo' && password === 'bar')
{
done(null, { user: username });
}
else
{
done(null, false);
}
}));
passport.serializeUser(function(user, done) {
// please read the Passport documentation on how to implement this. We're now
// just serializing the entire 'user' object. It would be more sane to serialize
// just the unique user-id, so you can retrieve the user object from the database
// in .deserializeUser().
done(null, user);
});
passport.deserializeUser(function(user, done) {
// Again, read the documentation.
done(null, user);
});
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({ secret: 'secret' }));
app.use(passport.initialize());
app.use(passport.session());
// route to authenticate the user
app.post('/login', passport.authenticate('local', {
successRedirect: '/accessed',
failureRedirect: '/access'
}));
// app.listen(3012);
When you use curl -v -d "username=foo&password=bar" http://127.0.0.1:3012/login you see you'll get redirected to /accessed, meaning the authentication worked.

Categories

Resources