I'm trying to use passport to login with google. So here's how I created my files.
Created Passport.js for passport configurations which looks like below,
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth2').Strategy;
const Config = require("../../configs/configs");
passport.serializeUser((user , done) => {
done(null , user);
})
passport.deserializeUser(function(user, done) {
done(null, user);
});
passport.use(new GoogleStrategy({
clientID:Config.clientId, // Your Credentials here.
clientSecret:Config.clientSecret, // Your Credentials here.
callbackURL:"http://localhost:5041/auth/callback",
passReqToCallback:true
},
function(request, accessToken, refreshToken, profile, done) {
console.log(profile);
return done(null, profile);
}
));
module.exports = passport;
check I'm exporting this passport instance in this file.
Now in controller I'm Importing the passport function for authenticate. Now the requirement is such, I need to redirect user to specific URL from backend and invoke the google login page.
SO my controller functions looks something like this.
to redirect:
async registrationWithGoogle() {
try {
return this.res.send(`<?xml version='1.0'?> <!DOCTYPE html><html><head><title>HTML Meta Tag</title><meta http-equiv='refresh' content='3; url = ${Config.beRedirectUrlPrefix}${Config.serverPort}${Config.beRedirectUrlSuffix}?mode=${this.req.query.target}'/></head><body><p>Redirecting to another URL</p></body></html>`);
} catch (error) {
console.log(error);
loggerError(
this.req.url,
this.req.method,
this.req.connection.remoteAddress,
this.req.body,
this.req.params,
0,
error
);
this.res.send({ status: 0, message: error });
}
}
in the same controller I'm creating a function against this /auth/redirect
route and to authenticate. the code looks something like this;
async validatePassportForGoogle() {
try {
const x = await passport.authenticate('google', { scope: [ 'email', 'profile' ] });
console.log("======2======>", x);
} catch (error) {
console.log(error)
}
}
and as an output of x I'm getting ======2======> [Function: authenticate]
as output, instead of profile details.
Can anyone ple correct me what I'm doing wrong.
Passport is middleware, so need to call on router level.