I am a beginner and I have simple node application that use passport js.
Everything works but I want to get username here
app.get('/', checkLogged, (req, res) => {
res.render('index', {name: username});
});
Full project here https://github.com/aruzo1/passport
Can anybody help me?
There is way to do this?
Ps. This database is temporary
app.js
if (process.env.NODE_ENV !== 'production'){
require('dotenv').config();
}
const express = require('express'),
app = express(),
port = process.env.PORT || 3000,
bcrypt = require('bcrypt'),
passport = require('passport'),
initializePassport = require('./passport-config'),
flash = require('express-flash'),
session = require('express-session'),
methodOverride = require('method-override'),
users = []
initializePassport(passport,
email => users.find(user => user.email === email),
id => users.find(user => user.id === id)
);
require('ejs');
app.set('view engine', 'ejs');
app.use(express.urlencoded({extended : false}));
app.use(flash());
app.use(session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(methodOverride('_method'));
app.get('/', checkLogged, (req, res) => {
res.render('index', {name: ""});
});
app.get('/login', checkNotLogged, (req, res) => {
res.render('login', {});
});
app.get('/register', checkNotLogged, (req, res) => {
res.render('register', {});
});
app.post('/register', checkNotLogged, async (req, res) => {
try{
hashedPassword = await bcrypt.hash(req.body.password, 10);
users.push({
id: Date.now().toString(),
name: req.body.name,
email: req.body.email,
password: hashedPassword
});
res.redirect('/login')
}
catch{
res.redirect('/register')
}
});
app.post('/login', checkNotLogged, passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/login',
failureFlash: true
}));
app.delete('/logout', (req, res) => {
req.logOut()
res.redirect('/login')
});
app.listen(port, () => {
console.log('serwer wystartowal')
});
function checkLogged(req, res, next){
if (req.isAuthenticated()){
return next();
}
res.redirect('/login');
}
function checkNotLogged(req, res, next){
if (req.isAuthenticated()){
return res.redirect('/')
}
next()
}
passport-config.js
const localStrategy = require('passport-local').Strategy,
bcrypt = require('bcrypt')
function initialize(passport, getUserByEmail, getUserById){
const authentitaceUser = async (email, password, done) =>{
const user = getUserByEmail(email);
if (user == null){
return done(null, false, {message: 'no user with that email'});
};
try{
if(await bcrypt.compare(password, user.password)){
return done(null, user)
}
else{
return done(null, false, {message: 'wrong password'})
}
}
catch(e){
return done(e)
}
};
passport.use(new localStrategy({
usernameField: 'email'
}, authentitaceUser));
passport.serializeUser((user, done) => {
return done(null, user.id)
});
passport.deserializeUser((id, done) => {
return done(null, getUserById(id))
});
};
module.exports = initialize
res.render('index', {name: req.user.username })
Should do the trick, as long the authentication itself was a success and your user has a 'username' field. Otherwise, req.user.username should throw an error;
Looks like you're using persistent sessions too - you should be able to grab user info from req.user and include it in your response...
app.get('/', checkLogged, (req, res) => {
res.send(req.user);
});
In passport.js when it verifies that user is logged in then the passport.js automatically set the logged-in user info to the res object.So it means whenever user send the request then the req object already having the user info.Here is the function whichdoing this:
passport.setAuthenticatedUser=(req,res,next)=>{
if(req.isAuthenticated())
{
res.locals.user=req.user;
}
next();
}
So in your case when user logged in at that time passport automatically set the user info to every res object.So when any request is coming in that request there is already an user info is present.
So that;s why you need write:
res.render('index', {name: req.user.username })
instead of writing:
res.render('index', {name: username});
Related
if (process.env.NODE_ENV !== "production") {
require("dotenv").config();
}
const express = require("express");
const app = express();
const bcrypt = require("bcrypt");
const passport = require("passport");
const flash = require("express-flash");
const session = require("express-session");
const initializePassport = require("/sandbox/project/passport-config");
initializePassport(
passport,
(email) => users.find((user) => user.email === email),
(id) => users.find((user) => user.id === id)
);
const users = [];
app.set("view-engine", "ejs");
app.use(express.urlencoded({ extended: false }));
app.use(flash());
app.use(
session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false
})
);
app.use(passport.initialize());
app.get("/", checkAuthenticated, (req, res) => {
res.render("index.ejs", { name: "Saleh Khatri" });
});
app.get("/login", (req, res) => {
res.render("login.ejs");
});
app.post(
"/login",
passport.authenticate("local", {
successRedirect: "/",
failureRedirect: "/login",
failureFlash: true
})
);
app.get("/register", (req, res) => {
res.render("register.ejs");
});
app.post("/register", async (req, res) => {
try {
const hashedpassword = await bcrypt.hash(req.body.password, 10);
users.push({
id: Date.now().toString(),
name: req.body.name,
email: req.body.email,
password: hashedpassword
});
res.redirect("/login");
} catch {
res.redirect("/register");
}
});
function checkAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
console.log("Authenticated");
return next();
} else {
console.log("Not Authenticated");
res.redirect("/login");
}
}
app.listen(3000);
//even though i enter correct email and password it displays Not Authenticated
passport-config code:
const LocalStrategy = require("passport-local").Strategy;
const bcrypt = require("bcrypt");
function initialize(passport, getUserByEmail, getUserById) {
const authenticateUser = async (email, password, done) => {
const user = getUserByEmail(email);
if (user == null) {
return done(null, false, { message: "No user with that email" });
}
try {
if (await bcrypt.compare(password, user.password)) {
return done(null, user);
} else {
return done(null, false, { message: "password incorrect" });
}
} catch (e) {
return done(e);
}
};
passport.use(new LocalStrategy({ usernameField: "email" }, authenticateUser));
passport.serializeUser((user, done) => done(null, user.id));
passport.deserializeUser((id, done) => {
return done(null, getUserById(id));
});
}`enter code here`
module.exports = initialize;
//trying to debug it since hour and i am an absolute beginer so i have no idea
//it return not authenticated evertimne even though i enter correct email and password
First of all, this function is immediately executed once server starts listening on the port. Neither in function nor global scopes the user, email, id variables exist.
initializePassport(
passport,
email) => users.find((user) => user.email === email), // email == undefined, user == undefined
id) => users.find((user) => user.id === id) // id == undefined
);
Secondly, you are trying to call an isAuthenticated() method, which isn't declared or expressed, on the request object.
function checkAuthenticated(req, res, next) {
if (req.isAuthenticated()) { // req.isAuthenticated() == undefined, which is false
console.log("Authenticated");
return next();
else {
console.log("Not Authenticated"); // Therefore, this line is executed
res.redirect("/login");
}
}
I can not deliver the solution for you since I've no access to your code or I don't know which middleware you've created which affects request/response objects.
I hope, it helps you to debug the problem. Good luck!
As a beginner I was following a tutorial to make my first website with node.js but when I try to test a login with 100% valid information I get the following error:
Error: Failed to serialize user into session
Something weird I found is that when the error pops up I go back to the previous page, in this case the login page, and a welcome message I added on /profile.hbs/ pops up as if I was in a session.
This is my passport.js
const res = require('express/lib/response');
const passport = require('passport');
const pool = require('../database');
const router = require('../routes/usuario');
const LocalStrategy = require('passport-local').Strategy;
//const helpers = require('../lib/helpers')
passport.use('local.signin', new LocalStrategy({
usernameField: 'username',
passwordField: 'password',
passReqToCallback: true
}, async (req, username, password, done) => {
const rows = await pool.query('SELECT * FROM userr WHERE username = ?', [username])
if (rows.length > 0) {
const user = rows[0];
const validPassword = user.password == password
if (validPassword) {
done(null, user, req.flash('success', 'Bienvenido, ' + user.username))
}else{
done(null, false, req.flash('message', 'Contraseña incorrecta'))
}
} else {
return done(null, false, req.flash('message', 'El usuario no existe'))
}
}));
passport.use('local.signup', new LocalStrategy({
usernameField: 'username',
passwordField: 'password',
passReqToCallback: true
}, async (req, username, password, done) => {
const newUser = {
username: username,
password: password
};
//newUser.password = await helpers.encryptPassword(password);
const result = await pool.query('INSERT INTO userr SET ?', [newUser])
newUser.id_user = result.insertId;
return done(null, newUser);
}));
passport.serializeUser((user, done) => {
console.log(user)
done(null, user.id_user)
});
passport.deserializeUser(async (id_user, done) => {
const rows = await pool.query('SELECT * FROM userr WHERE ID = ?', [id_user]);
done(null, rows[0]);
});
And this is my authentication.js
const express = require('express');
const router = express.Router();
const passport = require('passport');
const { route } = require('./usuario');
router.get('/signup', (req, res) => {
res.render('auth/signup')
});
router.post('/signup', passport.authenticate('local.signup', {
successRedirect: '/profile',
failureRedirect: '/signup',
failureFlash: true
}));
router.get('/signin', (req, res) => {
res.render('auth/signin')
});
router.post('/signin', (req, res, next) => {
passport.authenticate('local.signin',{
successRedirect: '/profile',
failureRedirect: '/signin',
failureFlash: true
})(req, res, next);
})
router.get('/profile', (req, res) => {
res.render('profile');
});
module.exports = router;
I tried to use a different route, I forced out a session (it worked with a deserialize error I had), I redid the login step with completely different variables and a different database but I still got the same response.
I have been trying to figure out why I keep having the error localhost didn’t send any data displayed on the browser whenever I try to login
using a registered username and password. Please, what could be the cause of this problem?
Setting up passport
const passport = require("passport");
const localStrategy = require("passport-local").Strategy;
const { Passport } = require("passport/lib");
Content of Schema file
const mongoose = require("mongoose");
const passportLocalMongoose = require("passport-local-mongoose");
const userSchema = mongoose.Schema({
username: {
type: String,
required: true
},
password: String,
});
userSchema.plugin(passportLocalMongoose);
const User = mongoose.model("User", userSchema);
module.exports = User;
passport configuration
router.use(require("express-session")({
secret: "It's all about coding!",
resave: false,
saveUninitialized: false
}));
router.use(passport.initialize());
router.use(passport.session());
passport.use(new localStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
Register routes
router.get("/register", async(req, res)=>{
res.render("register");
})
router.post("/register", async (req, res)=>{
req.body.username
req.body.password
var newUser = new User ({username: req.body.username})
User.register(newUser, req.body.password, (err, user)=>{
if(err){
console.log(err)
return res.render("register")
}
passport.authenticate("local")(req, res, ()=>{
res.redirect("login");
})
})
})
Login routes:
router.get("/login", (req, res)=>{
res.render("login");
})
router.post("/login", passport.authenticate("local", {
successRedirect: "new",
failureRedirect: "login"
})
The route for the page I'm supposed to be redirected to is:
router.get("/new", isLoggedIn, (req, res) => {
console.log(req.params)
res.render("new", {post: new Post()});
})
router.post("/register", async (req, res)=>{
User.register(username: req.body.username, req.body.password, (err, user)=>{
if(err){
console.log(err)
return res.render("register")
}
passport.authenticate("local")(req, res, ()=>{
res.redirect("/login");
})
})
})
when I pass name: req.user.name to my ejs file it gives me undefined, Can you help me with that please. let me know if you need more information if you need. I have tried a lot of ways but non of then have worked. thanks for the help.
Error:
Cannot read property 'name' of undefined when i call it in index.js
app.js
const express = require("express");
const expressLayouts = require('express-ejs-layouts');
const mongoose = require("mongoose");
const app = express();
const passport = require('passport');
const flash = require('connect-flash');
const session = require('express-session');
const PORT = process.env.PORT || 3000;
const nodemailer = require("nodemailer");
const bodyParser = require("body-parser");
var exphbs = require('express-handlebars');
app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));
app.get("/home", function(req, res) {
res.sendFile(__dirname + "/index.html")
})
app.get("/login", function(req, res) {
res.sendFile(__dirname + "/login.ejs")
})
app.get("/signup", function(req, res) {
res.sendFile(__dirname + "/register.html")
})
app.get("/payment", function(req, res) {
res.sendFile(__dirname + "/payment.html")
})
app.get("/companyInfo", function(req, res) {
res.sendFile(__dirname + "/companyInfo.html")
})
app.get("/FAQ", function(req, res) {
res.sendFile(__dirname + "/Faq.html")
})
app.get("/contactUs", function(req, res) {
res.sendFile(__dirname + "/contactUs.html")
})
app.post("/contactUs", function(req, res) {
const output = `
<h1>You have a new feedback</h1>
<ul>
<h3>Full Name: ${req.body.name}</h3>
<h3>Full Email: ${req.body.email}</h3>
<h3>Order Number: ${req.body.orderNumber}</h3>
</ul>
<h1>The Subject</h3>
<h3>${req.body.subject}</h1>
`;
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: "sziacustomer#gmail.com",
pass: "Sziaszia12"
}
});
var mailOptions = {
from: req.body.email,
to: 'TEAMSZIA#GMAIL.COM',
subject: 'Costumers Email',
html: output
};
transporter.sendMail(mailOptions, function(error, info) {
if (error) {
console.log(error);
res.sendFile(__dirname + ("/failed.html"), { msg: "email sent" });
} else {
console.log('Email sent: ' + info.response);
res.sendFile(__dirname + ("/success.html"), { msg: "email sent" });
}
});
});
//bodyparser
app.use(express.urlencoded({ extended: false }))
const db = require("./config/keys").mongoURI;
require('./config/passport')(passport);
// Express session
app.use(
session({
secret: 'secret',
resave: true,
saveUninitialized: true
})
);
// Passport middleware
app.use(passport.initialize());
app.use(passport.session());
// connect flash
app.use(flash());
// Global variables
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');
next();
});
//connect mangodb using mongoose
mongoose.connect(db, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log("mongoo bd connected"))
.catch(() => console.log(err));
//ejs
app.use(expressLayouts);
app.set('view engine', 'ejs');
app.use("/", require("./routes/index"));
app.use("/dashboard", require("./routes/index"));
app.use("/users", require("./routes/users"))
app.listen(PORT, console.log(`we are live on ${PORT}`));
*
index.js*
const express = require("express");
const router = express.Router();
const mongoose = require("mongoose");
const bcrypt = require('bcryptjs');
const User = require('../models/User');
const users = require("./users");
const LocalStrategy = require('passport-local').Strategy;
const { ensureAuthenticated } = require("../config/auth")
router.get("/", users, (req, res) =>
res.render("welcome", {
login: req.isAuthenticated(),
name: req.user.name //undefined
}))
user.js
const express = require("express");
const router = express.Router();
const bcrypt = require("bcryptjs");
const User = require("../models/User");
const passport = require("passport")
router.get("/login", (req, res) => res.render("login"));
router.get("/register", (req, res) => res.render("register"));
router.post('/register', (req, res) => {
const { name, email, password, password2 } = req.body;
let errors = [];
if (!name || !email || !password || !password2) {
errors.push({ msg: 'Please enter all fields' });
}
if (password != password2) {
errors.push({ msg: 'Passwords do not match' });
}
if (password.length < 6) {
errors.push({ msg: 'Password must be at least 6 characters' });
}
if (errors.length > 0) {
res.render('register', {
errors,
name,
email,
password,
password2
});
} else {
User.findOne({ email: email }).then(user => {
if (user) {
errors.push({ msg: 'Email already exists' });
res.render('register', {
errors,
name,
email,
password,
password2
});
} else {
const newUser = new User({
name,
email,
password
});
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(newUser.password, salt, (err, hash) => {
if (err) throw err;
newUser.password = hash;
newUser
.save()
.then(user => {
req.flash(
'success_msg',
'You are now registered and can log in'
);
res.redirect('/users/login');
})
.catch(err => console.log(err));
});
});
}
});
}
});
// Login
router.post('/login', (req, res, next) => {
passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/users/login',
failureFlash: true,
})(req, res, next);
});
// Logout
router.get('/logout', (req, res) => {
req.logout();
req.flash('success_msg', 'You are logged out');
res.redirect('/users/login');
});
module.exports = router;
passport.js
const LocalStrategy = require('passport-local').Strategy;
const bcrypt = require('bcryptjs');
// Load User model
const User = require('../models/User');
module.exports = function(passport) {
passport.use(
new LocalStrategy({ usernameField: 'email' }, (email, password, done) => {
// Match user
User.findOne({
email: email
}).then(user => {
if (!user) {
return done(null, false, { message: 'That email is not registered' });
}
// Match password
bcrypt.compare(password, user.password, (err, isMatch) => {
if (err) throw err;
if (isMatch) {
return done(null, user);
} else {
return done(null, false, { message: 'Password incorrect' });
}
});
});
})
);
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
}
auth.js
module.exports = {
ensureAuthenticated: function(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
req.flash('error_msg', 'Please log in to view that resource');
res.redirect('/users/login');
},
forwardAuthenticated: function(req, res, next) {
if (!req.isAuthenticated()) {
return next();
}
res.redirect('/');
}
}
I'm makking login system in node js whem I try to get user detail after logged in in log it says undefined
here is app.js
const express = require('express');
const session = require('express-session');
const mongoose = require('mongoose');
const passport = require('passport');
const bodyParser = require('body-parser');
const app = express();
//Passport Config
require('./config/passport')(passport);
//DB config
const db= require('./config/key').dbURI;
//Connect to mongodb
mongoose.connect(db,{ useNewUrlParser: true})
.then(() => console.log('MongoDB Connected...'))
.catch(err => console.log(err));
//ejs
app.set('view engine','ejs');
//Bodyparser
app.use(bodyParser.json());
app.use(express.urlencoded({ extended: false }));
//Express session
app.use(session({
secret: 'secret key',
resave: true,
saveUninitialized: true
}));
//passport middleware
app.use(passport.initialize());
app.use(passport.session());
//Routes
app.use('/', require('./routes/index'));
app.use('/users', require('./routes/users'));
app.listen(3000,console.log("Server started on 3000"));
here is my login system
router.post('/login', (req,res,next) => {
passport.authenticate('local',{
successRedirect: '/dashboard',
failureRedirect: '/users/login',
failureFlash: true
})(req,res,next);
});
here is my dashboard redirection code
route.get('/dashboard',ensureAuthenticated,(req,res) => {
console.log(req.admin);
res.render('dashboard', { admin : req.admin });
});
in this console.log(req.admin); it says undefined in log
here is passport config
const LocalStrategy = require('passport-local').Strategy;
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const passport = require('passport');
//Load user model
const User = require('../models/admin');
module.exports=function(passport){
passport.use(
new LocalStrategy({ usernameField: 'email' }, (email,password,done) => {
//Check if user is available or not
User.findOne({ email: email })
.then(user => {
if(!user){
return done(null, false, console.log('That email is not registerd'));
}
//match password
bcrypt.compare(password, user.password, (err, isMatch) => {
if(err) throw err;
if(isMatch){
return done(null, user);
}else{
return done(null, false, console.log('Password Incorrect'));
}
});
})
.catch(err => console.log(err));
})
);
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
User.findById(id, (err, user) => {
done(err, user);
});
});
}
here is the code of auth.js
module.exports = {
ensureAuthenticated: function(req,res,next){
if(req.isAuthenticated()){
return next();
}
console.log('Please log in to view this resourse');
res.redirect('/users/login');
}
}
and in dashboard.ejs i'm using <%= admin.name %> and it gives error
Cannot read property 'name' of undefined
I don't know what's the matter here or what's i'm missing here
After successful authentication in passport.js, usedetails are assigned to "user" object in request through a passport middleware.
so you can access it using "req.user".
error
Include the new keyword while initializing the Strategy.
solution