Passing state value to passport.authenticate function for GoogleOAuthStrategy - javascript

I need to get referralCode which is present as a param on the request URL. I am getting a forbidden error with status code 402 with the following code. On passing this referralcode in passport.authenticate as a state variable the code isn't working. It works fine without referralcode.
passport.use(
new GoogleStrategy(
{
clientID: secrets.GOOGLE_CLIENT_ID,
clientSecret: secrets.GOOGLE_SECRET_KEY,
callbackURL: `${config.api_host}/v1/user/login/google/callback`,
passReqToCallback: true,
scope: ['email', 'profile'],
state: true
},
async (req, accessToken, refreshToken, profile, cb) => {
cb(null, profile);
}
)
);
passport.serializeUser((user, done) => {
done(null, user);
});
passport.deserializeUser((id, done) => {
done(null, id);
});
router.get(
"/login/google/:referralcode",
function (req, res, next) {
passport.authenticate("google", {
scope: ["email", "profile"],
state: req.params.referralcode,
})(req, res, next)
},
);
router.get(
"/login/google/callback",
passport.authenticate("google", {
passReqToCallback: true,
failureRedirect: failureRedirectRoute,
}), // If I comment above two lines, it works fine.
async (req, res, next) => {
try {
const result = await googleSignInAuthCallback(req, res, next);
// console.log("req", req);
return res.status(200).json(result);
} catch (err) {
console.log(err, "ERR");
}
}
);

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);
}));

Passport openid-connect strategy not authenticating when I redirect from a page to Login Routes

Now These routes below function properly when I hit them directly but when I am redirecting a user them from a page to these routes the authentication is never successful instead I am redirected back to the route '/auth/openidconnect/undefined'.
Moreover Something that I found really weird was that after trying at least 2 more times (redirecting the user to the auth route from the above mentioned page) I get successfully authenticated.
router.get('/auth/openidconnect',oidcSettings, oidcProviderReq);
router.get('/auth/openidconnect/callback',oidcSettings, oidcCallback);
let oidcSettings = function (req, res, next) {
//provider contains all the required data
var OidcStrategy = require('passport-openidconnect').Strategy;
passport.use('oidc', new OidcStrategy({
issuer: provider.settings.issuer,
authorizationURL: provider.settings.authorizationURL,
tokenURL: provider.settings.tokenURL,
userInfoURL: provider.settings.userInfoURL,
clientID: provider.settings.ClientID,
clientSecret: provider.settings.clientSecret,
callbackURL: provider.settings.callbackURL,
scope: 'openid profile'
}, (issuer, sub, profile, accessToken, refreshToken, done) => {
if (!(profile && profile._json && profile._json.email)) {
return done(null, false);
}
req.params.provider =profile.id
oidcLogin(req, profile, 'oidc_user', done); //basically either logs into the application or creates a new user
}));
next();
}
let oidcProviderReq = function(req, res, next){
passport.authenticate('oidc', {scope: 'openid profile'})(req, res, next);
}
let oidcCallback = function(req, res, next){
passport.authenticate('oidc', function (err, user, info) {
if(err) throw err;
console.log(user)
})(req, res, next);
}
```

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);
});
}
));

Passport JS auth middleware issue

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")
}

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);
});

Categories

Resources