Open AMEERAZAM08 opened 1 month 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. This involves creating a user model to store Google-specific information, setting up Google OAuth 2.0 authentication using Passport.js, and integrating the Google sign-in button in the front end.
We need to create a user model to store Google-specific information such as Google ID, email, name, and tokens.
File: server/models/User.js
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
},
token: {
type: String,
required: true
},
refreshToken: {
type: String
},
createdAt: {
type: Date,
default: Date.now
}
});
const User = mongoose.model('User', UserSchema);
module.exports = User;
Set up Passport.js to handle Google OAuth 2.0 authentication.
File: server/config/passport.js
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const User = require('../models/User');
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,
token: accessToken,
refreshToken: refreshToken
});
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;
Create routes to handle the OAuth 2.0 callback from Google and manage user sessions.
File: server/routes/auth.js
const express = require('express');
const passport = require('passport');
const router = express.Router();
router.get('/google', passport.authenticate('google', { scope: ['profile', 'email'] }));
router.get('/google/callback',
passport.authenticate('google', { failureRedirect: '/' }),
(req, res) => {
res.redirect('/');
}
);
router.get('/logout', (req, res) => {
req.logout((err) => {
if (err) { return next(err); }
res.redirect('/');
});
});
module.exports = router;
Ensure that the server is set up to use Passport and the authentication routes.
File: server/index.js
const express = require('express');
const passport = require('./config/passport');
const session = require('express-session');
const authRoutes = require('./routes/auth');
const app = express();
app.use(session({ secret: 'your_secret_key', resave: false, saveUninitialized: true }));
app.use(passport.initialize());
app.use(passport.session());
app.use('/auth', authRoutes);
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Create a React component that renders a Google sign-in button and handles the sign-in process using Google's OAuth 2.0 API.
File: src/components/GoogleSignInButton.js
import React from 'react';
import { GoogleLogin } from 'react-google-login';
import axios from 'axios';
const GoogleSignInButton = () => {
const handleSuccess = async (response) => {
const { tokenId } = response;
try {
const res = await axios.post('/api/auth/google', { tokenId });
console.log('User authenticated successfully:', res.data);
} catch (error) {
console.error('Error authenticating user:', error);
}
};
const handleFailure = (error) => {
console.error('Google Sign-In failed:', error);
};
return (
<GoogleLogin
clientId={process.env.REACT_APP_GOOGLE_CLIENT_ID}
buttonText="Sign in with Google"
onSuccess={handleSuccess}
onFailure={handleFailure}
cookiePolicy={'single_host_origin'}
/>
);
};
export default GoogleSignInButton;
Import and include the GoogleSignInButton
component in the main application layout.
File: src/App.js
import React from 'react';
import GoogleSignInButton from './components/GoogleSignInButton';
function App() {
return (
<div className="App">
<header className="App-header">
<h1>Welcome to My App</h1>
<GoogleSignInButton />
</header>
</div>
);
}
export default App;
Add your Google Client ID to your environment variables.
File: .env
REACT_APP_GOOGLE_CLIENT_ID=your-google-client-id
By following these steps, you will have implemented Google sign-in functionality on your website, allowing users to sign up and log in using their Google accounts.
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