Google Authentication using passport-google not working - passport.js

Here's the code i typed.
var passport = require("passport");
var GoogleStrategy = require("passport-google-oauth").OAuth2Strategy;
// Use the GoogleStrategy within Passport.
// Strategies in Passport require a `verify` function, which accept
// credentials (in this case, an accessToken, refreshToken, and Google
// profile), and invoke a callback with a user object.
passport.use(
new GoogleStrategy(
{
clientID: '28013134812-qc5lbogacg4cf42etiruqveskh8vaqgh.apps.googleusercontent.com',
clientSecret: 'secret! i can't type secret here',
callbackURL: "www.example.com.com/auth/google/callback",
},
function (accessToken, refreshToken, profile, done) {
User.findOrCreate({ googleId: profile.id }, function (err, user) {
return done(err, user);
});
}
)
);
// GET /auth/google
// Use passport.authenticate() as route middleware to authenticate the
// request. The first step in Google authentication will involve
// redirecting the user to google.com. After authorization, Google
// will redirect the user back to this application at /auth/google/callback
app.get(
"/auth/google",
passport.authenticate("google", {
scope: ["https://www.googleapis.com/auth/plus.login"],
})
);
// GET /auth/google/callback
// Use passport.authenticate() as route middleware to authenticate the
// request. If authentication fails, the user will be redirected back to the
// login page. Otherwise, the primary route function function will be called,
// which, in this example, will redirect the user to the home page.
app.get(
"/auth/google/callback",
passport.authenticate("google", { failureRedirect: "/login" },
function (req, res) {
res.redirect("/");
})
);
ReferenceError: User is not defined
at Strategy._verify (C:\Users\hp\short.nner\server.js:64:7)
at C:\Users\hp\short.nner\node_modules\passport-oauth2\lib\strategy.js:202:24
at C:\Users\hp\short.nner\node_modules\passport-google-oauth20\lib\strategy.js:122:5
at passBackControl (C:\Users\hp\short.nner\node_modules\oauth\lib\oauth2.js:134:9)
at IncomingMessage. (C:\Users\hp\short.nner\node_modules\oauth\lib\oauth2.js:157:7)
at IncomingMessage.emit (node:events:341:22)
at endReadableNT (node:internal/streams/readable:1294:12)
at processTicksAndRejections (node:internal/process/task_queues:80:21)
I copied the above code from passport docs. Does anyone know why I am getting this error?
What actually is User here?
i think something's wrong with this code
function (accessToken, refreshToken, profile, done) {
User.findOrCreate({ googleId: profile.id }, function (err, user) {
return done(err, user);
});
}

Just put correct callback URL here callbackURL: "http://localhost:3000.com/auth/google/callback", and define User. That's it

Related

How would I redirect after authenticating a user using passportjs?

I looked in several posts, but I cannot find something that meets my situation.
To login (or signup) with google, you have to go to mydomain.com/login/google
You then, well, login with google, and then the callback is handled on mydomain.com/auth/google
Here is the code responsible for this.
app.get('/login/google', passport.authenticate('google'));
app.get('/auth/google',
passport.authenticate('google', { failureRedirect: '/login', failureMessage: false, session: false, failureFlash: true }),
function(req, res) {
res.redirect('/');
});
Here is where I store the users:
passport.use(new GoogleStrategy({
clientID: no,
clientSecret: definitely not,
callbackURL: 'https://no cuz privacy/auth/google'
},
async function(issuer, profile, cb) {
var user = await User.find({ google: true, googleid: profile.id })
if (!user[0]) {
// The Google account has not logged in to this app before. Create a
// new user record and link it to the Google account.
const newUser = await new User({ username: generateUsername(), google: true, googleid: profile.id, googleProfile: profile })
await newUser.save()
return cb(null, newUser);
} else {
// The Google account has previously logged in to the app. Get the
// user record linked to the Google account and log the user in.
console.log('exists')
return cb(null, newUser);
}
}
));
I think you have to do something with the callback function (cb()) to somehow go to app.get('/auth/google') for the redirect, but, all it does is print either exists or new in the console, spinning forever on the client side. Not sure how to redirect after the code determines either account exists or new account.
Edit: I just want to point out that the cb() function could also be done() too. For example:
function(accessToken, refreshToken, profile, done){
console.log("strategy");
console.log(profile);
console.log(accessToken);
console.log(refreshToken);
done(null, profile);
}
^^ Not my code --> PassportJS in Nodejs never call the callback function ^^

How to Get user Email Address using OAuth in Node js

I am writing a code to add functionality of logging in with Google. I have written code but when a user log in with google, it only gives me id, name, fullname etc. It does not provide with user email address. Can any one help me to solve this? Following is my code
passport.use(new GoogleStrategy({
clientID: CLIENT_ID,
clientSecret: CLIENT_SECRET,
callbackURL: "http://localhost:8000/auth/google/notepad"
},
function(accessToken, refreshToken, profile, cb) {
console.log(profile);
User.findOrCreate({ googleId: profile.id }, function (err, user) {
return cb(err, user);
});
}
));
router.get('/auth/google', passport.authenticate('google',{scope: ['profile']}));
router.get('/auth/google/notepad',
passport.authenticate('google', { failureRedirect: '/' }),
async function(req, res) {
const token = await req.user.generateAuthToken();
res.cookie('authToken', token);
res.redirect('/')
});
You are missing the email scope. It’s a separate scope to their profile.
See the docs too if you want to know more: https://developers.google.com/identity/protocols/oauth2/openid-connect#scope-param

