Passport Session Failed to serialize (Bad Gateway) - javascript

I am using the following dependencies:
express session
passport
passport-local
passport-local-mongoose
When I try to register a user and they post the data. The data get saved to the database but it give a bad request. Also when I try to use req.user.id in the Tweet.find() it gives undefined and I also console.log(req.user) and it give me undefined. And once a error came that failed to serialize session one or two time. Can anybody help me. Here is some code sorry in advance if this is to much code as I was not sure that which part of the code was important.
//-----------------------//Require---------------------
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 LocalStratagy= require("passport-local").Strategy;
const passportLocalMongoose = require("passport-local-mongoose");
const mongoose = require("mongoose");
//-----------------------//App.use---------------------
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
}));
//-----------------------//Passport---------------------
app.use(passport.initialize());
app.use(passport.session());
//-----------------------//Mongoose---------------------
mongoose.connect('mongodb://localhost/Twitter', {useNewUrlParser: true, useUnifiedTopology: true});
mongoose.set('useCreateIndex', true);
const tweetschema = new mongoose.Schema({
username: String,
password: String,
tweets: String
});
//-----------------------//Schema Plgin---------------------
tweetschema.plugin(passportLocalMongoose);
//-----------------------//New Model---------------------
const Tweet = new mongoose.model("Tweet", tweetschema);
//-----------------------//Local Strategy-------------------
passport.use(new LocalStratagy(Tweet.authenticate()));
//-----------------------//Seralize Passport---------------------
passport.serializeUser(function(user, done) {
console.log(user);
done(null, user.id);
});
//-----------------------//Desarlize Passport---------------------
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
app.post("/tweets", bodyParser.urlencoded({extended: true}), (req, res)=>{
const Gottweets= req.body.tweet;
console.log(Gottweets);
console.log(req.user);
/* Tweet.findById(req.tweet.id, (err, foundUser)=>{
if(err){
console.log(err);
res.redirect("/tweets");
}else{
if(foundUser){
foundUser.tweets = Gottweets;
foundUser.save(()=>{
res.redirect("/");
})
}
}
})
*/
});
app.post("/regsiter",bodyParser.urlencoded({extended: true}), (req, res)=>{
console.log(req.body.email);
Tweet.register({username: req.body.email}, req.body.password, (err, user)=>{
if(err){
console.log(err);
res.redirect("/regsiter");
}else{
if(user){
passport.authenticate("local")(req, res, function(){
res.redirect("/regsiter");
})
}
}
})
});
<%- include('partials/header') %>
<form action="/regsiter" method="post" class="login">
<label for="emial" class="email">
Email
<input type="email" name="email" id="email">
</label>
<label for="password">
Password
<input type="password" name="password" id="password">
</label>
<div class="soicalLogin">
Facebook
Google
</div>
<button type="submit">Register</button>
</form>
<%- include('partials/footer') %>

You can try rewriting your POST /register endpoint with this example
app.post("/register",bodyParser.urlencoded({extended: true}), (req, res, next) => {
console.log(req.body.email);
Tweet.register({username: req.body.email}, req.body.password, (err, user)=>{
if(err){
console.log(err);
res.redirect("/regsiter");
return;
}
if(!user){ // also handle the case where user is undefined
return res.status(500).json({ yourMessage: 'error' });
}
next();
})
}, passport.authenticate("local", { successRedirect: '/', failureRedirect: '/register' }));
It's not a good idea to override the next function given to passport.authenticate("local")
Now the error should be gone, let me know if this code sample doesn't work.
Hope it helps

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.

Showing passport.js messages with flash

