Closed OwlbanGroup closed 8 months ago
The task involves implementing Google sign-in functionality on both the front end and back end of a web application. The front end requires a Google sign-in button and the necessary JavaScript to handle the sign-in process, while the back end needs to verify the Google ID token and manage user sessions.
onSignIn
function to handle the sign-in success event.<!-- Add the Google API script tag -->
<script src="https://apis.google.com/js/platform.js" async defer></script>
<meta name="google-signin-client_id" content="YOUR_CLIENT_ID.apps.googleusercontent.com">
<!-- Add the Google sign-in button -->
<div class="g-signin2" data-onsuccess="onSignIn"></div>
<script>
function onSignIn(googleUser) {
// Handle sign-in
}
function signOut() {
// Handle sign-out
}
</script>
function loadGoogleAPI() {
gapi.load('auth2', function() {
gapi.auth2.init({
client_id: 'YOUR_CLIENT_ID.apps.googleusercontent.com',
scope: 'profile email'
}).then(function () {
gapi.signin2.render('google-signin-button', {
'onsuccess': onSignIn
});
});
});
}
function onSignIn(googleUser) {
var id_token = googleUser.getAuthResponse().id_token;
sendTokenToBackend(id_token);
}
function sendTokenToBackend(id_token) {
fetch('YOUR_BACKEND_ENDPOINT', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ token: id_token })
})
.then(response => response.json())
.then(data => {
console.log('Token verified by backend:', data);
})
.catch(error => {
console.error('Error sending token to backend:', error);
});
}
window.onload = loadGoogleAPI;
const { OAuth2Client } = require('google-auth-library');
const User = require('./models/user');
const client = new OAuth2Client(CLIENT_ID);
async function verifyToken(token) {
const ticket = await client.verifyIdToken({
idToken: token,
audience: CLIENT_ID,
});
const payload = ticket.getPayload();
return payload;
}
async function findOrCreateUser(userData) {
let user = await User.findOne({ googleId: userData.sub });
if (!user) {
user = new User({
googleId: userData.sub,
email: userData.email,
name: userData.name,
});
await user.save();
}
return user;
}
exports.googleSignIn = async (req, res) => {
try {
const { token } = req.body;
const userData = await verifyToken(token);
const user = await findOrCreateUser(userData);
req.session.userId = user._id;
res.status(200).json({ message: 'User signed in successfully', user });
} catch (error) {
res.status(500).json({ message: 'Authentication failed', error });
}
};
Make sure to replace CLIENT_ID
with your actual Google client ID, adjust the User model according to your application, and set up the necessary middleware for handling sessions and JSON requests.
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