Open Khumpol opened 7 months ago
To implement Google sign-in functionality, we need to update the backend to handle authentication with Google and create or update user records accordingly. On the frontend, we need to provide a way for users to initiate the Google sign-in process and handle the response.
backend/userModel.js
and backend/authController.js
)userModel.js
to include fields for storing Google user information.authController.js
to verify the token received from the frontend and create or update the user record in the database.backend/userModel.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 },
googleToken: { type: String, required: false },
// Additional fields as needed
});
const User = mongoose.model('User', userSchema);
module.exports = User;
backend/authController.js
const { OAuth2Client } = require('google-auth-library');
const jwt = require('jsonwebtoken');
const User = require('./userModel');
const CLIENT_ID = 'your-google-client-id';
const client = new OAuth2Client(CLIENT_ID);
async function verifyGoogleToken(token) {
const ticket = await client.verifyIdToken({
idToken: token,
audience: CLIENT_ID,
});
const payload = ticket.getPayload();
return payload;
}
async function findOrCreateUser(googleData) {
let user = await User.findOne({ googleId: googleData.sub });
if (!user) {
user = new User({
googleId: googleData.sub,
email: googleData.email,
name: googleData.name,
// Additional fields as needed
});
await user.save();
}
return user;
}
function createSessionToken(user) {
const payload = {
userId: user._id,
email: user.email,
// Additional claims as needed
};
return jwt.sign(payload, 'your-secret-key', { expiresIn: '24h' });
}
app.post('/api/auth/google', async (req, res) => {
try {
const googleData = await verifyGoogleToken(req.body.token);
const user = await findOrCreateUser(googleData);
const token = createSessionToken(user);
res.status(200).json({ token });
} catch (error) {
res.status(401).json({ message: 'Authentication failed', error });
}
});
frontend/auth.js
and frontend/login.html
)login.html
.auth.js
to handle the Google sign-in response and communicate with the backend.frontend/login.html
<!DOCTYPE html>
<html lang="en">
<head>
<!-- ... -->
</head>
<body>
<!-- ... -->
<div id="gSignInWrapper">
<div id="customBtn" class="customGPlusSignIn">
<span class="icon"></span>
<span class="buttonText">Google</span>
</div>
</div>
<script src="https://apis.google.com/js/platform.js" async defer></script>
<script src="auth.js"></script>
</body>
</html>
frontend/auth.js
gapi.load('auth2', function() {
gapi.auth2.init({
client_id: 'YOUR_CLIENT_ID.apps.googleusercontent.com',
}).then(function () {
gapi.signin2.render('customBtn', {
'scope': 'profile email',
'onsuccess': onSignIn,
'onfailure': onFailure
});
});
});
function onSignIn(googleUser) {
var id_token = googleUser.getAuthResponse().id_token;
var xhr = new XMLHttpRequest();
xhr.open('POST', '/api/auth/google');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
if (xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
sessionStorage.setItem('sessionToken', response.token);
window.location.href = '/dashboard.html';
} else {
console.error('Sign-in error:', xhr.responseText);
}
};
xhr.send(JSON.stringify({ token: id_token }));
}
function onFailure(error) {
console.error('Google sign-in failed:', error);
}
function signOut() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
console.log('User signed out.');
});
}
initGoogleSignIn();
Make sure to replace placeholders like 'your-google-client-id'
, 'your-secret-key'
, and 'YOUR_CLIENT_ID.apps.googleusercontent.com'
with actual values from your Google Developer Console and your secret key. Additionally, ensure that the backend endpoint /api/auth/google
matches the route defined in authController.js
.
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