Passport JS auth middleware issue - javascript

I am implementing auth using passport js and database is mysql. My successRedirect route is '/main' and in the main route, I have added a middleware (isAuthenticated). But the issue is that, after entering valid credentials, I am not being redirected to '/main', instead, it just timeouts. I tried without adding middleware to '/main' route and it works fine.
var isAuthenticated = function(req, res, next) {
if (req.isAuthenticated()) {
return next;
}
res.redirect("/login")
}
// AUTH Implementation
app.use(session( {
secret: "asdnoifjasofijmaofmjkneknf",
resave: false,
saveUninitialized: false
}))
app.use(passport.initialize())
app.use(passport.session())
passport.use(new localStrategy(
function(username, password, done) {
connection.query("SELECT password FROM user" +
" WHERE email = ?", [username], function (err, results, fields) {
if (err) {
console.log(err);
}
else if (results.length === 0) {
done(null, false);
}
else {
console.log("Results");
console.log(results[0]);
hashedPassword = results[0].password;
bcrypt.compare(password, hashedPassword, function (err, response) {
if (response) {
console.log("True");
return done(null, true);
}
else {
console.log("False");
return done(null, false);
}
})
}
})
}
));
passport.serializeUser(function(ID, done) {
done(null, ID);
});
passport.deserializeUser(function(ID, done) {
connection.query("SELECT * FROM user WHERE userID = ?", [ID], function (err, results, fields) {
if (err) throw err;
else if (results.length === 0) done(null, false);
else {
done(null, results[0]);
}
})
done(null, ID);
});
app.post("/login", passport.authenticate('local', {
successRedirect: "/main",
failureRedirect: "/login"
}))
app.get("/main", isAuthenticated, function(req, res) {
res.send("In the main page");
})
app.post("/login", passport.authenticate('local', {
successRedirect: "/main",
failureRedirect: "/login"
}))
Help me out.

You need execute next function instead of return it.
var isAuthenticated = function(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
res.redirect("/login")
}

Related

Why isAuthenticated return false in passport.js local strategy after successful login the user

I have the following code to authenticate through the passport-local strategy:
routes.post("/login", passport.authenticate("local"), (req, res) => {
res.json(req.user);
});
function ensureAuth(req, res, next) {
console.log(req.isAuthenticated());
if (req.isAuthenticated()) {
next();
} else {
req.flash("info", "You must be logged in to see this page");
res.redirect("/login");
}
}
routes.get("/edit", ensureAuth, (req, res) => {
res.sendStatus(200);
});
routes.post("/edit", ensureAuth, (req, res, next) => {
req.user.username = req.body.username;
req.user.bio = req.body.bio;
req.user.email = req.body.email;
req.user.save((err) => {
if (err) {
return next(err);
} else {
res.send({
success: "true",
info: "Profile updated",
});
}
});
});
I can't figure out why this is happening? Why won't it authenticate?
I can't see your passport local configuration and I send a sample for local Authentication by passport local I hope help you :)
login route:
router.post('/login', loginController.process);
controller loginController.process :
async process(req, res, next) {
try {
passport.authenticate('local.login', async (err, user) => {
// User not Exist
if (!user) return this.back(req, res);
req.logIn(user, (err) => {
if (req.body.remember) {
user.setRememberToken(res);
}
return res.redirect('/');
});
})(req, res, next);
} catch (e) {
next(e);
}
}
}
passport configuration :
passport.use('local.login', new localStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true,
}, async (req, email: string, password: string, done) => {
// Select User Where email
const user = await userService.findOne({email});
// Check user Exist or Incorrect Password
if (!user || !user.comparePassword(password)) return done(req.flash('global_error', req.__('typeScript.app.passport.passport-local.wrong')), null);
done(null, user);
}));

Nodejs Passport Failure message not working

