Thursday 25 June 2020

Redirecting on clicking Login with Google button using Passport-Google oAuth2 and Express, React

Right now, I want that:Whne user clicks on Login with Google button, gets redirected to the oAuth consent screen.In the consent screen, when the user chooses the account, it gets redirected to the route /auth/google/redirect(is this the correct route?) which logs in the user. So, then I want to set a cookie which I'm doing in app.js. This shows that the user is logged in.Now, how do I make a request from the NavBar component in my react frontend? For now, I have a button. I want to know the process that happens when I click the button; which backend route should I call?I'm having real trouble. Please suggest me some resources or help me understand it. Thanks.routes/auth.js```js const express = require("express") const passport = require("passport") const auth = require("./controllers/auth") const router = express.Router()// auth with google router.get("/google", passport.authenticate("google", { scope: ["profile"] }))// callback route for google to redirect to router.get("/google/redirect", passport.authenticate("google"), (req, res) => { // what to do here????? })module.exports = router ```config/passport.js```js const passport = require("passport") const GoogleStrategy = require("passport-google-oauth20").Strategy const User = require("../models/User")passport.serializeUser((user, done) => { done(null, user.id) })passport.deserializeUser((id, done) => { User.findById(id).then((user) => { done(null, user) }) })passport.use( new GoogleStrategy( { clientID: process.env.clientID, clientSecret: process.env.clientSecret, callbackURL: "/auth/google/redirect", }, (accessToken, refreshToken, profile, done) => { // check if the user exists User.findOne({ googleID: profile.id }).then((currentUser) => { if (!currentUser) { // if the user doesn't exist; create a new user new User({ username: profile.displayName, googleID: profile.id, }) .save() .then((newUser) => { console.log(`New user created- ${newUser}`) done(null, newUser) }) } if (currentUser) { console.log(`The current user is- ${currentUser}`) done(null, currentUser) } }) } ) ) ```NavBar.js```jsimport React from "react"const NavBar = () => { return ( // is this the correct URL??? //how to handle onClick here ) }export default NavBar ```app.js```js app.use(cookieSession({ maxAge: 24 * 60 * 60 * 1000, keys: [process.env.cookieKey] }))// intialize passport app.use(passport.initialize) app.use(passport.session) ```

Submitted June 25, 2020 at 03:34PM by Snoo10987

No comments:

Post a Comment