passport.js
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var user = require('../modal/admin');
exports.passport = (passport) => {
passport.use(new LocalStrategy({
usernameField: 'username',
passwordField: 'password'
},
(username, password, done, req) => {
console.log(req)
user.findOne(({ username: username }), async (err, user) => {
if (err) { return done(err); }
if (!user) { return done(null, false); }
const cpassword = await bcrypt.compare(password, user.password);
if (!cpassword) { return done(null, false); }
const token = jwt.sign(
{
id:user.id,
username:user.username
},
"shubham"
);
adminRecords = {
token:token
}
req.data = adminRecords ====>>>> Error here
console.log(adminRecords)
return done(null, user, adminRecords);
});
}
))
};
passport.serializeUser(function (user, done) {
done(null, user)
})
passport.deserializeUser(function (id, done) {
user.find(id, function (err, user) {
done(err, user)
});
});
route.js
router.post('/login', passport.authenticate('local'));
It's giving error req.data is not defined. I am using passport local strategy and want to return jwt token in req.data. It is not taking req parameter correctly.
Callback function have only 3 params
passport.use(new LocalStrategy({
usernameField: 'username',
passwordField: 'password'
},
(username, password, done, req) => { // callback function have only 3 params
// Additional codes
Solution try to use middleware when you authenticate
app.use(request, response, next) => { passport.authenticate('local', (err, token, info) => {
if (token) {
request.login(token, () => { // Do your logic });
} else { }
})(request, response, next); });
Related
I'm using Passport js local strategy but I can't redirect from my admin page. it always fails even if the login and password are correct, below is the auth.js and login.js code
login.js
router.get('/', (req, res, next) =>{
if (req.query.fail){
res.render('admin/login', {layout: 'admin.hbs', message: "Usuario e/ou Senha invalidos"});
}else{
res.render('admin/login', {layout: 'admin.hbs', message: null});
}
})
router.post('/',
passport.authenticate('local', { failureRedirect: '/login?fail=true' }),
function(req, res) {
res.redirect('/admin');
});
auth.js
const users = [{
_id: 123,
username: "adm",
password: hashedPassword
}];
console.log(users);
module.exports = function(passport){
function findUser(username){
return users.find(item => item.username === username);
}
function findUserById(id){
return users.find(item => item._id === id);
}
passport.serializeUser((user, done) => {
done(null, user._id);
});
passport.deserializeUser((id, done) => {
try {
const user = findUserById(id);
done(null, user);
} catch (err) {
console.log(err);
return done(err, null)
}
});
passport.use(new localStrategy({
usernameField: 'username',
passwordField: 'password',
},
(username, password, done) => {
try{
const user = findUser(username).then(user);
if(!user) return done(null, false);
const isValid = bcrypt.compare(password, user.password);
if(!isValid) return done(null, false);
return done(null, user);
}
catch(err){
console.log(err);
return done(err, false)
}}));
}
I don't know why it's not working, I wanted help getting into the admin page
I have configured passportJS with node express app but when I make login/register request then in that case req.user is undefined any idea what is wrong am I missing something in configuring passport js? I have used express-session and mongoDB store for storing sessions
passport-config.js:
const passport = require("passport");
const LocalStrategy = require("passport-local").Strategy;
const User = require("./Models/userSchema");
passport.use(
new LocalStrategy(
{
usernameField: "email",
passwordField: "password",
},
async (email, password, done) => {
try {
const user = await User.findOne({ email });
// Username/email does NOT exist
console.log("user in config", user);
if (!user) {
return done(null, false, {
message: "Username/email not registered",
});
}
// Email exist and now we need to verify the password
const isMatch = await user.isValidPassword(password);
return isMatch
? done(null, user)
: done(null, false, { message: "Incorrect password bro" });
} catch (error) {
done(error);
}
}
)
);
passport.serializeUser(function (user, done) {
done(null, user.id);
});
passport.deserializeUser(async function (id, done) {
const user = await User.findById(id);
done(null, user);
});
server.js file: https://pastebin.com/NfpvXSFf (see line 39)
I would try:
async (req, res) => {
{email, password, done} = req.body;
(you need a body-parser for that)
I'm havig trouble understanding how to access the properties of a global variable that is set in the middleware of my application
// app.js
app.use(function (req, res, next) {
res.locals.user = req.user || null;
next();
});
I would have thought I could access the req.user.username in my template (using handlebars), but for some reason it is forcing me to iterate over this object.
A consle.log(req.user) shows:
_id: 5f01f9a861f5b33b42a9e,
username: 'onetap',
email: 'test#gmail.com',
password: '$2b$10$VLBS8ZwPKiaXasdfsiiwfg.wyJ1J5CwTKLjS5zXwAsvukHpNmk0HG2',
createdAt: 2020-07-05T16:02:48.081Z,
__v: 0
}
And in my template I have to use an each loop and can't access the properties directly. the req.user is not an array either.
{{user.username}}//undefined
{{#each user}}
{{username}} //onetap
{{/each}}
passport.js file
const LocalStrategy = require("passport-local").Strategy;
const bcrypt = require("bcrypt");
const mongoose = require("mongoose");
// Load User Model
const User = require("../models/User");
module.exports = function (passport) {
passport.use(
new LocalStrategy({ username: "username" }, (username, password, done) => {
// Match User
User.findOne({
username: username,
}).then((user) => {
if (!user) {
return done(null, false, { message: "Invalid Username" });
}
console.log("Checking password");
// 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);
});
});
};
I was able to fix this by chaning deserialize to:
passport.deserializeUser(function (id, done) {
User.findById(id)
.lean()
.exec(function (err, user) {
done(err, user);
});
});
passport.js
module.exports = (passport) => {
passport.use(new LocalStrategy({
usernameField: 'username',
passwordField: 'password'
},
(username, password, done) => {
user.findOne(({ username: username }), async (err, user) => {
if (err) { return done(err); }
if (!user) { return done(null, false); }
const cpassword = await bcrypt.compare(password, user.password);
if (!cpassword) { return done(null, false); }
console.log(user._id)
const token = jwt.sign(
{
id: user._id,
username: user.username
},
"shubham"
);
adminRecords = {
token: token
}
return done(null, user, adminRecords);
});
}
));
passport.use(new JwtStrategy({
jwtFromRequest: ExtractJWT.fromAuthHeaderAsBearerToken(),
secretOrKey : 'key'
}, function(jwt_payload, done) {
console.log('1')
user.findOne({id: jwt_payload.sub}, function(err, user) {
if (err) {
return done(err, false);
}
if (user) {
return done(null, user);
} else {
return done(null, false);
// or you could create a new account
}
});
}));
};
passport.serializeUser(function (user, done) {
done(null, user)
})
passport.deserializeUser(function (id, done) {
user.find(id, function (err, user) {
done(err, user)
});
});
route.js
router.post('/profile', passport.authenticate('jwt', { session: false }),
function(req, res) {
console.log('1')
res.send(req.user.profile);
}
);
I am trying passport-jwt strategy and it returns unauthorized with status code 401 whereas token is generating. I am using token x-acccess-token=jwtToken but it returns unauthorized.
What can I try to debug this?
try to set in the header
Authorization: Bearer TOKEN
you should have space between token and bearer
replace the jwtFromRequest: as below and try out
jwtFromRequest:ExtractJwt.fromAuthHeaderWithScheme('JWT');
I am using passport with local strategy .but I want to send message and status when credential is not match or (user is not exit is DB)
here is code
router.js
const passport = require('passport');
const passportConfig = require('../passport')
const passportSignIn = passport.authenticate('local', { session: false });
router.route('/login',)
.post(passportSignIn,controller.login)
on controller file
login: async (req, res, next) => {
console.log(req.body);
res.json({status:200})
}
passport.js
passport.use(new LocalStrategy({
usernameField: 'email'
}, async (email, password, done) => {
const user = await db.User.findOne({where: {email: email}});
if (!user) {
return done(null, false,{message:"No user exit"});
}
const isMatch = await bcrypt.compare(password, user.dataValues.password);
console.log(isMatch, 'isMatch');
if (!isMatch) {
return done(null, false);
}
// Otherwise, return the user
done(null, user);
}))
Client code
when user click on login button it goes to /login path first it goes to passportSignIn function or below function.
`new LocalStrategy({
usernameField: 'email'
}, async (email, password, done) => {`
now if user not found I want to send this message on the client as the response ("No user exit")
return done(null, false,{message:"No user exit"});
You have to update your login controller, like so:
login: (req, res, next) => {
console.log(req.body);
passport.authenticate('yourStrategy', function(err, user, info) {
if (err) {
return res.status(500).json("Internal Server Error");
}
if (!user) {
// This 'info' variable below would be - { message: "No user exit" }
// as you passed in the done() callback as the third param
return res.status(404).json(info.message);
}
}
}