Passport successRedirect not working!!1 - javascript

I've tried everything. I went through all of the answers ever answered to questions with the slightest similarity. I'm desperate.
I'm using passport module for my website and successRedirect is not working, while failureRedirect does exactly what it's supposed to do.
this is users.js, it does the routing.
'use strict';
const passport = require('passport');
const User = require('../models/user');
module.exports = function(_, passport){
return {
SetRouting: function(router){
console.log('got it');
router.get('/', this.indexPage);
router.get('/signup', this.getSignUp);
router.get('/home', this.homePage);
router.post('/signup', this.postSignUp);
},
indexPage: function(req, res){
console.log('got index page');
return res.render('index');
},
getSignUp: function(req, res){
console.log('got signup page');
return res.render('signup');
},
homePage: function(req, res){
console.log('got home page');
return res.render('home');
},
postSignUp: passport.authenticate('local.signup', {
successRedirect: '/home',
failureRedirect: '/signup',
failureFlash: true
}),
}
and this is passport-local.js, where I do my local strategy function call:
'use strict';
const passport = require('passport');
const User = require('../models/user');
const LocalStrategy = require('passport-local').Strategy;
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
User.findById(id, (err, user) => {
done(err, user);
});
});
passport.use('local.signup', new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true
}, (req, email, password, done) => {
User.findOne({'email': email}, (err, user) => {
if(err){
return done(err);
}
if(user){
return done(null, false, req.flash('error', 'User with email already exist'));
}
const newUser = new User();
newUser.username = req.body.username;
newUser.fullname = req.body.username;
newUser.email = req.body.email;
newUser.password = newUser.encryptPassword(req.body.password);
newUser.save((err) => {
done(null, newUser);
});
});
}));
i'd appriciate your help so so so much!

Your strategy is named 'local.signup'. Strategy names can't contain a period.
There are a number of places where Passport uses the strategy name as an object key and variable identifier. For example, Passport's Authenticator constructs, and later references, an Object of strategies with the strategy names as keys:
Authenticator.prototype.use = function(name, strategy) {
...
this._strategies[name] = strategy;
return this;
};
For this to work, name must be a valid Javascript identifier, meaning no periods.

Related

My code for Authentification on Google is giving me the error ReferenceError: id is not defined

