Open erfanNectar opened 9 months ago
To implement Google sign-in on both the front end and back end, we will follow the steps outlined in the "Changes to files" section. The front end will be responsible for rendering the Google sign-in button and handling the sign-in process, while the back end will verify the ID token sent by the front end and create or update the user record in the database.
frontend/auth.js
)// Load the Google API Library in the HTML file with a script tag
// Initialize the Google Auth API
function initGoogleAuth() {
gapi.load('auth2', function() {
gapi.auth2.init({
client_id: 'YOUR_CLIENT_ID.apps.googleusercontent.com',
scope: 'profile email'
}).then(function () {
renderGoogleSignInButton();
});
});
}
// Render the Google Sign-in Button
function renderGoogleSignInButton() {
gapi.signin2.render('google-signin-button', {
'onsuccess': onGoogleSignIn
});
}
// Sign-in Callback Function
function onGoogleSignIn(googleUser) {
var id_token = googleUser.getAuthResponse().id_token;
sendTokenToBackend(id_token);
}
// Helper function to send the ID token to the backend
function sendTokenToBackend(id_token) {
var xhr = new XMLHttpRequest();
xhr.open('POST', '/api/auth/google-signin');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
if (xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
localStorage.setItem('sessionToken', response.token);
// Redirect to user dashboard or perform other actions
} else {
// Handle errors
}
};
xhr.send(JSON.stringify({ token: id_token }));
}
// Call the init function when the window loads
window.onload = function() {
initGoogleAuth();
};
backend/userModel.js
)const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
// Standard fields
username: { type: String, unique: true, sparse: true },
email: { type: String, unique: true, required: true },
password: { type: String },
// Google authentication fields
googleId: { type: String, unique: true, sparse: true },
googleToken: { type: String },
googleRefreshToken: { type: String },
// Profile information
profilePicture: { type: String },
displayName: { type: String },
// Additional fields
createdAt: { type: Date, default: Date.now },
updatedAt: { type: Date, default: Date.now },
});
const User = mongoose.model('User', userSchema);
module.exports = User;
backend/authController.js
)const { OAuth2Client } = require('google-auth-library');
const User = require('./userModel');
const jwt = require('jsonwebtoken');
const CLIENT_ID = 'YOUR_GOOGLE_CLIENT_ID';
const client = new OAuth2Client(CLIENT_ID);
async function verifyToken(idToken) {
const ticket = await client.verifyIdToken({
idToken: idToken,
audience: CLIENT_ID,
});
const payload = ticket.getPayload();
return payload;
}
async function handleGoogleSignIn(req, res) {
try {
const { token } = req.body;
const googleUser = await verifyToken(token);
let user = await User.findOne({ googleId: googleUser.sub });
if (!user) {
user = await User.create({
googleId: googleUser.sub,
email: googleUser.email,
displayName: googleUser.name,
// Add other fields as necessary
});
}
const sessionToken = jwt.sign({ userId: user._id }, 'YOUR_SECRET_KEY', { expiresIn: '1h' });
res.status(200).json({
message: 'User logged in successfully',
sessionToken: sessionToken,
user: user,
});
} catch (error) {
res.status(500).json({ message: 'Error signing in with Google', error: error });
}
}
module.exports = {
handleGoogleSignIn,
};
frontend/login.html
)<!-- Inside frontend/login.html -->
<div id="google-signin-button"></div>
<script src="https://apis.google.com/js/platform.js" async defer></script>
<script src="path/to/auth.js"></script> <!-- Include the auth.js script -->
<meta name="google-signin-client_id" content="YOUR_CLIENT_ID.apps.googleusercontent.com">
In this solution, we have provided the necessary code snippets to implement Google sign-in on both the front end and back end. The front end will render a Google sign-in button and handle the sign-in process, while the back end will verify the ID token and manage user records. Remember to replace placeholders like YOUR_CLIENT_ID
and YOUR_SECRET_KEY
with your actual credentials.
Click here to create a Pull Request with the proposed solution
Files used for this task:
Hey @autopilot implement a Google sign-in on my website. Make changes to the front end and the back end of the application
I want to allow users to signup and login using their Google account