Im trying to display flash messages from passport.js but for some reason they are not showing - It is however showing "credentials not found" (but thats not the error message i want)
The code below - App,config and ejs (respectively)
const express = require('express')
const app = express()
const bcrypt = require('bcrypt')
app.set('view engine', 'ejs')
const initializePassport = require('./passport-config')
const passport = require('passport')
const flash = require('express-flash')
const session = require('express-session')
const accounts = [
]
app.use(passport.initialize())
initializePassport(passport, accounts.find(user => user.email === email))
app.use(express.urlencoded({ extended: true }))
app.use(passport.session())
app.use(session({
secret: 'secret',
resave: false,
saveUninitialized: false
}))
app.use(flash())
app.get('/login', (req, res) => {
res.render('login')
})
app.post('/login', passport.authenticate(('local'), {
successRedirect: '/',
failureRedirect: '/login',
failureFlash: true
}))
app.get('/register', (req, res) => {
res.render('register')
})
app.post('/register', async (req, res) => {
const { name, email, password } = req.body
accounts.push({ id: Date.now().toString(), name, email, password: await bcrypt.hash(password, 10) })
console.log(accounts);
res.render('login')
})
app.listen(3000, () => {
console.log('server is running ');
})
//////////
const LocalStrategy = require('passport-local').Strategy
const bcrypt = require('bcrypt')
const initializePassport = (passport, getUserByEmail) => {
const authenticateUser = async (email, password, done) => {
const user = getUserByEmail(email)
if (user == null) {
return done(null, false, { message: "email is not on our db" })
}
try {
if (await bcrypt.compare(password), user.password) {
return done(null, user)
} else {
return done(null, false, { message: 'wrong password ' })
}
} catch (error) {
return done(error)
}
}
passport.use(new LocalStrategy(({ usenameField: 'email' }), authenticateUser))
}
module.exports = initializePassport
//////////
<h1>Login</h1>
<% if(messages.error){ %>
<p><%=messages.error%></p>
<% } %>
<form action="/login" method="POST">
<label for="email">email</label>
<input id="email" name="email" type="text">
<label for="password">password</label>
<input id="password" name="password" type="text">
<button>Log in</button>
</form>
<p> register</p>
Can anyone see the issue? I am following a tutorial and this seems to match exactly with his code
The documentation states that it requires cookieParser in order to work. I would add the following to your file:
const cookieParser = require('cookie-parser');
app.use(cookieParser());
Documentation: https://github.com/RGBboy/express-flash#usage
You could also potentially look at the source project for this extension called connect-flash. There is a wealth of information on implementing this package which should transfer well to the express-flash extension.
Working example: https://gist.github.com/vesse/9e23ff1810089bed4426

Node if/else statement using EJS

Could anyone help me figure out what I'm doing wrong here? I'm a semi beginner coder, and looking to learn more. Im having an issue trying to use and if/else statement to change my header to display "login" when a user is logged out, and "logout" when a user is logged in.
All my routes work fine, but just getting the logic right is giving me issues.
index.js
I have tried changing the "serializeduser" to "user" and a bunch of other things that wouldn't work for me.
require('dotenv').config();
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require("mongoose");
const session = require('express-session');
const passport = require("passport");
const passportLocalMongoose = require("passport-local-mongoose");
const flash = require("flash");
const app = express();
app.use(express.static("public"));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(session({
secret: process.env.SECRET,
saveUninitialized: false,
resave: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
mongoose.connect("mongodb://localhost:27017/userDB", {
useNewUrlParser: true
});
mongoose.set("useCreateIndex", true);
const userSchema = new mongoose.Schema({
email: String,
password: String,
googleId: String,
secret: String
});
userSchema.plugin(passportLocalMongoose);
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);
});
});
app.get("/", function(req, res) {
res.render("home");
});
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.redirect("/login");
}
});
app.get('/logout', function(req, res) {
req.logout();
res.clearCookie();
res.redirect('/');
});
app.post('/login', passport.authenticate('local', {
successRedirect: '/secrets',
failureRedirect: '/login',
failureFlash: true,
}));
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("/");
} else {
passport.authenticate("local")(req, res, function() {
res.redirect("/secrets");
});
}
});
});
app.listen(3000, function() {
console.log("Server started on port 3000.");
});
header.ejs snippet
<% if ('serializeUser') { %>
<li class="nav-item">
<a class="nav-link" href="/login"> login</a></li>
<% } else { ('deserializeUser') %>
<li class="nav-item">
<a class="nav-link" href="/logout">logout</a></li>
<% } %>