So this is my code that is giving me problems with the authentification. I dont know how to get the id since is already created.
require('dotenv').config()
const express = require ("express");
const bodyParser = require ("body-parser");
const ejs = require ("ejs");
const mongoose = require ("mongoose")
const md5 = require ("md5");
const saltRounds = 10;
var bcrypt = require('bcryptjs');
const session = require('express-session');
const passport = require ("passport");
const passportLocalMongoose = require ("passport-local-mongoose");
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const findOrCreate = require ("mongoose-findorcreate");
const app = express();
app.use(session({
secret: "our little secret",
resave: false,
saveUninitialized:false
}));
app.use(passport.initialize());
app.use(passport.session());
mongoose.connect("mongodb://localhost:27017/userDB", {useNewUrlParser:true});
const userSchema = new mongoose.Schema({
email: String,
password: String,
googleID: String
});
userSchema.plugin(passportLocalMongoose);
userSchema.plugin(findOrCreate);
const User = new mongoose.model ("User", userSchema);
passport.use(User.createStrategy());
passport.serializeUser(function(user, done) {
done(null, user, id);
});
passport.deserializeUser(function(id,done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
passport.use(new GoogleStrategy({
clientID: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
callbackURL: "http://localhost:3000/auth/google/secrets",
},
function(accessToken, refreshToken, profile, cb) {
console.log(profile);
User.findOrCreate({ googleId: profile.id }, function (err, user) {
return cb(err, user);
});
}
));
app.use(express.static("public"));
app.set("view engine", "ejs");
app.use (bodyParser.urlencoded({
extended:true
}));
app.get ("/", function (req, res) {
res.render("home");
});
app.get('/auth/google',
passport.authenticate('google', {scope: ['profile', 'email']})
);
app.get('/auth/google/callback',
passport.authenticate('google', {
successRedirect: '/profile',
failureRedirect: '/fail'
})
);
app.get('/auth/google/secrets',
passport.authenticate('google', { failureRedirect: '/login' }),
function(req, res) {
// Successful authentication, redirect home.
res.redirect('/secrets');
});
app.get ("/login", function (req, res) {
res.render("login");
});
app.get ("/register", function (req, res) {
res.render("register");
});
app.get("/secrets", function (req,res) {
if (req.isAuthenticated()){
res.render("secrets");
}else {
res.rendirect("/login");
}
})
app.get("/logout", function (req, res) {
req.logout();
res.redirect ("/");
});
app.post ("/register", function(req, res) {
User.register({username: req.body.username}, req.body.password, function(err, user){
if (err){
console.log(err);
res.redirect("/register");
} else
passport.authenticate("local") (req, res, function(){
res.redirect("/secrets");
});
});
});
app.post("/login", function(req,res){
const user = new User ({
username: req.body.username,
password: req.body.password
});
req.login(user, function(err){
if(err) {
console.log(err);
}else {
passport.authenticated("local")(req,res, function() {
res.redirect("/secrets");
});
}
});
});
app.listen(3000, function() {
console.log("Server started on port 3000")
});
So when Im trying to run my code but the same error appears all the time in my system.
ReferenceError: id is not defined
at /Users/vivianaandrango/Desktop/Alberto/Secrets code/app.js:55:20
at pass (/Users/vivianaandrango/Desktop/Alberto/Secrets code/node_modules/passport/lib/authenticator.js:291:9)
at Authenticator.serializeUser (/Users/vivianaandrango/Desktop/Alberto/Secrets code/node_modules/passport/lib/authenticator.js:296:5)
at SessionManager.logIn (/Users/vivianaandrango/Desktop/Alberto/Secrets code/node_modules/passport/lib/sessionmanager.js:14:8)
at IncomingMessage.req.login.req.logIn (/Users/vivianaandrango/Desktop/Alberto/Secrets code/node_modules/passport/lib/http/request.js:39:26)
at Strategy.strategy.success (/Users/vivianaandrango/Desktop/Alberto/Secrets code/node_modules/passport/lib/middleware/authenticate.js:256:13)
at verified (/Users/vivianaandrango/Desktop/Alberto/Secrets code/node_modules/passport-oauth2/lib/strategy.js:189:20)
at /Users/vivianaandrango/Desktop/Alberto/Secrets code/app.js:73:14
at /Users/vivianaandrango/Desktop/Alberto/Secrets code/node_modules/mongoose-findorcreate/index.js:47:11
at /Users/vivianaandrango/Desktop/Alberto/Secrets code/node_modules/mongoose/lib/model.js:4999:1
UPDATE
When I add to the code
passport.serializeUser(function(user, done, id) {
done(null, user, id);
});
The system gives me back all my data but on Hyper I get all the information.

Passport.js Multiple login system is not working correctly

I am getting a weird error as all of my login system are working correctly which include local login in system and Google and Facebook login. The problem arose when I try to try to register with google when I have already register the Facebook account and I try to register Google account it gives E11000 duplicate key error collection and vice versa for Facebook. I am using passport.js for authentication and login system here is some code:
const express = require("express");
const app = express();
const BodyParser = require('body-parser');
const ejs = require('ejs');
const session = require("express-session");
const passport = require("passport");
const LocalStratgy = require('passport-local').Strategy;
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const FacebookStrategy = require("passport-facebook").Strategy;
const passportLocalMongoose = require("passport-local-mongoose");
const findOrCreate = require('mongoose-findorcreate');
const mongoose = require('mongoose');
const { static } = require("express");
app.use(express.static('public'));
app.set('view engine', 'ejs');
app.use(BodyParser.urlencoded({extended: true}));
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
mongoose.connect('mongodb://localhost/userDB', {useNewUrlParser: true, useUnifiedTopology: true});
mongoose.set('useCreateIndex', true);
const userSchema = new mongoose.Schema( {
email: String,
password: String,
googleId: String,
facebookId: String
});
userSchema.plugin(passportLocalMongoose);
userSchema.plugin(findOrCreate);
/* userSchema.plugin(encrypt,{secret: process.env.SECRET, encryptedFields: ['password']}); */
const User = new mongoose.model("User", userSchema);
passport.use(new LocalStratgy(User.authenticate()));
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
passport.use(new GoogleStrategy({
clientID: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRETS,
callbackURL: "http://localhost:3000/auth/google/secrets",
userProfileURL: "https://www.googleapis.com/oauth2/v3/userinfo"
},
function(accessToken, refreshToken, profile, cb) {
User.findOrCreate({ googleId: profile.id }, function (err, user) {
return cb(err, user);
});
}
));
passport.use(new FacebookStrategy({
clientID: process.env.FACEBOOK_APP_ID,
clientSecret: process.env.FB_APP_SECRETS,
callbackURL: "http://localhost:3000/auth/facebook/secrets"
},
function(accessToken, refreshToken, profile, cb) {
console.log(profile);
User.findOrCreate({ facebookId: profile.id }, function (err, user) {
return cb(err, user);
});
}
));
app.get("/" ,(req, res) => {
res.render('home');
});
app.get('/auth/google',
passport.authenticate('google', { scope: ['profile'] }));
app.get('/auth/google/secrets',
passport.authenticate('google', { failureRedirect: '/login' }),
function(req, res) {
// Successful authentication, redirect secrets.
res.redirect('/secrets');
});
app.get('/auth/facebook',
passport.authenticate('facebook'));
app.get('/auth/facebook/secrets',
passport.authenticate('facebook', { failureRedirect: '/login' }),
function(req, res) {
// Successful authentication, secrets .
res.redirect('/secrets');
});
app.get("/login" ,(req, res) => {
res.render('login');
});
app.get("/register" ,(req, res) => {
res.render('register');
});
app.get("/secrets", (req, res) => {
if(req.isAuthenticated()){
res.render("secrets");
}else{
res.redirect("/login");
}
})
app.post("/register", (req, res) => {
User.register({username: req.body.username}, req.body.password, function(err, user){
if(err){
console.log(err);
res.redirect("/register");
}else{
passport.authenticate("local")(req, res, function(){
res.redirect("/secrets");
})
}
})
});
app.post("/login", (req, res) => {
const user = new User({
username: req.body.username,
password: req.body.password
});
req.login(user, err => {
if(err){
console.log(err);
}else{
passport.authenticate("local")(req, res, function(){
res.redirect("/secrets");
});
}
})
});
app.get("/logout", (req, res) => {
req.logOut();
res.redirect("/");
})
Note: Individually the Facebook and Google authentication works like a charm but when both used together it throws an error. I store Facebook and Google id in my database as in screenshot: and local system works just fine with Facebook and Google no problem there.
If you follow passport documentation then it's probably not so correct for your usage.
The following will just create an account base on facebook Id
User.findOrCreate({ facebookId: profile.id }, function (err, user) {
return cb(err, user);
});
The following will just create an account base on google Id
User.findOrCreate({ googleId: profile.id }, function (err, user) {
return cb(err, user);
});
However, I'm quite sure your user is identified by email.
Your above queries will create 2 separate _id with same email address.
Hence your query should be corrected to similar as follows
User.updateOne({ email: profile.email }, { googleId: profile.id }, { upsert: true })
And
User.updateOne({ email: profile.email }, { facebookId: profile.id }, { upsert: true })
The above will check whether email exist, if it does, update googleId. If it doesn't exist, create a new user.
In addition, your schema is missing the username field

error implementing passport-facebook authentication with the error code as "FacebookTokenError": redirect_uri isn't an absolute URI. Check RFC 3986

i'm using a localhost to test the passport-facebook authentication, i've been trying to implement the Auth and im getting the error mentioned above i've reviewed similar questions but none seem to help me, i've changed my dns address but to no avail,
this is my passport.js code for facebook authentication
const mongoose = require("mongoose");
const FacebookStrategy = require('passport-facebook').Strategy;
const passport = require('passport');
const User = module.exports = mongoose.model('User', facebookSchema)
var facebookSchema = mongoose.Schema
module.exports = function (_passport) {}
//serialize the user for the session
passport.serializeUser(function (user, done) {
done(null, user.id);
});
//deserialize the user
passport.deserializeUser(function (id, done) {
User.findById(id, function (err, user) {
done(err, user);
});
});
passport.use('facebook', new FacebookStrategy({
clientID: 'XXXXXXXXXX',
clientSecret: 'YYYYYYYYYYYYYYY',
callbackURL: " http://localhost:3000/auth/facebook/callback",
enableProof: true,
profileFields: ['id', 'displayName', 'photos', 'email']
},
function (accessToken, refreshToken, profile, done)
{ let newUser = new User();
// set the user's facebook credentials
newUser.facebook.email = profile.emails[0].value,
newUser.facebook.fullName = profile.displayName,
User.findOne({email:newUser.facebook.email }, function(err, user) {
if(!user) {
newUser.save(function(err, newUser) {
if(err) return done(err);
done(null,newUser);
});
} else {
done(null, user);
}
});
}
));
this is my index.js code for initiallizing app
const rfc = require('rfc-3986');
const express = require('express');
const bodyParser = require('body-parser');
var routes = require('./routes/routes'); //importing route
require('./models/userModel')
app = express();
port = 3000;
require("./config/db"); app.get('/success', (req, res) => res.send("You have successfully logged in"));
app.get('/error', (req, res) => res.send("error logging in"));
const passport = require("passport");
app.use(passport.initialize());
app.use(passport.session());
require('./config/passport')(passport);
app.set(rfc)
routes(app, passport);
app.set('view engine', 'ejs')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended:true}))
app.listen(port,()=>{
console.log('server listening on localhost:' + port)
});
and this is my routes.js for app routing
app.get('/auth/facebook',
passport.authenticate('facebook', {scope:"email"}));
app.get('/auth/facebook/callback',
passport.authenticate('facebook', { failureRedirect: '/login' }),
function(req, res) {
// Successful authentication, redirect home.
res.redirect('/success');`module.exports = function(app, passport) {
app.get('/auth/facebook',
passport.authenticate('facebook', {scope:"email"}));
app.get('/auth/facebook/callback',
passport.authenticate('facebook', { failureRedirect: '/login' }),
function(req, res) {
// Successful authentication, redirect home.
res.redirect('/success');
});
}
});
}
this is the error i get on browser
this is the same error on terminal

Passport Strategy is not being called

Hello SO wonderful users
I am having trouble with passport js since two days and cant figure it out.
Passport Strategy is not being called.
the console.log is not being called!
any ideas ?
here is my code
//init.js
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
module.exports = function(app) {
passport.use(new LocalStrategy(function(username, password, done) {
console.log(username, password);
return done(null, {username: 'agent'});
}));
passport.serializeUser(function(user, done) {
done(null, 'agent');
});
passport.deserializeUser(function(id, done) {
done(null, {username: 'agent'});
});
app.use(passport.initialize());
};
//routes.js
var passport = require('passport');
module.exports = function(app) {
app.get('/login', function(req, res) {
res.send('login');
});
app.post('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) {
return next(err);
}
if (!user) {
console.log(user);
console.log('no user');
return res.redirect('/login');
}
req.logIn(user, function(err) {
if (err) {
return next(err);
}
return res.redirect('/');
});
})(req, res, next);
});
//index.js, where i call the auth
require('./src/auth/init')(app);
require('./src/auth/routes')(app);
edit
solution
the issue was with postman, I hade to change the body post data to x-www-form-urlencoded

Passport Local Strategy doesn't get called NodeJS

I have some trouble implementing passport-local on my NodeJS application. I don't understand what I'm doing wrong here. I'll list the important code for this question here.
app.js:
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(passport.initialize());
app.use(passport.session());
users.js:
var express = require('express');
var router = express.Router();
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var User = require('../models/user.js');
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.getUserById(id, function(err, user) {
done(err, user);
});
});
passport.use(new LocalStrategy(
function(username, password, done) {
console.log('Entered passport'); // This doesn't even happen
User.getUserByUsername(username, function(err, user) {
if (err) throw err;
if (!user) {
console.log('Unknown User');
return done(null, false, {
message: 'Unknown User'
});
}
User.comparePassword(password, user.password, function(err, isMatch) {
if (err) throw err;
if (isMatch) {
return done(null, user);
}
console.log('Invalid Password');
return done(null, false, {
message: 'Invalid Password'
});
});
return done(null, user);
});
}
));
router.post('/login', passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/users/login',
failureFlash: 'Invalid username or password'
}), function(req, res) {
console.log("Authentication Successfull!");
req.flash('success', 'You are logged in');
res.redirect('/');
});
user.js (Model):
module.exports.getUserByUsername = function(username, callback) {
var query = { username: username };
User.findOne(query, callback);
}
module.exports.getUserById = function(id, callback) {
User.findById(id, callback);
}
module.exports.comparePassword = function(candidatePassword, hash, callback) {
bcrypt.compare(candidatePassword, hash, function(err, isMatch) {
if(err) return callback(err);
callback(null, isMatch);
});
}
I'm not getting any syntax errors. In users.js I want to log a message to the console, but it doesn't even get there. The post function on the login gets fired when I just enter a function with a console.log there, but now it seems that it doesn't. It just reloads the page (looks like it). Any help is appreciated.
try to mount session middleware before passport initilized:
var session = require('express-session')
app.use(session({ secret: 'xxxxxxx' }));
app.use(passport.initialize());
app.use(passport.session());

Categories