I have Passport Local working on my app.
Success brings authenticates and failure does not.
However im trying to make it fail better through fail messages and escaping the action.
Tried following the passport documentation.
The error messages are not appearing for some reason, would appreciate some assistance!
here is the local startegy
// Configure the local strategy for use by Passport.
passport.use(new Strategy(
function(username, password, cb) {
db.users.findByUsername(username, function(err, user) {
if (err) { return cb(err); }
if (!user) { return cb(null, false,req.flash('message','Invalid username or password')); }
if (user.password != password) { return cb(null, false,req.flash('message','Invalid username or password')); }
return cb(null, user);
});
}));
The authentication
//Home
app.post('/home.ejs',
passport.authenticate('local'),
function(req, res) {
res.redirect('/');
});
I also have another attempt at authentication if this is more accurate but also had no luck
//Home
app.post('/home.ejs', function( req, res, next) { passport.authenticate('local', function(err, user, info) {
if (err) { return next(err); req.flash('message','Invalid username or password') }
if (!user) { return res.redirect('/'); failureFlash: 'Invalid username or password' }
req.logIn(user, function(err) {
if (err) { return next(err); }
return res.redirect('/');
});
})(req, res, next);
});*/
It should be
passport.use(new LocalStrategy ...
instead of your
passport.use(new Strategy(.....

Unknown authentication strategy "github"

Online authentication of GitHub is not working. I've registered the new app in GitHub and still the application won't redirect to OAuth.
The following code I've written and getting Error:Unknown authentication strategy "github"
const passport = require('passport');
const bcrypt = require('bcrypt');
module.exports = function (app, db) {
app.route('/')
.get((req, res) => {
res.render(process.cwd()+'/views/pug/index', {title: 'Hello', message: 'Please login',showLogin: true, showRegistration: true});
});
app.route('/login')
.post(passport.authenticate('local',{ failureRedirect: '/' }),(req,res)=>{
res.redirect('/profile');
});
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
res.redirect('/');
}
app.route('/profile')
.get(ensureAuthenticated, (req,res) => {
res.render(process.cwd() + '/views/pug/profile',{username:req.user.username});
});
app.route('/logout')
.get((req, res) => {
req.logout();
res.redirect('/');
});
app.route('/register')
.post((req, res, next) => {
var hash = bcrypt.hashSync(req.body.password, 12);
db.collection('users').findOne({ username: req.body.username }, function (err, user) {
if(err) {
next(err);
} else if (user) {
res.redirect('/');
} else {
db.collection('users').insertOne(
{username: req.body.username,
password: hash},
(err, doc) => {
if(err) {
res.redirect('/');
} else {
next(null, user);
}
}
)
}
})},
passport.authenticate('local', { failureRedirect: '/' }),
(req, res, next) => {
res.redirect('/profile');
}
);
/*GitHub OAuth*/
app.route('/auth/github')
.get(passport.authenticate('github'));
app.route('/auth/github/callback')
.get(passport.authenticate('github', { failureRedirect: '/' }), (req,res) => {
res.redirect('/profile');
});
/*End of GitHub OAuth*/
app.use((req, res, next) => {
res.status(404)
.type('text')
.send('Not Found');
});
}
It seems I have missing something or anything else for OAuth. The strategy wasn't defined in my side I just accessing default strategy for GitHub.
You have to configure passport github strategy in your script. https://github.com/jaredhanson/passport-github
var GitHubStrategy = require('passport-github').Strategy;
passport.use(new GitHubStrategy({
clientID: GITHUB_CLIENT_ID,
clientSecret: GITHUB_CLIENT_SECRET,
callbackURL: "http://127.0.0.1:3000/auth/github/callback"
},
function(accessToken, refreshToken, profile, cb) {
User.findOrCreate({ githubId: profile.id }, function (err, user) {
return cb(err, user);
});
}
));

Persistent Login with Passport.js no longer working. isAuthenticated returns false

I had this code working at some point and must have lost it in a careless save at some point. I am trying to achieve persistent login with passport but it does not seem to be doing that as I am getting false on the isAuthentiacted middleware.
Here is my primary server.js setup, as you can see the order is good. But I am not sure about the cookie settings as I'm new to this whole thing.
app.use(cookieParser('S3CRE7'));
app.use(bodyParser.json());
app.use(session({ key: 'express.sid', resave: false, saveUninitialized: false, maxAge: 3000}));
app.use(passport.initialize());
app.use(passport.session());
app.use('/users/', usersRouter);
app.use('/transcriptions', transRouter);
app.use(express.static('public'));
const basicStrategy = new BasicStrategy(function(username, password, callback) {
let user;
User
.findOne({username: username})
.exec()
.then(_user => {
user = _user;
if (!user) {
return callback(null, false, {message: 'Incorrect username'});
}
return user.validatePassword(password);
})
.then(isValid => {
if (!isValid) {
return callback(null, false, {message: 'Incorrect password'});
}
else {
return callback(null, user)
}
});
});
passport.use(basicStrategy);
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
Here is my initial Log In endpoint with custom callback function, which logs in just fine, as well as stores a cookie on the client side
router.post('/login', function(req, res, next) {
passport.authenticate('basic', function (err, account) {
req.logIn(account, function() {
res.status(err ? 500 : 200).send(err ? err : account);
});
})(req, res, next)
});
isAuthenticated function:
const isAuthenticated = function (req, res, next) {
if (req.isAuthenticated())
return next();
console.log('not authenticated');
}
First lines of where the authentication fails:
router.get('/', isAuthenticated,
(req, res) => {
console.log(req);
});

node.js passport local strategy problems

I am new to node.js in general and passport in particular.
I have exposed a passport configuration in a file by itself like the following:
var LocalStrategy = require('passport-local').Strategy;
var User = require('../models/User');
var messages = {
100: 'Username and/or password are not correct.',
101: 'User already exists.'
};
module.exports = function (passport) {
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('local-login', new LocalStrategy(function (username, password, done) {
User.findOne({ username: username }, function (err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false, req.flash('loginMessage', messages['100']));
}
user.comparePassword(password, function (err, isMatch) {
if (err) {
return done(err);
}
if (isMatch) {
return done(null, user);
} else {
return done(null, false, req.flash('loginMessage', messages['100']));
}
});
});
}));}
in my node routes, i am doing the following to handle the login scenario:
app.post('/login',function(req, res, next){
console.log('loggin in ')
passport.authenticate('local-login', function(err, user, info){
console.log('allo');
console.log(err);
console.log(user);
console.log(info)
});
});
however I am not getting a response; can you please clarify what I am doing wrong.
You need to return the object returned by passport.authenticate
app.post('/login',function(req, res, next){
console.log('loggin in ')
/**/return passport.authenticate('local-login', function(err, user, info){
console.log('allo');
console.log(err);
console.log(user);
console.log(info)
})(req, res, next);
});

Categories

Resources