Unable to determine error messages while implementing passport.js local-signup

I'm adapting this local authentication implementation (using Sequelize instead of Mongoose, but this should be DB agnostic), and here is my following directory hierarchy:
app.js
package.json
node_modules
config
-----env
-----config.js
-----passport.js
-----sequelize.js
views
-----index.ejs
-----login.ejs
-----signup.ejs
I have the routes defined in app.js and the models defined in sequelize.js, as described below:
./app.js
const express = require('express');
const http = require('http');
const https = require('https');
const sequelize = require('sequelize');
const db = require('./config/sequelize');
const config = require('./config/config');
const passport = require('passport');
const strategies = require('./config/passport')(passport);
const env = 'development';
const app = express();
const port = 3000;
app.set('view engine', 'ejs');
app.use(passport.initialize());
app.use(passport.session());
app.listen(port);
function isLoggedIn(req, res, next) {
if (req.isAuthenticated()){
return next();
}
else{
res.redirect('/');
}
}
app.post('/signup', function(req, res){
console.log("nothing");
passport.authenticate('local-signup', {
successRedirect : '/profile',
failureRedirect : '/signup',
failureFlash : false // allow flash messages
}
}));
./config/passport.js
const LocalStrategy = require('passport-local').Strategy;
const passport = require('passport');
const User = require('../config/sequelize');
module.exports = function(passport) {
passport.serializeUser(function(user, done) {
console.log("Serializing user");
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
console.log("Deserializing user");
User.findById(id, function(err, user) {
done(err, user);
});
});
passport.use('local-signup', new LocalStrategy({
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true
},
function(req, email, password, done) {
console.log("Inside local strategy");
process.nextTick(function() {
User.findOne({ 'local.email' : email }, function(err, user){
if (err){
console.log("nothing");
return done(err);
}
if (user) {
console.log("There is already a user attached to this email.");
return done(null);
}
else {
const newUser = new User();
newUser.local.email = email;
newUser.local.password = password;
newUser.save(function(err) {
if (err)
throw err;
return done(null, newUser);
});
}
});
});
}));
};
./views/signup.ejs
<!doctype html>
<html>
<head>
<title>Node Authentication</title>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css">
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css"> <!-- load fontawesome -->
<style> body { padding-top:80px; }</style>
</head>
<body>
<div class="container">
<div class="col-sm-6 col-sm-offset-3">
<h1><span class="fa fa-sign-in"></span> Signup</h1>
<% if (message.length > 0) { %>
<div class="alert alert-danger"><%= message %></div>
<% } %>
<form action="/signup" method="post">
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" name="email">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" name="password">
</div>
<button type="submit" class="btn btn-warning btn-lg">Signup</button>
</form>
<hr>
<p>Already have an account? Login</p>
<p>Or go home.</p>
</div>
</div>
</body>
</html>
And for good measure:
./config/sequelize.js
const path = require('path');
const Sequelize = require('sequelize');
const _ = require('lodash');
const config = require('./config');
const db = {};
const sequelize = new Sequelize(config.db.name, config.db.username, config.db.password, {
host: config.db.host,
port: config.db.port,
dialect: 'mysql',
storage: config.db.storage
});
sequelize
.authenticate()
.then(function(err) {
console.log('Connection has been established successfully.');
}, function (err) {
console.log('Unable to connect to the database:', err);
});
const User = sequelize.define('User', {
username: Sequelize.STRING,
email: Sequelize.STRING,
password: Sequelize.STRING
});
sequelize.sync();
module.exports = User;
What occurs when I run the app and press the signup button
is the "nothing" console.log statement in config/passport.js, but when I try to diagnose the source of the error by adding console.log statements on 'err' nothing appears to show up on cmd.

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