Advertisement
amt

DevQ

amt
Jan 19th, 2025
18
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. To integrate Google login and enable saving files to Google Drive in a React application, you can use the **Google Identity Services API** for authentication and the **Google Drive API** for file operations. Below is a step-by-step guide:
  3.  
  4. ---
  5.  
  6. ### 1. **Set Up a Google Cloud Project**
  7. - Go to the [Google Cloud Console](https://console.cloud.google.com/).
  8. - Create a new project.
  9. - Enable the **Google Drive API** for your project.
  10. - Configure the **OAuth consent screen**:
  11.   - Add your application name.
  12.   - Specify scopes for Drive and User Info.
  13. - Create **OAuth 2.0 Client IDs**:
  14.   - Set the application type to **Web Application**.
  15.   - Add your authorized redirect URI (e.g., `http://localhost:3000` for development).
  16.  
  17. ---
  18.  
  19. ### 2. **Install Required Libraries**
  20. Install the required libraries using npm or yarn:
  21.  
  22. ```bash
  23. npm install @react-oauth/google
  24. ```
  25.  
  26. ---
  27.  
  28. ### 3. **Authenticate with Google Login**
  29. Use the `@react-oauth/google` package to handle Google login.
  30.  
  31. ---
  32.  
  33. ### 4. **Save Files to Google Drive**
  34. Use the access token obtained after login to interact with the Google Drive API.
  35.  
  36. ---
  37.  
  38. ### 5. **Code Implementation**
  39.  
  40. Here’s the full implementation:
  41.  
  42. #### `App.js`
  43.  
  44. ```javascript
  45. import React, { useState } from "react";
  46. import { GoogleOAuthProvider, googleLogout, useGoogleLogin } from "@react-oauth/google";
  47. import axios from "axios";
  48.  
  49. function App() {
  50.   const [user, setUser] = useState(null);
  51.   const [accessToken, setAccessToken] = useState(null);
  52.  
  53.   const login = useGoogleLogin({
  54.     onSuccess: (tokenResponse) => {
  55.       setAccessToken(tokenResponse.access_token);
  56.       fetchUserInfo(tokenResponse.access_token);
  57.     },
  58.     onError: () => console.error("Login Failed"),
  59.     scope: "https://www.googleapis.com/auth/drive.file",
  60.   });
  61.  
  62.   const fetchUserInfo = async (token) => {
  63.     try {
  64.       const res = await axios.get("https://www.googleapis.com/oauth2/v3/userinfo", {
  65.         headers: { Authorization: `Bearer ${token}` },
  66.       });
  67.       setUser(res.data);
  68.     } catch (err) {
  69.       console.error("Error fetching user info", err);
  70.     }
  71.   };
  72.  
  73.   const uploadToDrive = async () => {
  74.     if (!accessToken) {
  75.       alert("Please log in first!");
  76.       return;
  77.     }
  78.  
  79.     const fileContent = "Hello, Google Drive!";
  80.     const file = new Blob([fileContent], { type: "text/plain" });
  81.     const metadata = {
  82.       name: "example.txt", // Filename
  83.       mimeType: "text/plain", // File type
  84.     };
  85.  
  86.     const form = new FormData();
  87.     form.append("metadata", new Blob([JSON.stringify(metadata)], { type: "application/json" }));
  88.     form.append("file", file);
  89.  
  90.     try {
  91.       const res = await axios.post("https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart", form, {
  92.         headers: {
  93.           Authorization: `Bearer ${accessToken}`,
  94.           "Content-Type": "multipart/form-data",
  95.         },
  96.       });
  97.       alert("File uploaded successfully!");
  98.     } catch (err) {
  99.       console.error("Error uploading file to Google Drive", err);
  100.     }
  101.   };
  102.  
  103.   const logout = () => {
  104.     googleLogout();
  105.     setUser(null);
  106.     setAccessToken(null);
  107.   };
  108.  
  109.   return (
  110.     <GoogleOAuthProvider clientId="YOUR_CLIENT_ID.apps.googleusercontent.com">
  111.       <div style={{ padding: "20px" }}>
  112.         {!user ? (
  113.           <button onClick={() => login()}>Login with Google</button>
  114.         ) : (
  115.           <div>
  116.             <h2>Welcome, {user.name}</h2>
  117.             <button onClick={uploadToDrive}>Upload File to Google Drive</button>
  118.             <button onClick={logout}>Logout</button>
  119.           </div>
  120.         )}
  121.       </div>
  122.     </GoogleOAuthProvider>
  123.   );
  124. }
  125.  
  126. export default App;
  127. ```
  128.  
  129. ---
  130.  
  131. ### 6. **Steps in the Code**
  132. 1. **Login with Google**:
  133.    - `useGoogleLogin` initiates the OAuth 2.0 login.
  134.    - After a successful login, the user's access token is saved.
  135.  
  136. 2. **Fetch User Info**:
  137.    - Use the access token to fetch user profile details.
  138.  
  139. 3. **Upload to Google Drive**:
  140.    - Use the `axios` library to send a POST request with the file and metadata to the Google Drive API.
  141.  
  142. 4. **Logout**:
  143.    - Clears the login state using `googleLogout`.
  144.  
  145. ---
  146.  
  147. ### 7. **Important Notes**
  148. - Replace `"YOUR_CLIENT_ID.apps.googleusercontent.com"` with the client ID from your Google Cloud project.
  149. - Ensure you have added the required **OAuth Scopes** for Google Drive (`https://www.googleapis.com/auth/drive.file`).
  150. - For production, configure your Google Cloud project with the proper **Authorized Redirect URIs**.
  151.  
  152. This setup provides a seamless Google login experience and the ability to save files to Google Drive in a React application.
  153.  
  154. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement