Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- 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:
- ---
- ### 1. **Set Up a Google Cloud Project**
- - Go to the [Google Cloud Console](https://console.cloud.google.com/).
- - Create a new project.
- - Enable the **Google Drive API** for your project.
- - Configure the **OAuth consent screen**:
- - Add your application name.
- - Specify scopes for Drive and User Info.
- - Create **OAuth 2.0 Client IDs**:
- - Set the application type to **Web Application**.
- - Add your authorized redirect URI (e.g., `http://localhost:3000` for development).
- ---
- ### 2. **Install Required Libraries**
- Install the required libraries using npm or yarn:
- ```bash
- npm install @react-oauth/google
- ```
- ---
- ### 3. **Authenticate with Google Login**
- Use the `@react-oauth/google` package to handle Google login.
- ---
- ### 4. **Save Files to Google Drive**
- Use the access token obtained after login to interact with the Google Drive API.
- ---
- ### 5. **Code Implementation**
- Here’s the full implementation:
- #### `App.js`
- ```javascript
- import React, { useState } from "react";
- import { GoogleOAuthProvider, googleLogout, useGoogleLogin } from "@react-oauth/google";
- import axios from "axios";
- function App() {
- const [user, setUser] = useState(null);
- const [accessToken, setAccessToken] = useState(null);
- const login = useGoogleLogin({
- onSuccess: (tokenResponse) => {
- setAccessToken(tokenResponse.access_token);
- fetchUserInfo(tokenResponse.access_token);
- },
- onError: () => console.error("Login Failed"),
- scope: "https://www.googleapis.com/auth/drive.file",
- });
- const fetchUserInfo = async (token) => {
- try {
- const res = await axios.get("https://www.googleapis.com/oauth2/v3/userinfo", {
- headers: { Authorization: `Bearer ${token}` },
- });
- setUser(res.data);
- } catch (err) {
- console.error("Error fetching user info", err);
- }
- };
- const uploadToDrive = async () => {
- if (!accessToken) {
- alert("Please log in first!");
- return;
- }
- const fileContent = "Hello, Google Drive!";
- const file = new Blob([fileContent], { type: "text/plain" });
- const metadata = {
- name: "example.txt", // Filename
- mimeType: "text/plain", // File type
- };
- const form = new FormData();
- form.append("metadata", new Blob([JSON.stringify(metadata)], { type: "application/json" }));
- form.append("file", file);
- try {
- const res = await axios.post("https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart", form, {
- headers: {
- Authorization: `Bearer ${accessToken}`,
- "Content-Type": "multipart/form-data",
- },
- });
- alert("File uploaded successfully!");
- } catch (err) {
- console.error("Error uploading file to Google Drive", err);
- }
- };
- const logout = () => {
- googleLogout();
- setUser(null);
- setAccessToken(null);
- };
- return (
- <GoogleOAuthProvider clientId="YOUR_CLIENT_ID.apps.googleusercontent.com">
- <div style={{ padding: "20px" }}>
- {!user ? (
- <button onClick={() => login()}>Login with Google</button>
- ) : (
- <div>
- <h2>Welcome, {user.name}</h2>
- <button onClick={uploadToDrive}>Upload File to Google Drive</button>
- <button onClick={logout}>Logout</button>
- </div>
- )}
- </div>
- </GoogleOAuthProvider>
- );
- }
- export default App;
- ```
- ---
- ### 6. **Steps in the Code**
- 1. **Login with Google**:
- - `useGoogleLogin` initiates the OAuth 2.0 login.
- - After a successful login, the user's access token is saved.
- 2. **Fetch User Info**:
- - Use the access token to fetch user profile details.
- 3. **Upload to Google Drive**:
- - Use the `axios` library to send a POST request with the file and metadata to the Google Drive API.
- 4. **Logout**:
- - Clears the login state using `googleLogout`.
- ---
- ### 7. **Important Notes**
- - Replace `"YOUR_CLIENT_ID.apps.googleusercontent.com"` with the client ID from your Google Cloud project.
- - Ensure you have added the required **OAuth Scopes** for Google Drive (`https://www.googleapis.com/auth/drive.file`).
- - For production, configure your Google Cloud project with the proper **Authorized Redirect URIs**.
- This setup provides a seamless Google login experience and the ability to save files to Google Drive in a React application.
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement