Following the tutorial here
Auth.js
var passport = require("passport"),
LocalStrategy = require("passport-local").Strategy;
passport.use(new LocalStrategy(
function(username, password, done){
console.log("----", username, password, "----"); //this works fine, get the proper values here.
if(username === "admin" && password === "sw") {
return done(null, {username: "admin"});
}
return done(null, false);
}
));
passport.serializeUser(function(user, done){
done(null, user.username);
});
passport.deserializeUser(function(username, done){
done(null, {username: username});
});
module.exports = passport;
app.js (the relevant bits)
var passport = require("./auth")
var users = require('./routes/users');
.
.
.
app.use('/users', users);
app.post('/', passport.authenticate("local", {
failureRedirect: "/",
successRedirect: "/users"
}));
user route
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function (req, res, next) {
console.log(req.user);
res.render('users', {
title: 'Routed !'
});
});
module.exports = router;
Most of the code works fine, it posts and routes correctly, but, req.user is undefined in the users route, and I'm not able to figure out why.
Related
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
I am using Node.js Passport and I'm trying to figure out how to display username after a successful login. After reading the documentation I've verified that i have Sessions and Middleware configured which is what I need but what are my next steps?
This is my users.js file:
var express = require('express');
var router = express.Router();
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var User = require('../models/user');
// Home
router.get('/index', function(req, res){
res.render('index');
});
// Profile
router.get('/profile', function(req, res){
res.render('profile');
});
// Register
router.get('/register', function(req, res){
res.render('register');
});
// Login
router.get('/login', function(req, res){
res.render('login');
});
// About-us
router.get('/about-us', function(req, res){
res.render('about-us');
});
// Register User
router.post('/register', function(req, res){
var email = req.body.email;
var username = req.body.username;
var password = req.body.password;
// Validation
req.checkBody('username', 'Username is Required').notEmpty();
req.checkBody('email', 'Email is required').notEmpty();
req.checkBody('email', 'Email is not valid').isEmail();
req.checkBody('password', 'Password is required').notEmpty();
var errors = req.validationErrors();
if(errors){
res.render('register',{
errors:errors
});
} else {
var newUser = new User({
email:email,
username: username,
password: password,
});
User.createUser(newUser, function(err, user){
if(err) throw err;
console.log(user);
});
req.flash('success_msg', 'You are now registered. Log In!');
res.redirect('/users/login');
}
});
passport.use(new LocalStrategy(
function(username, password, done) {
User.getUserByUsername(username, function(err, user){
if(err) throw err;
if(!user){
return done(null, false, {message: 'User does not exist!'});
}
User.comparePassword(password, user.password, function(err, isMatch){
if(err) throw err;
if(isMatch){
return done(null, user);
} else {
return done(null, false, {message: 'Invalid password'});
}
});
});
}));
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.getUserById(id, function(err, user) {
done(err, user);
});
});
router.post('/login',
passport.authenticate('local', {successRedirect:'/users/profile', failureRedirect:'/users/login',failureFlash: true}),
function(req, res) {
res.redirect('/users/profile')
});
router.get('/logout', function(req, res){
req.logout();
req.flash('success_msg', '');
res.redirect('/');
});
module.exports = router;
And this is my app.js file:
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var exphbs = require('express-handlebars');
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongo = require('mongodb');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/loginandregister');
var db = mongoose.connection;
var routes = require('./routes/index');
var users = require('./routes/users');
// Init App
var app = express();
// View Engine
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', exphbs({defaultLayout:'layout'}));
app.set('view engine', 'handlebars');
// BodyParser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
// Set Static Folder
app.use(express.static(path.join(__dirname, 'public')));
app.use('/public', express.static('public'));
// Express Session
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
// Passport init
app.use(passport.initialize());
app.use(passport.session());
// Express Validator
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
// Connect Flash
app.use(flash());
// Global Vars
app.use(function (req, res, next) {
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
res.locals.user = req.user || null;
next();
});
app.use('/', routes);
app.use('/users', users);
// Set Port
app.set('port', (process.env.PORT || 3000));
app.listen(app.get('port'), function(){
console.log('Server started on port '+app.get('port'));
});
I've read a similar question on the site and the answer stated that:
app.get('/example', function(req, res) {
res.render('index', { username: req.user.username });
});
needs to be implemented. But I am confused as to where and how? I tried placing it into to my users.js file but i get a "ReferenceError: app is not defined" error in terminal when restarting the node app.
What are my next steps? Any and every help is valued and appreciated. Thank you.
EDIT:
I added
router.get('/profile', function(req, res){
res.render('profile', { username: req.user.username });
});
to my users.js file and added:
<header>
<h1>Hello?</h1>
{{#if user}}
<p>Hello {{username}}</p>
{{else}}
<p>Please <a href='/users/login'>Log In</a></p>
{{/if}}
</header>
to my profile.handlebars page but still no username display. What am i missing???
SOLUTION: Apparently my code was correct and my problem was solved hours ago however it was hiding in plain site. I am using Firefox to build my site and Chrome to conduct all my research and web searching. After DEEP searching i stumbled upon another similar question to my own and this guy complained that he had <p>Hi, {{username}}</p> within his index file but only Hi was showing up within his browser. On the contrary neither Hi or {{username}} was showing in my browser. My entire <p> tag was missing. So i simply loaded my site in Chrome and there it was problem solved! Bad practice on my part for only using one browser but that's what I get for silly mistakes :)
You need to use the rendering part of the mentioned part of this code:
app.get('/example', function(req, res) {
res.render('index', { username: req.user.username });
});
i.e., res.render('index', { username: req.user.username }); at the right/required path.
like you can try using it as
router.get('/profile', function(req, res){
res.render('profile', { username: req.user.username });
});
and consume(use) the rendered variable username in your view for displaying.
If this doesn't work or you have some other problem, refer Nodejs Passport display username also.
My workaround was adding the req.user (if it exists, thus when loggedin) to the rendering. I've included both a hello, {{user}} and Dynamic navbar example.
I don't know if it's because I use handlebars instead of express-handelbars but the example I used to make this does not have to send the req.user object along for the render. It automatically sends it along? So I feel like my workaround is unnecesary if I do it right?
Edit: this solution only works for 1 page. If you go to another route it doesn't send the object along anymore.
Edit2: Apparently with express 4 sending the user object along in req.user is the only way I've found so far. But you'll have to send it along every route that requests data from the data base as well.
Confirmed edit 2 through this example: https://github.com/passport/express-4.x-local-example/blob/master/server.js
// Get Homepage
router.get('/', function(req,res){
Job.find({})
.exec(function(err, jobs){
if(err){
res.send('Error occured', err);
} else {
res.render('jobs', {jobs, user:req.user});
}
});
});
<nav>
<ul class="nav nav-pills pull-right">
{{#if user}}
<li role="presentation"><span class="glyphicons glyphicons-user"></span><p style='color:white'>Hello {{user.name}}</p></li>
<li role="presentation">Logout</li>
{{else}}
<li role="presentation">Login</li>
<li role="presentation">Register</li>
{{/if}}
</ul>
</nav>
I am new to nodejs and trying to develop nodejs demo application referring this article. I followed all steps
and its first phase is working fine for me. But after adding passport authentication it is not working
here is my 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 session = require('express-session');
var passport = require('passport');
//add for Mongo support
//var mongoose = require('mongoose');
var api = require('./routes/api');
var authenticate = require('./routes/authenticate')(passport);
//connect to Mongo
// mongoose.connect('mongodb://localhost:27017/MEAN_Stack');
// require('./models/models.js');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(session({
secret: 'keyboard cat'
}));
//app.use(bodyParser.json());
//app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(passport.initialize());
app.use(passport.session());
//// Initialize Passport
var initPassport = require('./passport-init');
initPassport(passport);
app.use('/api', api);
app.use('/auth', authenticate);
// 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 handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
here is my api.js
var express = require('express');
var router = express.Router();
//Register the authentication middleware
//router.use('/posts');
//api for all posts
router.route('/posts')
//create a new post
.post(function(req, res){
//TODO create a new post in the database
res.send({message:"TODO create a new post in the database rhushikesh"});
})
.get(function(req, res){
//TODO get all the posts in the database
res.send({message:"TODO get all the posts in the database"});
})
//api for a specfic post
router.route('/posts/:id')
//create
.put(function(req,res){
return res.send({message:'TODO modify an existing post by using param ' + req.param.id});
})
.get(function(req,res){
return res.send({message:'TODO get an existing post by using param ' + req.param.id});
})
.delete(function(req,res){
return res.send({message:'TODO delete an existing post by using param ' + req.param.id})
});
module.exports = router;
here is my authenticate.js
var express = require('express');
var router = express.Router();
module.exports = function(passport){
//sends successful login state back to angular
router.get('/success', function(req, res){
res.send({state: 'success', user: req.user ? req.user : null});
});
//sends failure login state back to angular
router.get('/failure', function(req, res){
res.send({state: 'failure', user: null, message: "Invalid username or password1111"});
});
//log in
router.post('/login', passport.authenticate('login', {
successRedirect: '/auth/success',
failureRedirect: '/auth/failure'
}));
//sign up
router.post('/signup', passport.authenticate('signup', {
successRedirect: '/auth/success',
failureRedirect: '/auth/failure'
}));
//log out
router.get('/signout', function(req, res) {
req.logout();
res.redirect('/');
});
return router;
}
here is my passport-init.js
var LocalStrategy = require('passport-local').Strategy;
var bCrypt = require('bcrypt-nodejs');
//temporary data store
var users = {};
module.exports = function(passport){
// Passport needs to be able to serialize and deserialize users to support persistent login sessions
passport.serializeUser(function(user, done) {
console.log('serializing user:',user.username);
return done(null, user.username);
});
passport.deserializeUser(function(username, done) {
return done('we have not implemented this', false);
});
passport.use('login', new LocalStrategy({
passReqToCallback : true
},
function(req, username, password, done) {
if(!users[username]){
console.log('User Not Found with username '+username);
return done(null, false);
}
if(isValidPassword(users[username], password)){
//sucessfully authenticated
return done(null, users[username]);
}
else{
console.log('Invalid password '+username);
return done(null, false)
}
}
));
passport.use('signup', new LocalStrategy({
passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, username, password, done) {
// if (users[username]){
// console.log('User already exists with username: ' + username);
// return done(null, false);
// }
//store user in memory
users[username] = {
username: username,
password: createHash(password)
}
console.log(users[username].username + ' Registration successful');
return done(null, users[username]);
})
);
var isValidPassword = function(user, password){
return bCrypt.compareSync(password, user.password);
};
// Generates hash using bCrypt
var createHash = function(password){
return bCrypt.hashSync(password, bCrypt.genSaltSync(10), null);
};
};
When i try to hit the signup api from postman it always redirect to failure api. I also have tried with the debugger but i am not getting the controller over there.
just uncomment following line in app.js
//app.use(bodyParser.json());
//app.use(bodyParser.urlencoded({ extended: false }));
and update passport-init.js
passport.deserializeUser(function(username, done) {
return done('we have not implemented this', false);
});
to
passport.deserializeUser(function(username, done) {
return done(null, users[username]);
});
I'm using PassportJS to create a login/sign-up program. Then to enter I try to include the username of the user in the path of the redirect. To be more precise, when the user does a login with username and password I want to redirect him/her to the page localhost:3000/library?'username'. How can I do it?
var config = require('./config');
var express = require('express');
var path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');
var dustjs = require('adaro');
var app = express();
var multer = require('multer');
var passport = require('passport');
LocalStrategy = require('passport-local').Strategy;
var mongoose = require('mongoose');
require('./models');
require('express-session');
// Connect to MongoDB here
var mongoose = require('mongoose');
mongoose.connect(config.mongoUrl + config.mongoDbName);
//passport
// --------------- USER PART --------------------\\
var User = mongoose.model('User');
passport.use(new LocalStrategy({
usernameField:'userName',
passwordField:'password'
},
function(username, password, done) {
User.findOne({userName: username}, function (err, user) {
if (err) { return done(err); }
// Return an error as in Node
if (!user) {
return done(null, false, { message: 'Incorrect username.' });
// If user does not exist return the error and the message
}
user.isValidPassword(password, function(err,isMatch){
if (isMatch==true){
return done(null, true);
// Authentication is good, the password is valid
}else{
return done(null, false, {message:"Incorrect password! "})
}
});
});
}
));
passport.serializeUser(function(users, done) {
done(null, 0);
// Invoke passport with user._id authenticated
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
// Deserializza e cerca attraverso l'id
done(err, user);
});
});
// --------------- EDN USER PART --------------------\\
/*--- Configure the multer. used to upload the track from our pc on the server ---*/
app.use(multer({ dest: './public/tracks_folder/',
rename: function (fieldname, filename) {
return filename;
}
}));
// Register model definition here
require('./models');
// dustjs view engine setup
app.engine('dust', dustjs.dust());
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'dust');
// USER
app.use(passport.initialize());
app.use(passport.session());
//configure app
app.use(logger('dev'));
app.use(bodyParser.urlencoded({ extended: false })); // parse application/x-www-form-urlencoded
app.use(bodyParser.json()); // parse application/json
app.use(express.static(path.join(__dirname, 'public')));
// Initialize routers here
var routers = require('./routes/routers');
app.use('/', routers.root);
app.use('/albums', routers.albums);
app.use('/artists', routers.artists);
app.use('/tracks', routers.tracks);
app.use('/users', routers.users);
// USER
app.use('/signup', routers.signup);
app.use('/library', routers.library);
EDIT OF GET
app.get('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) { return next(err); }
if (!user) { return res.redirect('/login'); }
req.logIn(user, function(err) {
if (err) { return next(err); }
return res.redirect('/library/' + user.username);
});
})(req, res, next);
});
app.post('/login',
passport.authenticate('local', { successRedirect: '/library',
failureRedirect: '/'}));
// END USER
module.exports = app;
I'm sure, I'm doing something wrong coz of my lack of experience with this technologies.
So here I'm trying to authenticate my user.
in server.js I have the following :
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
//var configDB = require('./config/database.js');
require('./config/environement.js')(app, express);
require('./config/routes.client.js')(app);
//setting all modules routes
require('./api/oAuth/routes.js')(app);
app.listen(port);
In environement.js :
module.exports = function(app, express) {
app.configure(function() {
var path = require('path');
var mongoose = require('mongoose');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
/* je pense que ce code n'a rien a faire ici*/
var User = require('./../models/user.js');
passport.use(new LocalStrategy(
function(username, password, done) {
User.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);
});
}));
app.use(express.logger());
app.use(express.static(path.join(__dirname + '/../views')));
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.session({secret: 'm4B1teD4nsTaG0rgE'}));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
/*fin*/
mongoose.connect('mongodb://localhost/passport_local_mongoose');
app.set('views', __dirname + '/../views');
app.set('view engine', 'jade'); //extension of views
console.log("config ok");
});
//development configuration
app.configure('development', function() {
app.use(express.errorHandler({
dumpExceptions: true,
showStack: true
}));
});
//production configuration
app.configure('production', function() {
app.use(express.errorHandler());
});
};
And finaly my api/oAuth/routes.js
var User = require('../../models/user.js');
var passport = require('passport');
module.exports = function(app) {
app.get('/register', function(req, res) {
res.render('../api/oAuth/views/register.page.jade');
});
//Route vers /login en get et post
app.get('/login', function(req, res) {
res.render('../api/oAuth/views/login.page.jade');
});
app.post('/api/oAuth/login', function(req, res, next) {
console.log("post login = ok");
passport.authenticate('local',function(req, res) {
// If this function gets called, authentication was successful.
// `req.user` contains the authenticated user.
res.redirect('/users/' + req.user.username);
});
});
app.post('/api/oAuth/register', function(req, res) {
User.register(
new User({
username: req.body.username
}), req.body.password, function(err, user) {
if (err) {
res.send(err);
}
else {
res.send("Success");
}
});
});
}
Edit : Added user.js
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
passportLocalMongoose = require('passport-local-mongoose');
var passport = require('passport');
var User = new Schema({
username: String,
password: String
});
User.plugin(passportLocalMongoose);
passport.serializeUser(function(user, done) {
console.log("serializeUser");
done(null, user);
});
passport.deserializeUser(function(user, done) {
console.log("deserializeUser");
done(null, user);
});
module.exports = mongoose.model('User', User);
When the app goes into passport.authenticate() it does a lot of thing then it return to passport.authenticate() in a loop way. When I use the custom callback I realize that passport.authenticate() is going smoothly but the problem seems to be in req.logIn() function. I don't know what to do in order to make this work, and I tried a lot. I feel like a blind man trying to drive a car :D.