Passport Authentication in Nodejs - javascript

Below is the Code that i'm working on but i'm getting errors while executing.
Please help me in creating routes for both login and register forms which are on the same page.
When I'm submitting the registration form with this code, I'm getting an error which says "Bad request"
var express = require ('express');
var app = express();
var path= require('path');
var bodyParser = require('body-parser');
var mongoose = require("mongoose");
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport();
var smtpTransport = require('nodemailer-smtp-transport');
var passport = require('passport');
var LocalStrategy = require('passport-local');
var passportLocalMongoose = require('passport-local-mongoose');
var User = require('./models/user');
app.set('port', process.env.PORT || 3000);
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
app.use(express.static(path.join(__dirname, 'public')));
app.set("view engine", "ejs");
app.use(require('express-session')({
secret: 'Working on enroll Medicare',
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
mongoose.connect("mongodb://localhost/registration");
app.post('/login-register.html', function(req,res)
{
var username = req.body.usernameregister;
var email = req.body.emailregister;
var password1 = req.body.password1register;
var password2 = req.body.password2register;
password1, password2: password2}
User.register(new User({username: username, email: email}), password1, function(err, user){
if(err){
console.log(err);
return res.render('error');
}
passport.authenticate('local')(req, res, function(){
res.redirect("/secret");
});
});
});
login page
app.post("/login-register.html", passport.authenticate('local', {
succesRedirect: "/secret",
failureRedirect: "/error"
}), function(req, res){ });

I think you may have multiple problems here. Here are a few things to check:
You have passport.use(new LocalStrategy(User.authenticate()));. I don't know what User.authenticate() returns, but it should return a function with the arguments function(username, password, done) {...}
It looks like you're using email as the username. You need to add usernameField to the strategy options: new LocalStrategy({usernameField: 'email'}, function(email, password, done){...})
I've also found it really helpful to use a custom callback in the passport.authenticate function to see if the returned error provides any more information about the problem: passport.authenticate('local', function(err, user, info) {console.log(err, user, info)})

Related

MongoDB: Schema hasn't been registered for model "User"

I have been trying to add authentication feature to my angular app using express and mongo and I am getting the following error on line app.js 9:1:
"Schema hasn't been registered for model "User""
'Use mongoose.model(name, schema)',
name: 'MissingSchemaError'
Following is my app.js:
require('dotenv').config();
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var passport = require('passport');
require('./app_server/models/db');
require('./app_server/config/passport'); ----> This line is the one thats throwing the error
var indexRouter = require('./app_server/routes/index');
var usersRouter = require('./app_server/routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'app_server','views'));
app.set('view engine', 'jade');
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')));
app.use(passport.initialize());
app.use('/', indexRouter);
app.use('/users', usersRouter);
Following is my passport.js:
var passport = require('passport');
var LocalStratergy = require('passport-local').Strategy;
var mongoose = require('mongoose');
var User = mongoose.model('User'); ---> Probably the culprit
passport.use(new LocalStratergy({usernameField: 'email'},
function(username, password, done){
User.findOne({email: username}, function(err, user){
if (err) { return done(err); }
if (!user) {
return done(null, false, {
message: 'Incorrect Email.'
});
}
if (!user.validPassword(password)) {
return done(null, false, {
message: 'Incorrect Password.'
});
}
return done(null, user);
});
}
));
Following is my users.js:
var mongoose = require('Mongoose');
var crypto = require('crypto');
var jwt = require('jsonwebtoken');
var userSchema = new mongoose.Schema({
email: {
type: String,
unique: true,
required: true
},
fullname: {
type: String,
require: true
},
hash: String,
salt: String
});
Following is my db.js:
var mongoose = require('Mongoose');
var dbURI = "mongodb://localhost:27017/buddhafinds";
mongoose.connect(dbURI);
//Related functions and logs go here
require('./users');
I have been struggling with this since morning. Any help would be much appreciated. Thank you.
in your passport.js file you create a model without a schema
var User = mongoose.model('User');
try to assign the model to schema in your users.js file and export it from there
exports.User = mongoose.model('User', userSchema)
then just require User in any file you want

How to resolve req.flash is not a function in node js

In my nodejs app it shows an error like:
req.flash is not a function
I have installed connection-flash npm and session and express-session but instead of that it is throwing an error like:
TypeError: req.flash is not a function
in line no. 42 in my register.js. I googled it several times but did not find any proper solution. How can I solve this? Thanks in advance.
This is my register.js:
var express = require('express');
var router = express.Router();
var User = require('../models/user');
var flash = require('connect-flash');
router.get('/', (req, res, next) => {
res.render('register');
})
router.post('/', (req, res, next) => {
var name = req.body.name;
var username = req.body.username;
var email = req.body.email;
var password = req.body.password;
var cpassword = req.body.cpassword;
req.checkBody('name', 'Name is required').notEmpty();
req.checkBody('username', 'User Name 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();
req.checkBody('cpassword', 'Password do not match').equals(req.body.password);
var errors = req.validationErrors();
if(errors){
res.render('register', {
errors:errors
});
}else{
var newUser = new User({
name: name,
username: username,
email: email,
password: password
});
User.createUser(newUser, function(err, user){
if(err) throw err;
console.log(user)
});
req.flash('success_msg', 'Successfully Registered');
res.redirect('/login');
}
})
module.exports = router;
And this is my app.js:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var expressValidator = require('express-validator');
var passport = require("passport");
var LocalStrategy = require('passport-local').Strategy;
var session = require('session');
var flash = require('connect-flash');
var mongoose = require('mongoose');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var loginRouter = require('./routes/login');
var registerRouter = require('./routes/register');
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'twig');
app.use(expressValidator());
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')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/login', loginRouter);
app.use('/register', registerRouter);
app.use(flash());
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(passport.initialize());
app.use(passport.session());
app.use(function(req, res, next) {
next(createError(404));
});
app.use(function(err, req, res, next) {
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Do you try move app.use(flash()) before app.use('/register... ?
app.use(flash());
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/login', loginRouter);
app.use('/register', registerRouter);
and base of flash-connection documnet
Flash messages are stored in the session. First, setup sessions as usual by enabling cookieParser and session middleware. Then, use flash middleware provided by connect-flash.
Follow the document instruction to use flash properly
Use express-flash instead:
npm install express-flash --save
In app.js file add
flash = require('express-flash')
app.use(
session({
resave: true,
saveUninitialized: true,
secret:"yash is a super star",
cookie: { secure: false, maxAge: 14400000 },
})
);
app.use(flash());
use req.flash function wherever you want to send flash messages
res.flash("info","this message will be displayed");
res.redirect('');
In index.hbs file include
{{#if messages.info}}
{{messages.info}}
{{if}}
Define session first.
app.use(
session({
secret: 'secret',
resave: true,
saveUninitialized: true
})
);
Then Define flash
app.use(flash());
Then define your router
app.use('/', indexRouter);
app.use('/users', usersRouter);
The way how you arranged your middlewares are wrong.
If you want to use the flash middileware in your route files, then the flash middileware should be above your router middileware.
Like this:
app.use(flash());
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/login', loginRouter);
app.use('/register', registerRouter);

Passport Unknown authentication strategy

I am following this tutorial on creating an authentication system with passport in Nodejs
Currently I am trying to make the signup form work, but it gives this error:
Error: Unknown authentication strategy "local-signup"
at attempt (/home/jarno/0__projects/nodejs/EasyOrders_2.3.0/node_modules/passport/lib/middleware/authenticate.js:173:37)
at authenticate (/home/jarno/0__projects/nodejs/EasyOrders_2.3.0/node_modules/passport/lib/middleware/authenticate.js:349:7)
at Layer.handle [as handle_request] (/home/jarno/0__projects/nodejs/EasyOrders_2.3.0/node_modules/express/lib/router/layer.js:95:5)
at next (/home/jarno/0__projects/nodejs/EasyOrders_2.3.0/node_modules...
I am pretty sure that the config/passport.js file isn't seen by the routes/users.js file, but as I am a beginner I can't seem to find a solution to my problem.
/routes/users.js
var express = require('express');
var router = express.Router();
var passport = require('passport');
require('../config/passport');
/* GET users listing. */
router.get('/login', function(req, res){
res.render('login', {
title: 'Login'
});
});
router.get('/signup', function(req, res){
res.render('signup', {
title: 'signup'
});
});
router.get('/logout', function(req, res){
res.logout();
res.redirect('/users/login')
});
/* POST users listing */
router.post('/signup', passport.authenticate('local-signup', {
successRedirect : '/profile', // redirect to the secure profile section
failureRedirect : '/signup', // redirect back to the signup page if there is an error
failureFlash : true // allow flash messages
}));
/* functions */
function isLoggedIn(req, res, next) {
if (req.isAuthenticated())
return next();
res.redirect('/users/login');
}
module.exports = router;
/config/passport.js
// config/passport.js
var passport = require('passport');
// load all the things we need
var LocalStrategy = require('passport-local').Strategy;
// load up the user model
var User = require('../models/user');
// expose this function to our app using module.exports
module.exports = function(passport) {
// =========================================================================
// passport session setup ==================================================
// =========================================================================
// required for persistent login sessions
// passport needs ability to serialize and unserialize users out of session
// used to serialize the user for the session
passport.serializeUser(function(user, done) {
done(null, user.id);
});
// used to deserialize the user
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
// =========================================================================
// LOCAL SIGNUP ============================================================
// =========================================================================
// we are using named strategies since we have one for login and one for signup
// by default, if there was no name, it would just be called 'local'
passport.use('local-signup', new LocalStrategy({
// by default, local strategy uses username and password, we will override with email
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, email, password, done) {
// asynchronous
// User.findOne wont fire unless data is sent back
process.nextTick(function() {
// find a user whose email is the same as the forms email
// we are checking to see if the user trying to login already exists
User.findOne({ 'local.email' : email }, function(err, user) {
// if there are any errors, return the error
if (err)
return done(err);
// check to see if theres already a user with that email
if (user) {
return done(null, false, req.flash('signupMessage', 'That email is already taken.'));
} else {
// if there is no user with that email
// create the user
var newUser = new User();
// set the user's local credentials
newUser.local.email = email;
newUser.local.password = newUser.generateHash(password);
// save the user
newUser.save(function(err) {
if (err)
throw err;
return done(null, newUser);
});
}
});
});
}));
};
/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 mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
var morgan = require('morgan');
var session = require('express-session');
var configDB = require('./config/database.js');
mongoose.connect(configDB.url);
require('./config/passport');
// init app
var app = express();
var index = require('./routes/index');
var users = require('./routes/users');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({ secret: 'godaddy420' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
app.use(function (req, res, next) {
res.locals.path = req.path;
next();
});
app.use('/', index);
app.use('/users', users);
// 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');
});
module.exports = app;
config/password.js exports a function but you never call this function. In app.js, you should have something like that :
require('./config/passport')(passport);
)You have to set the routes with passport after the app.use() methods and send passport as argument. so:
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 mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
var morgan = require('morgan');
var session = require('express-session');
var configDB = require('./config/database.js');
mongoose.connect(configDB.url);
require('./config/passport');
// init app
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({ secret: 'godaddy420' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
app.use(function (req, res, next) {
res.locals.path = req.path;
next();
});
// require('./app/routes.js')(app, passport); // load our routes and pass in our app and fully configured passport
var index = require('./routes/index')(app, passport);
var users = require('./routes/users')(app, passport);
app.use('/', index);
app.use('/users', users);
// 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');
});
module.exports = app;
Inside 'index' and 'users' use the passport that you are sending as argument.

Sessions are not persistent [PASSPORT]

I am trying to implement login through OAuth 2.0, however I can't make my sessions persist, it seems right after a users has been authenticated their session is gone. Also, the app seems to get stuck in routes/bnetauth.js at the redirect in the callback function.
These are the files where I use passport
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
//TOOLS
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session'); //Persistant sessions
var passport = require('passport');
//REQUIRE MODELS
require('./models/News');
require('./models/Application');
//REQUIRE ROUTES
var bnetauth = require('./routes/bnetauth')(passport);
var api = require('./routes/api');
var public = require('./routes/public');
var admin = require('./routes/admin');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/karatechop');
require('./config/passport')(passport);
var app = express();
app.use(express.static('views'));
// 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(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
secret: 'ilovescotchscotchyscotchscotch', // session secret
resave: true,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
//Use Routes
app.use('/auth', bnetauth)
app.use('/api', api);
app.use('/admin', admin);
app.use('/', public);
// 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);
});
module.exports = app;
routes/bnetauth.js (Logging in through battle.net, hence the bnetauth name)
var express = require('express');
var router = express.Router();
module.exports = function(passport) {
router.get('/bnet',
passport.authenticate('bnet'));
router.get('/bnet/callback',
passport.authenticate('bnet', {
failureRedirect: '/' }),
function(req, res, next){
console.log('Authenticated: ' + req.isAuthenticated())
####THIS IS WHERE IT GETS STUCK####
res.redirect('https://localhost:3000/');
});
config/passport.js
var BnetStrategy = require('passport-bnet').Strategy;
var BNET_ID = 'hidden'
var BNET_SECRET = 'hidden'
var User = require('../models/user')
// expose this function to our app using module.exports
module.exports = function(passport) {
console.log('Entering passport')
// =========================================================================
// passport session setup ==================================================
// =========================================================================
// required for persistent login sessions
// passport needs ability to serialize and unserialize users out of session
// used to serialize the user for the session
passport.serializeUser(function(user, done) {
console.log('Serializing')
done(null, user.id);
});
// used to deserialize the user
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
console.log('Deserializing')
done(err, user);
});
});
passport.use(new BnetStrategy({
clientID: BNET_ID,
clientSecret: BNET_SECRET,
region: 'eu',
callbackURL: "https://localhost:3000/auth/bnet/callback"
}, function(accessToken, refreshToken, profile, done) {
console.log(profile)
console.log(accessToken)
User.findOne({id: profile.id}, function(err, user){
console.log("Trying!")
if(err)
return done(err);
if(user) {
return done(null, user);
} else {
var newUser = new User();
newUser.id = profile.id,
newUser.token = accessToken,
newUser.battle_tag = profile.battletag
newUser.save(function(err) {
if (err)
throw err;
return done(null, newUser);
});
}
});
}));
};
return router;
}
I found the solution to my problem!
The problem was in my serialize and deserialize functions in config/passport.js
On my user model, I had two forms of ids.
The _id applied by mongo
The id that I save from the users object passed back to me from battle.net (this is the ID of the user on battle.net).
In serialize, the id that would be used when serializing the user to the session would be the battle.net id (since I was calling user.id and not user._id
Then, in the deserialize when extracting data from the user object, I was using mongo's findById function, which uses the ._id (which is totally different from .id in my user's object, hence it returned 'undefined'.
Changing the .id to ._id in the serialize function solved my problem, and sessions are now working and are persistent.

Node.js Passport Display username after successful login

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>

Categories