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!
Related
I try to connect my Login page with mongoose. Unfortunetly it doesn`t work.
I get the error:
ObjectParameterError: Parameter "filter" to findOne() must be an object, got 637798b57bfa9d5fbede9c30
I tried to find the solution the whole day, but I cant figure it out. Im also still learning coding and struggle to understand everything of it, but most I understand.
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 initializePassport = require("./passport-config")
const flash = require("express-flash")
const session = require("express-session")
const methodOverride = require("method-override")
const mongoose = require("mongoose")
const User = require("./user")
const uri = 'abc'
async function connect(){
try{
await mongoose.connect(uri)
console.log("connected")
} catch (error){
console.error(error)
}
}
connect();
const user = User
initializePassport(
passport,
email => User.find(user => user.email === email),
_id => User.find(user => user._id === _id)
)
app.set('view-engine', 'ejs')
app.use(express.urlencoded({extended: false}))
app.use(flash())
app.use(session({
secret: process.env.SESSION_SECRET,
resave: false, // We wont resave the session var if nothing is changed
saveUninitialized: false
}))
app.use(passport.initialize())
app.use(passport.session())
app.use(methodOverride("_method"))
function initialize(passport, getUserByEmail, getUserById) {
const authenticateUser = async (email, password, done) => {
const user = await User.findOne({email:email});
console.log(user);
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))
})
}
module.exports = initialize
app.get('/', checkAuthenicated, (req, res)=> {
res.render('index.ejs', {name: req.body.name})
})
app.get('/login', checkNotAuthenicated, (req, res)=> {
res.render('login.ejs')
})
app.post("/login", checkNotAuthenicated, passport.authenticate("local", {
successRedirect: "/",
failureRedirect: "/login",
failureFlash: true
}))
app.get('/register', checkNotAuthenicated, (req, res)=> {
res.render('register.ejs')
})
app.post("/register", checkNotAuthenicated, async (req, res) => {
try {
const hashedPassword = await bcrypt.hash(req.body.password, 10)
//users.push({
const user = new User({
id: Date.now().toString(),
username: req.body.name,
email: req.body.email,
password: hashedPassword
})
user.save().then(()=> console.log("User saved"))
console.log(user)
res.redirect("/login")
} catch (e){
console.log(e);
res.redirect("/register")
}
})
app.delete("/logout", (req, res) =>{
req.logOut(
res.redirect("/login")
)
})
function checkAuthenicated(req, res, next){
if (req.isAuthenticated()){
return next()
}
res.redirect("/login")
}
function checkNotAuthenicated(req, res, next){
if (req.isAuthenticated()){
return res.redirect("/")
}
next()
}
app.listen(3000)
const bcrypt = require('bcrypt')
const mongoose = require("mongoose")
const userShema = new mongoose.Schema({
id: String,
username: String,
email: String,
password: String
})
module.exports = mongoose.model("User", userShema)
const LocalStrategy = require('passport-local').Strategy
const bcrypt = require('bcrypt')
const User = require("./user")
function initialize(passport, getUserByEmail, getUserById) {
const authenticateUser = async (email, password, done) => {
const user = await User.findOne({email:email});
console.log(user);
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(function(_id, done) {
User.findOne(_id, function (err, User) {
done(err, User);
});
});
}
module.exports = initialize
I think the problem lies somewhere in here:
passport.use(new LocalStrategy({ usernameField: 'email' }, authenticateUser))
passport.serializeUser((User, done) => done(null, User._id))
passport.deserializeUser(function(_id, done) {
User.findOne(_id, function (err, User) {
done(err, User);
});
});
But I`m not sure...
Thanks very much for your help.
You are mixing findOne and findById
findById does not need an object but the _id. As the docs (and also the method name) explain, under the hook it find by the id, so is like to do findOne({_id: id}).
From the docs:
findById(id) is almost* equivalent to findOne({ _id: id })
So the problem is you are trying to use simply the _id when the method expect an object to match the filter.
So you can use User.findOne({_id: _id}) or User.findById(_id)
I was developing a little software with registration and login forms in NodeJS. The code is blocked by this error "TypeError: initializePassport is not a function" at line 14 of server.js file.
This is the file server.js:
if (process.env.NODE_ENV !== "production"){
require("dotenv").config()
}
const express = require("express")
const app = express()
const bcrypt = require("bcryptjs")
const passport = require("passport")
const flash = require("express-flash")
const session = require("express-session")
const initializePassport = require("./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.use(passport.session())
app.get("/", (req, res) => {
res.render("index.ejs")
})
app.get("/login", (req, res) => {
res.render("login.ejs")
})
app.post("/login", passport.authenticate("local", {
successRedirect: "/",
failureRedirect: "/login",
failureFlash: true
}))
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")
}
console.log(users)
})
app.get("/register", (req, res) => {
res.render("register.ejs")
})
app.listen(3000)
and this is the passport-config.js:
const LocalStrategy = require('passport-local').Strategy
const bcrypt = require("bcryptjs")
function initialize(passport, getUserByEmail) {
const authenticateUser = async (email, password, done) => {
const user = getUserByEmail(email)
if(user==null){
return done(null, false, {message:"Non ci sono utenti con questo nome"})
}
try{
if(await bcrypt.compare(password,user.password)){
return done(null, user)
} else {
return done(null, false, {message:"Password Errata"})
}
} 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))
})
}
module.export = initialize
I tried to rename the const "initializePassport" or restarting the server but it doesn't work. At the start the server will block there on the same error.
I also tried changing the function I export from the passport-config.js.
Any other solutions? Tnx
I think that it is module.exports = initialize and not module.export = initialize.
If you wanna a named exports you use only exports = value
Try with this way: module.exports for default exports.
passport-config.js
function initialize() {}
exports.initialize = initialize
server.js
const initializePassport = require("./passport-config").initialize
initializePassport()
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});
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 have been browsing the forum but I am unable to find the error in my code , it always results in false and I am not able to solve it , Please help me...
Is there any other way to authenticate user instead of passport so that I can use it.I am adding more sentences as it is not allowing me to post my query,Sorry..
const http = require("http"),
hostname = "127.0.0.1",
port = 3000,
bodyParser = require("body-parser"),
mongoose = require("mongoose"),
express = require("express"),
passport = require("passport"),
localStrategy = require("passport-local"),
passportLocalMongoose = require("passport-local-mongoose"),
User = require("./models/user");
app = express();
mongoose.connect("mongodb://localhost/drive", { useNewUrlParser: true });
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(passport.initialize());
app.use(passport.session());
app.use(
require("express-session")({
secret: "Beta tumse na ho payega",
resave: false,
saveUninitialized: false
})
);
passport.use(new localStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.use(bodyParser.urlencoded({ extended: true }));
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader("Content-Type", "text/plain");
});
app.get("/", function(req, res) {
res.render("index");
});
app.get("/register", function(req, res) {
res.send("hello");
});
app.get("/login", function(req, res) {
res.render("login");
});
app.post(
"/login",
passport.authenticate("local", {
successRedirect: "/",
failureRedirect: "/login"
}),
function(req, res) {}
);
app.get("/logout", function(req, res) {
req.logout();
res.redirect("/");
});
function isLoggedIn(req, res, next) {
if (req.isAuthenticated()) {
return next();
} else {
console.log("Not logged");
res.redirect("/login");
}
}
app.get("/secret", isLoggedIn, function(req, res) {
res.send("You are logged in");
});
app.post("/register", function(req, res) {
if (req.body.password === req.body.cpassword) {
User.register(
new User({ username: req.body.username }),
req.body.password,
function(err, user) {
if (err) console.log(err);
else
passport.authenticate("local")(req, res, function() {
res.send("signed up");
});
}
);
} else res.send("Password Mismatch");
});
//DRIVE SCHEMA
//var driveSchema = mongoose.Schema({
// title: String,
// created: { type: Date, default: Date.now }
//});
app.listen(port, hostname, function() {
console.log("Server is running at " + hostname + "/" + port);
});
//./models/user.js file
const mongoose = require("mongoose"),
passportLocalMongoose = require("passport-local-mongoose");
var UserSchema = new mongoose.Schema({
username: String,
password: String
});
UserSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("User", UserSchema);
I have used passport and jwt library, to authenticate and maintain session for the user. There is no need to maintain user session on server side.
apis/apis.js : This file has all apis end points. /login url will authenticate user using passport and send a token to the client using jwt
const passport = require('passport')
const expRoute = require('express').Router();
let exporter = process.exporter;
expRoute.post('/login', (req, res, next) => {
passport.authenticate(
'local',
{
// successRedirect: '/',
// failureRedirect: '/login',
successFlash: 'Welcome!',
failureFlash: 'Invalid username or password.'
},
(err, user, info) => {
if (err) {
return res.status(500).json(err)
}
else if (user) {
return res.status(200).json({
token: exporter.generateToken(user)
})
}
else {
return res.status(400).json(info)
}
}
)(req, res, next);
})
expRoute.get('/view', exporter.authenticateToken, (req, res) => {
let param = req.finalTokenExtractedData
if (param && exporter.isObjectValid(param, 'tokenId', true, true)) {
let condition = {
_id: param.tokenId
}
let options = {
_id: 0,
password: 0,
__v: 0
}
process.USER.findOne(condition, options) // mongo find
.then((data) => {
res.status(200).json({
result: data,
msg: 'success'
})
})
.catch((mongoErr) => {
exporter.logNow(`USER mongo Error: ${mongoErr}`)
res.status(400).json({
msg: 'user not found'
})
})
}
else {
res.status(404).json({
msg: 'invalid token'
})
}
})
module.exports = expRoute
common/env.js: This file will initialise all connections such mongo, require few files will be used as global
process.CONFIG = require('../configs/config.json')
process.exporter = require("../lib/exporter.js")
process.dbInit = (globalName, mongoUrl, collectionName) => {
require("../models/db-init.js")(mongoUrl, collectionName)
.then((modelObj) => {
process[globalName] = modelObj // will be used as global
})
.catch((dbInitErr) => {
process.exporter.logNow(`dbInit Error: ${dbInitErr}`)
process.exit()
});
}
lib/exporter.js: This file has exporter class which consist of all major functions like mongo connection, authenticateToken, verifyPassword, etc.
const fs = require('fs'),
redis = require("redis"),
path = require("path"),
mongoose = require('mongoose'); mongoose.set('useCreateIndex', true);
const Schema = mongoose.Schema;
var bcrypt = require('bcryptjs')
var jwt = require('jsonwebtoken')
class Exporter {
mongoConnection(mongoURI, schemaObj) {
return new Promise(async (resolve, reject) => {
if (!mongoURI || typeof mongoURI == 'undefined' || mongoURI.length < 1)
return reject('invalid mongo connection url');
return resolve(mongoose.createConnection(mongoURI, { useNewUrlParser: true }))
})
}
createMongoSchema(schemaObj) {
return (new Schema(schemaObj));
}
createMongoModel(mongoDB, collectionName, newSchema) {
if (newSchema)
return mongoDB.model(collectionName, newSchema)
return mongoDB.model(collectionName)
}
authenticateToken(req, res, next) {
const bearerHeader = req.header('authorization')
if (typeof bearerHeader != 'undefined') {
const bearer = bearerHeader.split(' ')
const bearerToken = bearer[1]
jwt.verify(bearerToken, process.CONFIG.jwt.token.activated, (err, data) => {
if (err)
res.status(400).json({
msg: "Invalid token or please try to login again"
})
else {
process.exporter.getSingleHashKeysValuesFromRedis('expired_token', bearerToken)
.then((redisTokendata) => {
if (redisTokendata)
res.status(400).json({
msg: "token expired"
})
else {
req.finalTokenExtractedData = data
// if (req.originalUrl.trim() == process.logoutURL.trim())
req.jwtToken = {
token: bearerToken,
secret: process.CONFIG.jwt.token.activated
}
next()
}
})
.catch((redisTokenError) => {
process.exporter.logNow(`redis token error: ${redisTokenError}`)
res.status(400).json({
msg: "Some went wrong while checking token. Please try later."
})
})
}
})
}
else
res.status(400).json({
msg: "invalid token"
})
}
generateToken(data) {
let expiry = new Date();
// expiry.setDate(expiry.getDate() + 7)
expiry.setMinutes(expiry.getMinutes() + 5)
return jwt.sign({
tokenId: data._id,
exp: parseInt(expiry.getTime() / 1000),
}, process.CONFIG.jwt.token.activated)
}
createPassword(password) {
return new Promise((resolve, reject) => {
if (typeof password == 'undefined' && password == '')
return reject('password empty')
bcrypt.hash(password, 10, async (bErr, hash) => {
if (bErr)
reject(bErr)
else
resolve(hash)
})
})
}
verifyPassword(enteredPassword, savePassword) {
return bcrypt.compareSync(enteredPassword, savePassword)
}
}
module.exports = (new Exporter());
index.js: This is file which you will execute node index.js.
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const passport = require('passport');
require('./common/env')
require('./configs/passport')
const app = express()
const cors = require('cors')
app.use(cors());
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true}))
app.use(passport.initialize())
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
let apis = require('./apis/api')
app.use('/user', apis)
/**
* 404 Handler
*/
app.use((req, res, next)=>{
return res.status(404).send("Endpoint "+req.url +" not found");
})
/**
* if any error or exception occurred then write into a JS file so that app can be restarted
*/
process.on('uncaughtException', (err) => {
console.error(err.stack);
});
app.listen(3000, function(server) {
console.log("App listening at 3000");
});
When index.js file has been executed successfully and listening to a port 3000, then use this URL http://localhost:3000/user/login for authentication, it will accept your username and password, then authenticate using passport and send a token to the client as response. The token can contain user data in encrypted form and have expiry time.
Reference link: https://github.com/arjun-707/login-logout-jwt-nodejs
You need the express-session module.
server.js
// Require a possible config.js file with your configuration variables
const Config = require('./models/config.js');
// If the config module is formed as a class
const config = new Config();
const express = new('express');
const app = express();
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);
const uuid = require('uuid/v4');
const mongoose = require('mongoose');
// Require your custom passport local strategy file
const passport = require('./models/sessions');
mongoose.connect('mongodb://localhost:27017/your_db_name', {
useNewUrlParser: true
});
// Set the session options
app.use(session({
// Use UUIDs for session IDs
genid: (req) => {
return uuid()
},
// If you want to store the session in MongoDB using mongoose
// Require your personal mon
store: new MongoStore({
mongooseConnection: mongoose.connection
}),
// Define the session secret in env variable or in config file
secret: process.env.SESSION_SECRET || config.sessionSecretKey,
resave: false,
saveUninitialized: true
}));
// Initialize the passport module
app.use(passport.initialize());
// Tell to passport to use session
app.use(passport.session());
./models/session.js
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const bcrypt = require('bcrypt-nodejs');
// Your custom MongoDB connection module
const db = require('./db');
// Configure passport.js to use the local strategy
passport.use(new LocalStrategy({
usernameField: 'username'
},
(username, password, done) => {
db.User.find({
username: username // But it could use email as well
}).then(res => {
const user = JSON.parse(JSON.stringify(res[0]));
if (!user) {
return done(null, false, {
message: 'Invalid credentials.\n'
});
}
if (!bcrypt.compareSync(password, user.password)) {
return done(null, false, {
message: 'Invalid credentials.\n'
});
}
return done(null, user);
}).catch(error => done(error));
}
));
// Tell passport how to serialize the user
passport.serializeUser((user, done) => {
done(null, user._id);
});
// Tell passport how to deserialize the user
passport.deserializeUser((id, done) => {
db.User.find({
_id: id
}).then(res => {
const response = typeof res !== undefined && res.length != 0 ? JSON.parse(JSON.stringify(res[0])) : null;
done(null, response)
}).catch(error => done(error, false))
});
// Export passport for external usage
module.exports = passport;
./models/db.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const uuid = require('uuid/v4');
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/your_db_name', {
useNewUrlParser: true
});
// Define the models container
let models = {};
// Prepare your user schema
const userSchema = Schema({
username: {
type: String,
required: true
},
password: {
type: String,
required: true
}
});
// Assign the user schema
models.User = mongoose.model('User', userSchema);
// Export for external usage
module.exports = models;
/*
In that way you can wrap in "models" all schemas:
const newSchema = Schema({
name: String
});
models.Newschema = mongoose.model('Newschema', newSchema);
module.exports = models;
And use it externally like:
const db = require('./models/db');
db.User.find({}).then(docs => {}).catch(err => {});
db.Newschema.find({}).then(docs => {}).catch(err => {});
Etc....
*/
./models/config.js
class Config {
constructor() {
this.sessionSecretKey = "my-awesome-secretkey";
/* And other configurations */
}
}
module.exports = Config;
/*
Externally use like:
const Config = require('./models/config');
const config = new Config();
let sessionSecretKey = config.sessionSecretKey;
*/
Then you can use the req.isAuthenticated() after the login:
// POST the username and password to '/login' router
app.post('/login', (req, res, next) => {
passport.authenticate('local', (err, user, info) => {
if (info) {
return res.send(info.message)
}
if (err) {
return next(err);
}
if (!user) {
return res.sendStatus(404); // Is a shortcut
// OR -> res.status(404).end();
// OR -> res.status(404).send('Not found'); as you like
}
req.login(user, (err) => {
if (err) return next(err);
// Store the user object retrieved from MongoDB in `req.session`
req.session.user = user;
return res.sendStatus(200); // Is a shortcut
// OR -> res.status(200).end();
// OR -> res.status(200).send('OK'); as you like
})
})(req, res, next);
});
// The logout logic
app.get('/logout', verifySession, function (req, res) {
req.session.destroy(function (err) {
req.logout();
res.redirect('/');
});
});
// Verify the session to protect private routers
function verifySession(req, res, next) {
if (req.isAuthenticated()) {
next();
} else {
// Forbidden
res.redirect('/');
// OR -> res.sendStatus(403);
// OR -> res.status(403).end();
// OR -> res.status(403).send('Forbidden'); as you like
}
}
Of course you have to run npm install with all the dependencies required defined in package.json file or manually instal with npm i express-session#latest --s for all the dependencies required: npm i module-name#latest --s.
Don't forget the
const server = app.listen(config.port || 3000, () => {
console.log(`Server running on ${server.address().port} port.`);
});
At the end of server.js file. I hope that it will be useful for you.