How to pick an file from google drive picker and make it publicly viwable by using Oauth2

  Kiến thức lập trình

Problem Statement –
I have to open a google drive picker to let user select the file, then I am storing only embed link at database.
At view I am showing user the embedded view of that file image, now the problem is
if image is publc or open to anyone then no problem, it shows view on all third party as well icognito
when user selects any non public or private image, it only shows view in same browser where, user email is logged in

Solution I am expecting
either

  1. Restrict user to select only publicly viewable images
  2. modify file permissions when user selects the file

error I am getting is
TypeError: gapi.auth.getToken() is null as oauth window is not opening

const handleOpenPicker = async () => {
    await loadGoogleApi();

    const authInstance = gapi.auth2.getAuthInstance();
    if (!authInstance.isSignedIn.get()) {
      await authInstance.signIn();
    }

    const accessToken = gapi.auth.getToken().access_token;
    if (!accessToken) {
      console.error("Access token is not available");
      return;
    }

    const openPicker = () => {
      // @ts-ignore
      const google = window.google;
      const picker = new google.picker.PickerBuilder()
        .setAppId(clientId)
        .setDeveloperKey(developerKey)
        .setOAuthToken(accessToken)
        .addView(google.picker.ViewId.DOCS_IMAGES_AND_VIDEOS)
        .setCallback(async (data: any) => {
          if (data.action === "picked" && data.docs && data.docs.length > 0) {
            const doc = data.docs[0];
            if (allowedDriveMediaTypes.includes(doc.mimeType)) {
              try {
                await makeFilePublic(doc.id);
                setLink(doc.url);
                handleSlideImageUpdate(index, undefined, doc.url);
                setOpenCloseState(false);
              } catch (error) {
                console.error("Error accessing file:", error);
              }
            } else {
              console.log("Unsupported file type");
            }
          } else if (data.action === "cancel") {
            console.log("User clicked cancel/close button");
          }
        })
        .build();

      picker.setVisible(true);
    };

    openPicker();
  };

// functoin to modify file permissions
  const makeFilePublic = async (fileId: string) => {
    try {
      await gapi.client.drive.permissions.create({
        fileId: fileId,
        resource: {
          role: "reader",
          type: "anyone",
        },
      });
      console.log("File made public");
    } catch (error) {
      console.error("Error making file public:", error);
    }
  };
export const loadGoogleApi = (): Promise<void> => {
  return new Promise((resolve, reject) => {
    if (typeof gapi !== "undefined") {
      resolve();
    } else {
      const script = document.createElement("script");
      script.src = "https://apis.google.com/js/api.js";
      script.onload = () => {
        gapi.load("client:auth2", async () => {
          try {
            await gapi.client.init({
              apiKey: process.env.NEXT_PUBLIC_GCP_DEVELOPER_KEY,
              clientId: process.env.NEXT_PUBLIC_GCP_OAUTH_CLIENT_ID,
              discoveryDocs: ["https://www.googleapis.com/discovery/v1/apis/drive/v3/rest"],
              scope: "https://www.googleapis.com/auth/drive.file",
            });

            // Ensure user signed in
            const authInstance = gapi.auth2.getAuthInstance();
            if (!authInstance.isSignedIn.get()) {
              await authInstance.signIn();
            }

            resolve();
          } catch (error) {
            reject(error);
          }
        });
      };
      script.onerror = (error) => reject(error);
      document.body.appendChild(script);
    }
  });
};

LEAVE A COMMENT