I want to get the messages of users by gmail api. For that google authorization is needed. I managed to authorize the user by following code -
let authBtn = document.getElementById('authorize_button');
const CLIENT_ID = 'XXXXXX-XXXXXXXXXXX.apps.googleusercontent.com';
const API_KEY = 'XXXXXX-XXXXXXXXXXXXXXX';
const DISCOVERY_DOC = 'https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest';
const SCOPES = 'https://www.googleapis.com/auth/gmail.readonly';
let tokenClient;
let gapiInited = false;
let gisInited = false;
authBtn.style.visibility = 'hidden';
function gapiLoaded() {
gapi.load('client', intializeGapiClient);
}
async function intializeGapiClient() {
await gapi.client.init({
apiKey: API_KEY,
discoveryDocs: [DISCOVERY_DOC],
});
gapiInited = true;
maybeEnableButtons();
}
function gisLoaded() {
tokenClient = google.accounts.oauth2.initTokenClient({
client_id: CLIENT_ID,
scope: SCOPES,
callback: '',
});
gisInited = true;
maybeEnableButtons();
}
function maybeEnableButtons() {
if (gapiInited && gisInited) {
authBtn.style.visibility = 'visible';
}
}
function handleAuthClick() {
tokenClient.callback = async (resp) => {
if (resp.error !== undefined) throw (resp);
authBtn.innerText = 'Refresh';
await getMessages();
};
if (gapi.client.getToken() === null) {
tokenClient.requestAccessToken({prompt: 'consent'});
} else {
tokenClient.requestAccessToken({prompt: ''});
}
}
In above code gapi.client.getToken() === null is always false. Everytime I refresh the page I have to reauthorize user with prompt: 'consent'.
I also want user to stay signed in until user sign out.
How can I achieve by modifying the above code?
Can Please someone help me?