Open ovo63 opened 1 month ago
To implement Google sign-in on your website, we need to make changes to both the front end and the back end of your application. The front end will include a Google sign-in button, and the back end will handle the OAuth 2.0 flow, user authentication, and session management.
src/frontend/App.js
Create the App.js
file and ensure it imports and includes the Login
component.
// src/frontend/App.js
import React from 'react';
import Login from './components/Login';
function App() {
return (
<div className="App">
<header className="App-header">
<h1>Welcome to My App</h1>
<Login />
</header>
</div>
);
}
export default App;
src/frontend/components/Login.js
Implement the Google sign-in button and handle the OAuth 2.0 redirect to Google's authentication page.
Install the required package:
npm install react-google-login
Create the Login.js
file:
import React from 'react';
import { GoogleLogin } from 'react-google-login';
const Login = () => {
const clientId = 'YOUR_GOOGLE_CLIENT_ID'; // Replace with your Google Client ID
const onSuccess = (response) => {
console.log('Login Success: currentUser:', response.profileObj);
// You can send the response token to your backend for further processing
// Example: axios.post('/api/auth/google', { token: response.tokenId });
};
const onFailure = (response) => {
console.log('Login failed: res:', response);
alert('Failed to login. Please try again.');
};
return (
<div>
<h2>Login</h2>
<GoogleLogin
clientId={clientId}
buttonText="Login with Google"
onSuccess={onSuccess}
onFailure={onFailure}
cookiePolicy={'single_host_origin'}
/>
</div>
);
};
export default Login;
src/backend/models/User.js
Define a user model that includes fields for storing Google account information.
Install Mongoose:
npm install mongoose
Create the User.js
file:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserSchema = new Schema({
googleId: {
type: String,
required: true,
unique: true
},
email: {
type: String,
required: true,
unique: true
},
name: {
type: String,
required: true
},
createdAt: {
type: Date,
default: Date.now
}
});
const User = mongoose.model('User', UserSchema);
module.exports = User;
src/backend/config/passport.js
Set up Passport.js with the Google OAuth 2.0 strategy.
Install required packages:
npm install passport passport-google-oauth20 dotenv
Create the passport.js
file:
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 = new User({
googleId: profile.id,
email: profile.emails[0].value,
name: profile.displayName
});
await user.save();
}
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;
src/backend/routes/auth.js
Implement the routes for handling the OAuth 2.0 flow.
Install required packages:
npm install express passport passport-google-oauth20 dotenv
Create the auth.js
file:
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: '/' }),
function(req, res) {
res.redirect('/');
});
module.exports = router;
Ensure your main server file (e.g., server.js
or app.js
) uses the auth
routes.
const express = require('express');
const passport = require('./config/passport');
const session = require('express-session');
const authRoutes = require('./routes/auth');
require('dotenv').config();
const app = express();
app.use(session({ secret: 'your-secret-key', resave: false, saveUninitialized: true }));
app.use(passport.initialize());
app.use(passport.session());
app.use('/auth', authRoutes);
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Ensure you have the following environment variables set in your .env
file:
GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret
GOOGLE_CALLBACK_URL=http://localhost:3000/auth/google/callback
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:
// src/frontend/App.js
import React from 'react'; import Login from './components/Login';
function App() { return (
); }
export default App;
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