Send user details to controller in passport authenticate using google-oauth2

I have created a google user session using passport oauth, using the following routes:
nodeApp.get('/api/google', googlepassport.authenticate('google', { session: true,scope: ['profile', 'email'] })
nodeApp.get('/auth/google/callback',
googlepassport.authenticate('google',
{ // successRedirect: '/',
// failureRedirect: '/login-error',
}))
At the backend in passport.serializeuser, I am able to retrieve details however I want to send these details to client controller.
I tried using Http.get, but that doesn't work for google oauth as I get cross domain error. I am new to nodejs, so kindly suggest best possible way to do send user details to client controller.
google strategy
googlepassport.use(new GoogleStrategy({
clientID: "add",
clientSecret: "",
callbackURL: "---",
// passReqToCallback: true
},
function(req, token, refreshToken, profile, done) {
// make the code asynchronous
// console.log("test google");
// User.findOne won't fire until we have all our data back from Google
process.nextTick(function() {
console.log("test google");
//console.log(profile);
var userMap = {};
userMap['mail'] = profile.emails[0].value;
userMap['name'] = profile.displayName;
// console.log(JSON.stringify(userMap));
// req.user = req.session.googlepassport.user;
//console.log(req.session);
//req.session.user = req.session.googlepassport.user;
return done(null, userMap);
})
// done(null,null);
}));
googlepassport.serializeUser(function(user, done) {
console.log('Serializing');
console.log(user);
done(null, user);
});
googlepassport.deserializeUser(function(userMap, done) {
done(null, userMap);
});
I want to send userMap to the client, Here the route is made through href, to avoid cross-domain error, that I get if I use it on button click .

LinkedIN OAuth log in trouble Nodejs

I am using LinkedIn OAuth and passport for my sign in. For whatever reason the first time I try to log in, it routes to homepage without logging in. The second time however, it logs in properly. What might be causing this problem? LinkedIn or passport?
This is the get path :
router.get('/auth/linkedin/callback', passport.authenticate('linkedin', {failureRedirect: '/', failureFlash:true}),
function (req, res, next) {
User.findOne({_id: req.user._id}, function (err, user) {
if (err) {
return next(err);
res.redirect("/")
}
user.last_login = moment();
user.save()
return res.redirect('/profile/' + user.username);
});
});
And then the passport linkedIn :
passport.use(new LinkedInStrategy({
clientID: config.linkedin.consumerKey,
clientSecret: config.linkedin.consumerSecret,
callbackURL: config.linkedin.callbackURL,
state: true,
scope: ['r_basicprofile', 'r_emailaddress']}, function (token, refreshToken, profile, done) {
...

Why am I getting a TokenError when authenticating with OAuth2Strategy for Passport/Node Express

I'm trying to use the OAuth2Strategy for Passport JS in conjunction with Express (4).
After I'm redirected to to login, it successfully navigates me back to my callback url, at which point I get the following error:
TokenError: Invalid client or client credentials
at OAuth2Strategy.parseErrorResponse (/www/az-avatarz-server/node_modules/passport-oauth/node_modules/passport-oauth2/lib/strategy.js:298:12)
at OAuth2Strategy._createOAuthError (/www/az-avatarz-server/node_modules/passport-oauth/node_modules/passport-oauth2/lib/strategy.js:345:16)
at /www/az-avatarz-server/node_modules/passport-oauth/node_modules/passport-oauth2/lib/strategy.js:171:43
at /www/az-avatarz-server/node_modules/passport-oauth/node_modules/passport-oauth2/node_modules/oauth/lib/oauth2.js:177:18 at passBackControl (/www/az-avatarz-server/node_modules/passport-oauth/node_modules/passport-oauth2/node_modules/oauth/lib/oauth2.js:124:9)
at IncomingMessage.<anonymous> (/www/az-avatarz-server/node_modules/passport-oauth/node_modules/passport-oauth2/node_modules/oauth/lib/oauth2.js:143:7)
at IncomingMessage.EventEmitter.emit (events.js:117:20)
at _stream_readable.js:919:16
at process._tickDomainCallback (node.js:463:13)
My passport configuration is as follows:
passport.use("avatarz", new OAuth2Strategy({
authorizationURL: authorizationURL,
tokenURL: tokenURL,
clientID: clientID,
clientSecret: clientSecret,
callbackURL: callbackURL
},
function (accessToken, refreshToken, profile, done) {
User.find({
prid: profile.prid
}, function (error, user) {
if (error) {
return done(error);
}
if (user) {
return done(null, user);
}
else {
done(error);
}
});
}
));
And my routes are as follows:
app.get('/authentication/provider', passport.authenticate("avatarz"));
app.get('/', passport.authenticate("avatarz", { failureRedirect: '/authentication/provider' }),
function (req, res) {
res.sendfile("./public/index.html");
});
Any help/advice would be greatly appreciated!
Ensure that you have activated the Google+ API at: https://console.developers.google.com

Resources