Open 1alireza32109 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 updating the user model to store Google-specific information, configuring Google OAuth 2.0 settings, adding a Google sign-in button on the front end, and creating the necessary backend routes and controllers to handle the sign-in process.
We need to update the user model to include fields for storing Google-specific user information such as Google ID and email.
backend/models/user.js
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
googleId: {
type: String,
required: true,
unique: true
},
email: {
type: String,
required: true,
unique: true
},
name: {
type: String,
required: true
},
// Add any other fields you need for your user model
}, {
timestamps: true
});
const User = mongoose.model('User', userSchema);
module.exports = User;
Create a configuration file to store Google OAuth 2.0 settings such as client ID and client secret.
backend/config/googleAuthConfig.js
require('dotenv').config();
module.exports = {
googleClientID: process.env.GOOGLE_CLIENT_ID,
googleClientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: '/auth/google/callback'
};
Ensure that you have the environment variables set up in your .env
file:
GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret
Update the front end to include a Google sign-in button and initialize Google Sign-In.
frontend/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Google Sign-In</title>
<script src="https://apis.google.com/js/platform.js" async defer></script>
<meta name="google-signin-client_id" content="YOUR_GOOGLE_CLIENT_ID.apps.googleusercontent.com">
</head>
<body>
<div class="g-signin2" data-onsuccess="onSignIn"></div>
<script>
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
var id_token = googleUser.getAuthResponse().id_token;
fetch('/auth/google-signin', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ id_token: id_token })
}).then(response => {
if (response.ok) {
window.location.href = '/dashboard';
} else {
console.error('Failed to sign in');
}
});
}
</script>
</body>
</html>
Create a controller to handle Google sign-in, verify the Google ID token, and manage user sessions.
backend/controllers/authController.js
const { OAuth2Client } = require('google-auth-library');
const User = require('../models/user');
const config = require('../config/googleAuthConfig');
const client = new OAuth2Client(config.googleClientID);
async function verifyGoogleToken(idToken) {
try {
const ticket = await client.verifyIdToken({
idToken,
audience: config.googleClientID,
});
const payload = ticket.getPayload();
return payload;
} catch (error) {
throw new Error('Invalid Google ID token');
}
}
async function googleSignIn(req, res) {
const { id_token } = req.body;
try {
const googleUser = await verifyGoogleToken(id_token);
let user = await User.findOne({ googleId: googleUser.sub });
if (!user) {
user = new User({
googleId: googleUser.sub,
email: googleUser.email,
name: googleUser.name,
});
await user.save();
}
// Create or update user session
req.session.userId = user._id;
res.status(200).json({ success: true });
} catch (error) {
res.status(400).json({ success: false, message: error.message });
}
}
module.exports = {
googleSignIn,
};
Define routes to handle Google sign-in and user session management.
backend/routes/auth.js
const express = require('express');
const router = express.Router();
const authController = require('../controllers/authController');
router.post('/google-signin', authController.googleSignIn);
module.exports = router;
Initialize the Google API client and handle the sign-in process on the front end.
frontend/auth.js
function initializeGoogleSignIn() {
gapi.load('auth2', function() {
gapi.auth2.init({
client_id: 'YOUR_GOOGLE_CLIENT_ID.apps.googleusercontent.com'
});
});
}
function onGoogleSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
var id_token = googleUser.getAuthResponse().id_token;
fetch('/auth/google-signin', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ id_token: id_token })
})
.then(response => response.json())
.then(data => {
if (data.success) {
window.location.href = '/dashboard';
} else {
console.error('Sign-in failed:', data.message);
}
})
.catch(error => {
console.error('Error during sign-in:', error);
});
}
document.getElementById('google-signin-button').addEventListener('click', function() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signIn().then(onGoogleSignIn);
});
window.onload = initializeGoogleSignIn;
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