Open Mrcollinsiolf opened 5 days ago
To implement Google sign-in functionality on your website, we need to make changes to both the front end and the back end of the application. The front end will handle the Google sign-in button and the OAuth2.0 flow initiation, while the back end will handle the OAuth2.0 callback and user session management.
src/frontend/App.js
Create the App.js
file and render the LoginComponent
within the main application flow.
import React from 'react';
import LoginComponent from './components/LoginComponent';
function App() {
return (
<div className="App">
<LoginComponent />
</div>
);
}
export default App;
src/frontend/components/LoginComponent.js
Implement the Google sign-in button and handle the OAuth2.0 flow.
Install Required Packages:
npm install react-google-login
Create the LoginComponent.js
file:
import React from 'react';
import { GoogleLogin } from 'react-google-login';
const LoginComponent = () => {
const handleLoginSuccess = (response) => {
console.log('Login Success:', response.profileObj);
// Send the response token to your backend for further processing
fetch('/api/auth/google', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ token: response.tokenId })
});
};
const handleLoginFailure = (response) => {
console.log('Login Failed:', response);
};
return (
<div>
<h2>Login</h2>
<GoogleLogin
clientId="YOUR_GOOGLE_CLIENT_ID"
buttonText="Login with Google"
onSuccess={handleLoginSuccess}
onFailure={handleLoginFailure}
cookiePolicy={'single_host_origin'}
/>
</div>
);
};
export default LoginComponent;
src/backend/models/User.js
Update the user model to include fields for storing Google account information.
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
googleId: {
type: String,
required: true,
unique: true
},
email: {
type: String,
required: true,
unique: true
},
name: {
type: String,
required: true
},
}, {
timestamps: true
});
const User = mongoose.model('User', userSchema);
module.exports = User;
src/backend/routes/authRoutes.js
Implement the routes for initiating the Google OAuth2.0 flow and handling the callback.
Install Required Packages:
npm install express passport passport-google-oauth20 express-session
Create the authRoutes.js
file:
const express = require('express');
const passport = require('passport');
const router = express.Router();
router.use(passport.initialize());
router.use(passport.session());
router.get('/auth/google',
passport.authenticate('google', { scope: ['profile', 'email'] })
);
router.get('/auth/google/callback',
passport.authenticate('google', { failureRedirect: '/login' }),
(req, res) => {
res.redirect('/');
}
);
module.exports = router;
src/backend/config/passport.js
Set up Passport.js with the Google OAuth2.0 strategy.
Install Required Packages:
npm install passport passport-google-oauth20 dotenv
Create the passport.js
file:
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const User = require('../models/User');
require('dotenv').config();
passport.use(new GoogleStrategy({
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: process.env.GOOGLE_CALLBACK_URL
},
async (accessToken, refreshToken, profile, done) => {
try {
let user = await User.findOne({ googleId: profile.id });
if (!user) {
user = new User({
googleId: profile.id,
email: profile.emails[0].value,
name: profile.displayName
});
await user.save();
}
return done(null, user);
} catch (err) {
return done(err, null);
}
}
));
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser(async (id, done) => {
try {
const user = await User.findById(id);
done(null, user);
} catch (err) {
done(err, null);
}
});
module.exports = passport;
Environment Variables:
Ensure you have the necessary environment variables set up in your .env
file:
GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret
GOOGLE_CALLBACK_URL=http://localhost:5000/auth/google/callback
By following these steps, you will have implemented Google sign-in functionality on your website, covering both the front end and the back end.
Click here to create a Pull Request with the proposed solution
Files used for this task:
What - description of what you me to do Example: Hey @autopilot implement a Google sign-in on my website. Make changes to the front end and the back end of the application
Why - explain why this is important Example: I want to allow users to signup and login using their Google account