devoric / GeminiProChat

MIT License
1 stars 0 forks source link

Task w #6

Open sgriggs3 opened 4 months ago

sgriggs3 commented 4 months ago

Describe the feature

I want to allow users to signup and login using their Google account @autopilot implement a Google sign-in on my website. Make changes to the front end and the back end of the application

Additional context

I want to allow users to signup and login using their Google account

Participation

codeautopilot[bot] commented 4 months ago

Potential solution

To implement Google sign-in, we will need to update the environment variables to include Google Client ID and Secret, add utility functions for Google token verification and user session management, update the API route to handle Google sign-in, and modify the front-end to include a Google sign-in button and the corresponding sign-in logic. The package.json file will also be updated to include the google-auth-library dependency.

How to implement

src/env.d.ts

src/utils/auth.ts

src/pages/api/auth.ts

src/pages/index.astro

README.md

package.json

By following these steps, we will have a complete Google sign-in implementation that includes both frontend and backend changes, along with the necessary documentation updates.

Click here to create a Pull Request with the proposed solution

Files used for this task:

Changes on src/env.d.ts To solve the task for the `src/env.d.ts` file, we need to define new environment variables for the Google Client ID and Client Secret that will be used for the Google sign-in feature. These environment variables will be used by the backend to verify the Google sign-in token and by the frontend to initiate the OAuth flow. Here's a practical proposal to update the `src/env.d.ts` file: ```typescript /// interface ImportMetaEnv { readonly GEMINI_API_KEY: string readonly HTTPS_PROXY: string readonly API_BASE_URL: string readonly HEAD_SCRIPTS: string readonly PUBLIC_SECRET_KEY: string readonly SITE_PASSWORD: string readonly OPENAI_API_MODEL: string readonly PUBLIC_MAX_HISTORY_MESSAGES: string // Add the following lines for Google OAuth configuration readonly GOOGLE_CLIENT_ID: string readonly GOOGLE_CLIENT_SECRET: string } interface ImportMeta { readonly env: ImportMetaEnv } ``` By adding `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` to the `ImportMetaEnv` interface, we declare that these environment variables should be available in the application. The developer will need to set these variables in their environment or `.env` file with the appropriate credentials obtained from the Google Developer Console. Remember to instruct the developer to add these variables to their `.env` file and to keep them secure, as they should not be committed to version control. The `.env` file should be added to `.gitignore` if it's not already there. After updating the `src/env.d.ts` file, the next steps would involve updating the backend and frontend code to use these new environment variables, as outlined in the tasks for the other files.
Changes on src/utils/auth.ts To implement Google sign-in functionality, we need to add utility functions that will handle the verification of Google tokens and manage user sessions. Here's a practical proposal for the changes that need to be made to the `src/utils/auth.ts` file: 1. Install the necessary npm package for verifying Google tokens: ```bash npm install google-auth-library ``` 2. Import the Google authentication library and define a function to verify the Google token: ```typescript import { OAuth2Client } from 'google-auth-library'; const CLIENT_ID = import.meta.env.PUBLIC_GOOGLE_CLIENT_ID as string; const client = new OAuth2Client(CLIENT_ID); export async function verifyGoogleToken(idToken: string) { const ticket = await client.verifyIdToken({ idToken: idToken, audience: CLIENT_ID, }); const payload = ticket.getPayload(); return payload; } ``` 3. Add a function to create a user session after successful Google sign-in: ```typescript // This function should be adapted to your session management strategy export function createUserSession(userId: string, userInfo: any) { // Implement session creation logic here // For example, setting a cookie with session information } ``` 4. Add a function to handle the sign-out process: ```typescript export function signOutUser(sessionId: string) { // Implement sign-out logic here // For example, destroying the session or removing the session cookie } ``` 5. Ensure that the environment variables for the Google Client ID (and possibly the Client Secret, if needed for backend operations) are defined in `src/env.d.ts` and provided in your environment configuration. 6. Update the `generateSignature` and `verifySignature` functions if necessary to integrate with the new Google sign-in process. This might involve updating the payload structure or the verification logic to accommodate the new sign-in method. 7. Test the new utility functions to ensure they work as expected with the Google sign-in flow. Remember to handle errors appropriately in all the new functions, such as catching exceptions from the Google token verification and handling invalid session scenarios. By following these steps, you will extend the `src/utils/auth.ts` file to support Google sign-in, which is a critical part of the backend logic for the feature requested by the user.
Changes on src/pages/api/auth.ts To extend the `src/pages/api/auth.ts` file to support Google sign-in, you will need to implement the following steps: 1. Install the `google-auth-library` package to your project using npm or yarn to help with verifying the Google sign-in token. 2. Import the necessary modules from `google-auth-library` and any other required utilities. 3. Define a new route or extend the existing `post` route to handle the Google sign-in token. 4. Use the Google client library to verify the token and extract the user's information. 5. Check if the user already exists in your database (you will need to implement this part based on your database setup). 6. If the user exists, update their record if necessary; if not, create a new user record. 7. Generate a session or a token for the user to keep them logged in. 8. Return a response to the client with the session/token information or an error message if the sign-in failed. Here is a rough implementation of the steps above: ```typescript import type { APIRoute } from 'astro' import { OAuth2Client } from 'google-auth-library' const client = new OAuth2Client(import.meta.env.GOOGLE_CLIENT_ID) export const post: APIRoute = async (context) => { const body = await context.request.json() // Assuming the body contains a Google ID token const { token } = body try { const ticket = await client.verifyIdToken({ idToken: token, audience: import.meta.env.GOOGLE_CLIENT_ID, }) const payload = ticket.getPayload() // Here you would check if the user exists in your database // and create or update the user record accordingly // This is a placeholder for your database logic const user = findOrCreateUser(payload) // Generate a session or token for the user const sessionToken = generateSessionToken(user) return new Response(JSON.stringify({ code: 0, message: 'Authentication successful', sessionToken, }), { headers: { 'Content-Type': 'application/json', }, }) } catch (error) { return new Response(JSON.stringify({ code: -1, message: 'Authentication failed', error: error.message, }), { headers: { 'Content-Type': 'application/json', }, status: 401, }) } } // Placeholder functions for database logic and session token generation function findOrCreateUser(payload) { // Implement your user lookup/creation logic here } function generateSessionToken(user) { // Implement your session token generation logic here } ``` Please note that you will need to replace the placeholder functions `findOrCreateUser` and `generateSessionToken` with actual implementations based on your application's requirements and database setup. Additionally, you will need to handle the environment variables for the Google Client ID and Client Secret, which should be defined in your `.env` file and accessed via `import.meta.env`.
Changes on src/pages/index.astro To implement Google sign-in on the website, we need to add a Google sign-in button to the front end and handle the OAuth flow. Here's a practical proposal for the `src/pages/index.astro` file: 1. Add a Google sign-in button to the page. 2. Load the Google Platform Library to use the Google Sign-In API. 3. Initialize the Google Sign-In client with the Google Client ID. 4. Implement the sign-in function to handle the sign-in process. 5. Send the Google sign-in token to the backend for verification. Here's how you can modify the `src/pages/index.astro` file: ```astro --- import Layout from '../layouts/Layout.astro' import Header from '../components/Header.astro' import Footer from '../components/Footer.astro' import Generator from '../components/Generator' import '../message.css' import 'katex/dist/katex.min.css' import 'highlight.js/styles/atom-one-dark.css' ---
Google
``` Make sure to replace `'YOUR_GOOGLE_CLIENT_ID'` with the actual Google Client ID provided by the Google Developer Console. This code adds a Google sign-in button to the page and sets up the client-side logic to handle the sign-in process. When a user clicks the button, they will be prompted to sign in with their Google account. After successful sign-in, the Google sign-in token is sent to the backend endpoint `/api/auth/google` for verification. Remember to handle the backend part in the `src/pages/api/auth.ts` file and add utility functions in `src/utils/auth.ts` as described in the task. Also, update the `package.json` to include any necessary npm packages, define environment variables in `src/env.d.ts`, and update the `README.md` with configuration steps.
Changes on README.md To address the task of implementing Google sign-in on the website, the README.md file should be updated with instructions on how to configure Google API credentials and set up the necessary environment variables. Here's a practical proposal for updating the README.md file: ### README.md Update Proposal ```markdown ## Google Sign-In Integration To enable users to sign up and log in using their Google account, you need to set up Google OAuth credentials and configure the necessary environment variables. ### Setting up Google OAuth Credentials 1. Go to the [Google Cloud Console](https://console.cloud.google.com/). 2. Create a new project or select an existing one. 3. Navigate to the "Credentials" page under "APIs & Services". 4. Click on "Create credentials" and select "OAuth client ID". 5. Configure the OAuth consent screen if prompted. 6. Select "Web application" as the application type. 7. Add the authorized JavaScript origins and redirect URIs for your application. 8. Once created, take note of the "Client ID" and "Client Secret". ### Configuring Environment Variables Add the following environment variables to your `.env` file or your deployment platform's environment configuration: | Name | Description | Required | | --- | --- | --- | | `GOOGLE_CLIENT_ID` | The Client ID obtained from the Google Cloud Console. | **✔** | | `GOOGLE_CLIENT_SECRET` | The Client Secret obtained from the Google Cloud Console. | **✔** | Example `.env` file entries: ```env GOOGLE_CLIENT_ID=your_google_client_id_here GOOGLE_CLIENT_SECRET=your_google_client_secret_here ``` Make sure to replace `your_google_client_id_here` and `your_google_client_secret_here` with the actual credentials you obtained from the Google Cloud Console. ### Frontend and Backend Changes Ensure that the frontend includes a Google sign-in button and the necessary client-side logic to initiate the OAuth flow. The backend should be extended to verify the Google sign-in token and handle user account creation or updates. For detailed implementation steps, refer to the documentation in the `src/pages/index.astro` and `src/pages/api/auth.ts` files. ``` This update to the README.md file provides clear instructions on how to obtain Google API credentials and how to configure the necessary environment variables for integrating Google sign-in into the website. It also gives a brief overview of the changes needed in the frontend and backend, directing the reader to the specific files for more detailed information.
Changes on package.json To implement Google sign-in functionality, you will need to install the `google-auth-library` package which provides the necessary tools to verify Google ID tokens on the server side. Here's how you can update the `package.json` file to include this dependency: ```json { "name": "chatgpt-api-demo", "version": "0.0.1", "packageManager": "pnpm@7.28.0", "scripts": { "dev": "astro dev", "start": "astro dev", "build": "astro build", "build:vercel": "OUTPUT=vercel astro build", "build:netlify": "OUTPUT=netlify astro build", "preview": "astro preview", "astro": "astro", "lint": "eslint . --ext .js,.jsx,.ts,.tsx,.astro", "lint:fix": "eslint . --ext .js,.jsx,.ts,.tsx,.astro --fix" }, "dependencies": { "@astrojs/netlify": "2.3.0", "@astrojs/node": "^5.3.0", "@astrojs/solid-js": "^2.2.0", "@astrojs/vercel": "^3.5.0", "@fuyun/generative-ai": "0.1.3", "@zag-js/slider": "^0.16.0", "@zag-js/solid": "^0.16.0", "astro": "^2.7.0", "eslint": "^8.43.0", "eventsource-parser": "^1.0.0", "google-auth-library": "^7.10.2", // Added google-auth-library "highlight.js": "^11.8.0", "js-sha256": "^0.9.0", "katex": "^0.16.7", "markdown-it": "^13.0.1", "markdown-it-highlightjs": "^4.0.1", "markdown-it-katex": "^2.0.3", "solid-js": "1.7.6", "solidjs-use": "^2.1.0", "undici": "^5.22.1" }, "devDependencies": { "@evan-yang/eslint-config": "^1.0.9", "@iconify-json/carbon": "^1.1.18", "@types/markdown-it": "^12.2.3", "@typescript-eslint/parser": "^5.60.0", "@vite-pwa/astro": "^0.1.1", "eslint-plugin-astro": "^0.27.1", "punycode": "^2.3.0", "unocss": "^0.50.8" } } ``` After updating the `package.json` file, you should run the package manager to install the new dependency. If you're using `pnpm` as indicated in the `package.json`, you can run the following command in your terminal: ```sh pnpm install ``` This will install the `google-auth-library` package along with any other dependencies that are needed. Once installed, you can proceed with implementing the backend logic to verify the Google sign-in token as described in the task for the `src/pages/api/auth.ts` file.