Open ovo63 opened 3 weeks ago
To implement Google sign-in on your website, we need to make changes to both the front end and the back end of the application. The back end will handle the OAuth2.0 flow and user authentication, while the front end will provide the user interface for signing in with Google.
We need to update the user model to include fields for storing Google account information, such as Google ID and access tokens.
File: src/backend/models/User.js
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
googleId: {
type: String,
required: true,
unique: true
},
accessToken: {
type: String,
required: true
},
refreshToken: {
type: String,
required: true
},
name: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
createdAt: {
type: Date,
default: Date.now
}
});
const User = mongoose.model('User', userSchema);
module.exports = User;
Set up Passport.js to use the Google OAuth2.0 strategy for authentication.
File: src/backend/config/passport.js
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 = await User.create({
googleId: profile.id,
accessToken,
refreshToken,
name: profile.displayName,
email: profile.emails[0].value
});
}
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 Google OAuth2.0 callbacks and exchange authorization codes for access tokens.
File: src/backend/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: '/login' }),
(req, res) => {
res.redirect('/');
}
);
module.exports = router;
Ensure that the authentication routes and Passport.js configuration are integrated into your main application file.
File: src/backend/app.js
or src/backend/server.js
const express = require('express');
const session = require('express-session');
const passport = require('./config/passport');
const authRoutes = require('./routes/auth');
const app = express();
app.use(session({
secret: 'your-session-secret',
resave: false,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
app.use('/auth', authRoutes);
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Update the Login.js
file to include a Google sign-in button and the necessary JavaScript to initiate the OAuth2.0 flow.
File: src/frontend/components/Login.js
import React, { useEffect } from 'react';
const Login = () => {
useEffect(() => {
window.gapi.load('auth2', () => {
window.gapi.auth2.init({
client_id: 'YOUR_GOOGLE_CLIENT_ID.apps.googleusercontent.com',
});
});
}, []);
const handleGoogleSignIn = () => {
const auth2 = window.gapi.auth2.getAuthInstance();
auth2.signIn().then(googleUser => {
const id_token = googleUser.getAuthResponse().id_token;
fetch('/api/auth/google', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ token: id_token }),
})
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error('Error:', error);
});
});
};
return (
<div>
<h2>Login</h2>
<button onClick={handleGoogleSignIn}>Sign in with Google</button>
</div>
);
};
export default Login;
Ensure that the Google API script is loaded in your HTML file.
File: public/index.html
<script src="https://apis.google.com/js/platform.js" async defer></script>
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