Open danielCalbonero12345 opened 3 weeks 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 setting up Google OAuth token verification and user session management on the server side, and integrating the Google sign-in button on the client side.
auth.js
for Google OAuth Token VerificationCreate a new file src/server/auth.js
to handle Google OAuth token verification and user session management.
File Path: src/server/auth.js
Code:
const { OAuth2Client } = require('google-auth-library');
const CLIENT_ID = process.env.GOOGLE_CLIENT_ID;
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;
}
function createSession(user) {
// Implement session creation logic here
// For example, you can use JWT or express-session
}
module.exports = {
verifyToken,
createSession,
};
Create a new file src/server/routes.js
to define the necessary API endpoints for handling Google sign-in requests.
File Path: src/server/routes.js
Code:
const express = require('express');
const { verifyToken, createSession } = require('./auth');
const router = express.Router();
router.post('/auth/google', async (req, res) => {
const { token } = req.body;
try {
const user = await verifyToken(token);
// Handle user session management here, e.g., creating a session or JWT token
res.status(200).json({ message: 'Sign-in successful', user });
} catch (error) {
res.status(401).json({ message: 'Invalid token', error: error.message });
}
});
module.exports = router;
Ensure that the main server file (e.g., server.js
or app.js
) uses the routes defined in routes.js
.
File Path: src/server/app.js
(or server.js
)
Code:
const express = require('express');
const bodyParser = require('body-parser');
const routes = require('./routes');
const app = express();
app.use(bodyParser.json());
app.use('/api', routes);
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
package.json
to Include react-google-login
Add the react-google-login
package to handle the Google sign-in process on the front end.
File Path: package.json
Code:
{
"dependencies": {
"react-google-login": "^5.2.2"
}
}
Run the following command to install the new dependency:
npm install
Update the src/components/HomepageFeatures/styles.module.css
file to add styles for the Google sign-in button.
File Path: src/components/HomepageFeatures/styles.module.css
Code:
.googleSignInButton {
background-color: #4285F4;
color: white;
border: none;
border-radius: 4px;
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
transition: background-color 0.3s ease;
}
.googleSignInButton:hover {
background-color: #357ae8;
}
.googleSignInButton:active {
background-color: #2a65c7;
}
.googleSignInButton img {
margin-right: 8px;
}
Update the src/components/HomepageFeatures/index.js
file to add a Google sign-in button and handle the click event.
File Path: src/components/HomepageFeatures/index.js
Code:
import React from 'react';
import clsx from 'clsx';
import styles from './styles.module.css';
import { GoogleLogin } from 'react-google-login';
const FeatureList = [
{
title: 'Easy to Use',
Svg: require('@site/static/img/undraw_docusaurus_mountain.svg').default,
description: (
<>
Docusaurus was designed from the ground up to be easily installed and
used to get your website up and running quickly.
</>
),
},
{
title: 'Focus on What Matters',
Svg: require('@site/static/img/undraw_docusaurus_tree.svg').default,
description: (
<>
Docusaurus lets you focus on your docs, and we'll do the chores. Go
ahead and move your docs into the <code>docs</code> directory.
</>
),
},
{
title: 'Powered by React',
Svg: require('@site/static/img/undraw_docusaurus_react.svg').default,
description: (
<>
Extend or customize your website layout by reusing React. Docusaurus can
be extended while reusing the same header and footer.
</>
),
},
];
function Feature({Svg, title, description}) {
return (
<div className={clsx('col col--4')}>
<div className="text--center">
<Svg className={styles.featureSvg} role="img" />
</div>
<div className="text--center padding-horiz--md">
<h3>{title}</h3>
<p>{description}</p>
</div>
</div>
);
}
export default function HomepageFeatures() {
const handleLoginSuccess = (response) => {
console.log('Login Success:', response);
// Handle the login success, e.g., send the token to the server
};
const handleLoginFailure = (response) => {
console.log('Login Failed:', response);
// Handle the login failure
};
return (
<section className={styles.features}>
<div className="container">
<div className="row">
{FeatureList.map((props, idx) => (
<Feature key={idx} {...props} />
))}
</div>
<div className="text--center">
<GoogleLogin
clientId={process.env.REACT_APP_GOOGLE_CLIENT_ID}
buttonText="Sign in with Google"
onSuccess={handleLoginSuccess}
onFailure={handleLoginFailure}
cookiePolicy={'single_host_origin'}
/>
</div>
</div>
</section>
);
}
Update the docusaurus.config.js
file to load environment variables for the Google OAuth client ID and secret.
File Path: docusaurus.config.js
Code:
require('dotenv').config();
const lightCodeTheme = require('prism-react-renderer/themes/github');
const darkCodeTheme = require('prism-react-renderer/themes/dracula');
const config = {
title: 'Code Autopilot',
tagline: 'Documentation for </ autopilot >',
favicon: 'img/favicon.ico',
url: 'https://docs.codeautopilot.com',
baseUrl: '/',
organizationName: 'codeautopilot',
projectName: 'codeautopilot',
onBrokenLinks: 'throw',
onBrokenMarkdownLinks: 'warn',
i18n: {
defaultLocale: 'en',
locales: ['en'],
},
presets: [
[
'classic',
{
docs: {
routeBasePath: '/',
editUrl: 'https://github.com/codeautopilot/docs/tree/main/',
},
blog: false,
theme: {
customCss: require.resolve('./src/css/custom.css'),
},
},
],
],
themeConfig: {
image: 'img/autopilot.png',
navbar: {
title: '</ autopilot >',
items: [],
},
footer: {
style: 'dark',
links: [
{
title: 'Community',
items: [
{
label: 'Discord',
href: 'https://discord.gg/r72ykfvyx7',
},
],
},
],
copyright: `Copyright © ${new Date().getFullYear()} Code Autopilot`,
},
prism: {
theme: lightCodeTheme,
darkTheme: darkCodeTheme,
},
},
};
module.exports = config;
.env
FileCreate a .env
file in the root directory of your project and add your Google OAuth client ID and secret.
File Path: .env
Code:
GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret
By following these steps, you will have successfully implemented Google sign-in functionality on your website, including both the front end and the back end.
Click here to create a Pull Request with the proposed solution
Files used for this task:
docs
directory.
>
),
},
{
title: 'Powered by React',
Svg: require('@site/static/img/undraw_docusaurus_react.svg').default,
description: (
<>
Extend or customize your website layout by reusing React. Docusaurus can
be extended while reusing the same header and footer.
>
),
},
];
function Feature({Svg, title, description}) {
return (
{description}
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