Quantcast
Channel: Active questions tagged svelte - Stack Overflow
Viewing all articles
Browse latest Browse all 1541

Google Drive API in svelte - How to make user don't have to re-signIn after reload the page

$
0
0

Hey I'm just wondering how can i use google drive api to let user don't have to re-sign in the account to make request with google drie api in my svelte project

For now after i signIn everything works well I can upload, read, update file, but after i refresh the page i can't do any of them, I know there is refreshToken for this, but I can't use it(return undefined)AI told me to place something like:

await gapi.auth2.setAuthInstance().setOptions({      access_type: 'offline'});//orawait gapi.client.setAccessToken('offline');

in initializeGapiClient() or login() but the browser console shows they are not defined.

Here are some of my code:

Import the api with <svelte:head> which include

<svelte:head><script async defer src="https://apis.google.com/js/api.js"></script><script async defer src="https://accounts.google.com/gsi/client"></script></svelte:head>

I load the api when page load

$: onMount(() => {    gapiLoaded();    gisLoaded();});

the code of relative function up there

let gapiInited = false;let gisInited = false;const DISCOVERY_DOCS = ['https://www.googleapis.com/discovery/v1/apis/drive/v3/rest'];const SCOPES = 'https://www.googleapis.com/auth/drive';// ... CLIENT_ID CLIENT_SECRET API_KEY function gapiLoaded() {    gapi.load('client', initializeGapiClient);}async function initializeGapiClient() {    await gapi.client.init({        apiKey: API_KEY,        discoveryDocs: DISCOVERY_DOCS    });    gapiInited = true;}    function gisLoaded() {    tokenClient = google.accounts.oauth2.initTokenClient({        client_id: CLIENT_ID,        client_secret: CLIENT_SECRET,        scope: SCOPES,        callback: ''    });    gisInited = true;}

when user signIn

function SignIn() {    tokenClient.callback = async (resp) => {        if (resp.error !== undefined) {              throw resp;        }        const tokens = await gapi.auth.getToken();        const accessToken = tokens.access_token;        const refreshToken = tokens.refresh_token; // <- get undefined        localStorage.setItem('token', accessToken);        localStorage.setItem('refresh_token', refreshToken);  // <- get undefined        authed = true;        console.log('Sign-in Successful');    };    if (gapi.client.getToken() === null) {        tokenClient.requestAccessToken({ prompt: 'consent' });    } else {        tokenClient.requestAccessToken({ prompt: '' });    }}

upload file

function upload() {    if (uploadData != null) {        const blob = new Blob([JSON.stringify(uploadData)], { type: 'application/json'});        const parentFolder = localStorage.getItem('parent_folder');        let fileName = 'smoothword-data'; // set file metadata        let metadata = {            name: fileName +'.json',            mimeType: 'application/json',            parents: [parentFolder]        };        let formData = new FormData();        formData.append('metadata',            new Blob([JSON.stringify(metadata)], { type: 'application/json' })        );        formData.append('file', blob);        fetch('https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart', {            method: 'POST',            headers: new Headers({                Authorization: 'Bearer '+ localStorage.getItem('token')            }),            body: formData        })            .then(function (response) {                localStorage.setItem('file_id', response.id);                return response.json();            })            .then(function (value) {                console.log(value);            });    }}

Viewing all articles
Browse latest Browse all 1541

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>