I have problem like as title. I sign in oauth2 and google return error
"Cannot read property 'spreadsheets' of undefined". I tried copy sample from google page and same error;
function makeApiCall() {
var spreadsheetBody = {
// TODO: Add desired properties to the request body.
};
var request = gapi.client.sheets.spreadsheets.create({}, spreadsheetBody);
request.then(function(response) {
// TODO: Change code below to process the `response` object:
console.log(response.result);
}, function(reason) {
console.error('error: ' + reason.result.error.message);
});
}
function initClient() {
var SCOPE = 'https://www.googleapis.com/auth/spreadsheets';
gapi.client.init({
'apiKey': 'myke',
'clientId': 'myclientID',
'scope': SCOPE,
// 'discoveryDocs': ['https://sheets.googleapis.com/$discovery/rest?version=v4'],
}).then(function() {
gapi.auth2.getAuthInstance().signIn();
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSignInStatus);
updateSignInStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
});
}
function updateSignInStatus(isSignedIn) {
if (isSignedIn) {
makeApiCall();
}
}
gapi.load('client:auth2', initClient);
It's because you've commented out the "Discovery Docs" line. GAPI needs to know the discovery docs in order to load the correct API endpoints.
Related
I created a very simple app script that returns ContentService.createTextOutput("Hello"), associated it with a Google Cloud project, and created a JavaScript program to get the return value. I can successfully execute, deploy, and use the link from the deploy screen and everything works as expected. The JavaScript program returns
"The script completed but the returned value is not a supported return type."
When I look at the log, I can see the script did complete. The Cloud Project has Drive API enabled (even though I don't use it) and I specified that scope as well when creating the token.
Here is the JavaScript code:
example.ts
import * as google from "googleapis";
import { authorizePromise } from "./authorizePromise";
import * as dotenv from "dotenv";
dotenv.config();
main();
async function main() {
const auth = await authorizePromise();
console.log("abut to call");
callAppsScript(auth);
}
/**
* Call an Apps Script function to list the folders in the user's root
* Drive folder.
*
* #param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/
function callAppsScript(auth) {
var scriptId = process.env.SCRIPT_ID;
console.log("Script ID: ", scriptId);
var script = new google.script_v1.Script({});
// Make the API request. The request object is included here as 'resource'.
console.log("running", auth);
script.scripts.run(
{
auth: auth,
scriptId: scriptId,
requestBody: { function: "doGet", devMode: true },
},
function (err, resp) {
if (err) {
// The API encountered a problem before the script started executing.
console.log("The API returned an error: " + err);
return;
}
if (resp.error) {
// The API executed, but the script returned an error.
// Extract the first (and only) set of error details. The values of this
// object are the script's 'errorMessage' and 'errorType', and an array
// of stack trace elements.
var error = resp.error.details[0];
console.log("Script error message: " + error.errorMessage);
console.log("Script error stacktrace:");
if (error.scriptStackTraceElements) {
// There may not be a stacktrace if the script didn't start executing.
for (var i = 0; i < error.scriptStackTraceElements.length; i++) {
var trace = error.scriptStackTraceElements[i];
console.log("\t%s: %s", trace.function, trace.lineNumber);
}
}
} else {
// The structure of the result will depend upon what the Apps Script
// function returns. Here, the function returns an Apps Script Object
// with String keys and values, and so the result is treated as a
// Node.js object (folderSet).
console.log(
"debug",
resp,
"response",
Object.keys(resp),
Object.values(resp),
// "resp data",
// Object.keys(resp.data),
// "xxxxx",
// Object.values(resp.data),
// "xxxxx",
// Object.keys(resp.data.response),
// "xxxxx",
// Object.values(resp.data.response),
JSON.stringify(resp)
);
var folderSet = resp.data.response;
if (Object.keys(folderSet).length == 0) {
console.log("No folders returned!");
} else {
console.log("Folders under your root folder:");
Object.keys(folderSet).forEach(function (id) {
console.log("\t%s (%s)", folderSet[id], id);
});
}
}
}
);
}
authorizePromise.ts
const fs = require("fs");
const readline = require("readline");
const { google } = require("googleapis");
// If modifying these scopes, delete token.json.
const SCOPES = ["https://www.googleapis.com/auth/drive"];
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
const TOKEN_PATH = "token.json";
/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
* #param {Object} credentials The authorization client credentials.
* #param {function} callback The callback to call with the authorized client.
*/
export async function authorizePromise() {
const credentials = JSON.parse(
fs.readFileSync("credentials.json").toString()
);
return new Promise((resolve) => {
resolve(authorize(credentials, resolve));
});
}
async function authorize(credentials, callback) {
console.log("authorize", credentials);
const { client_secret, client_id, redirect_uris } = credentials.installed;
console.log("authorize 3", client_secret, client_id, redirect_uris);
const oAuth2Client = new google.auth.OAuth2(
client_id,
client_secret,
redirect_uris[0]
);
// Check if we have previously stored a token.
let token;
try {
token = JSON.parse(fs.readFileSync(TOKEN_PATH).toString());
} catch {
token = await getAccessTokenPromise(oAuth2Client);
}
console.log("token", token);
oAuth2Client.setCredentials(token);
console.log("authorize 4");
callback(oAuth2Client);
}
function getAccessTokenPromise(oAuth2Client) {
return new Promise((resolve) => {
getAccessToken(oAuth2Client, resolve);
});
}
/**
* Get and store new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
* #param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
* #param {getEventsCallback} callback The callback for the authorized client.
*/
function getAccessToken(oAuth2Client, callback) {
const authUrl = oAuth2Client.generateAuthUrl({
access_type: "offline",
scope: SCOPES,
});
console.log("Authorize this app by visiting this url:", authUrl);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.question("Enter the code from that page here: ", (code) => {
rl.close();
oAuth2Client.getToken(code, (err, token) => {
if (err) return console.error("Error retrieving access token", err);
console.log("token", token);
oAuth2Client.setCredentials(token);
console.log("Going here");
console.log("g", JSON.stringify(token));
// Store the token to disk for later program executions
fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
console.log("Err?", token, err);
if (err) return console.error(err);
console.log("Token stored to", TOKEN_PATH);
});
callback(oAuth2Client);
});
});
}
ContentService creates a TextOutput object, which is not supported as a return type by the api. Use primitive return types like string or number:
return "Hello";
That was it - return "hello", so simple!
I'm trying to implement Google Fit, in a school project.
I am using the documentation released by Google but it does not work.
I am getting 403 bad request error
Is it possible because I am using XAMPP to try to connect, it gives me an error?
I have entered the request domains on the Google project.
Can you help me?
Also I have a question:
Does it cost to use Google Fit Api rest?
Thanks everyone for your answers
var CLIENT_SECRET;
var CLIENT_ID;
$.post('healthDataFunc.php', { functionname: 'get_app_credentials' }, function(data){
var result = JSON.parse(data);
if (result){
CLIENT_SECRET = result[0];
CLIENT_ID = result[1];
}
});
var CLIENT_REDIRECT = "https://localdefault.com:4433";
//End-Configuration
var SCOPES_FITNESS = 'https://www.googleapis.com/auth/fitness.activity.read+https://www.googleapis.com/auth/fitness.body.read+https://www.googleapis.com/auth/fitness.location.read+https://www.googleapis.com/auth/fitness.blood_pressure.read+https://www.googleapis.com/auth/fitness.sleep.read';
var GoogleAuth;
/*
Initial request for Google authentication code
Opens google auth window
returns Google Auth token
*/
function requestGoogleoAuthCode() {
// Load the API's client and auth2 modules.
// Call the initClient function after the modules load.
gapi.load('client:auth2', initClient);
console.log(gapi);
}
function initClient() {
// In practice, your app can retrieve one or more discovery documents.
var discoveryUrl = "https://www.googleapis.com/discovery/v1/apis/drive/v3/rest";
// Initialize the gapi.client object, which app uses to make API requests.
// Get API key and client ID from API Console.
// 'scope' field specifies space-delimited list of access scopes.
gapi.client.init({
'apiKey': CLIENT_SECRET,
'clientId': CLIENT_ID,
'discoveryDocs': [discoveryUrl],
'scope': SCOPES_FITNESS
}).then(function () {
GoogleAuth = gapi.auth2.getAuthInstance();
// Listen for sign-in state changes.
GoogleAuth.isSignedIn.listen(updateSigninStatus);
// Handle initial sign-in state. (Determine if user is already signed in.)
var user = GoogleAuth.currentUser.get();
GoogleAuth.signIn();
console.log("test--------->", GoogleAuth, user);
});
}
/*
Uses Google Auth code to get Access Token and Refresh Token
returns object with access token, refresh token and access token expiration
*/
function getAccessToken(google_auth_code) {
var retVal = null;
jQuery.ajax({
url: "https://www.googleapis.com/oauth2/v3/token?code=" + google_auth_code + "&redirect_uri=" + CLIENT_REDIRECT + "&client_id=" + CLIENT_ID + "&client_secret=" + CLIENT_SECRET + "&scope=&grant_type=authorization_code",
type: "post",
success: function (result) {
console.log("Got Access Token And Refresh Token");
retVal = result;
console.log(result);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("Error during getAccessToken");
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
retVal = null;
},
async: false
});
return retVal;
}
/*
Uses Refresh token to obtain new access token
returns new access token with expiration
*/
function refreshAccessToken(refresh_token) {
var retVal = null;
jQuery.ajax({
url: "https://www.googleapis.com/oauth2/v3/token?client_secret=" + CLIENT_SECRET + "&grant_type=refresh_token&refresh_token=" + refresh_token + "&client_id=" + CLIENT_ID,
type: "post",
success: function (result) {
console.log("Refreshed Access Token");
retVal = result;
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("Error during refreshAccessToken");
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
retVal = null;
},
async: false
});
return retVal;
}
function revokeAccess(accessToken) {
GoogleAuth.disconnect();
}
var isAuthorized;
var currentApiRequest;
/**
* Store the request details. Then check to determine whether the user
* has authorized the application.
* - If the user has granted access, make the API request.
* - If the user has not granted access, initiate the sign-in flow.
*/
function sendAuthorizedApiRequest(requestDetails) {
currentApiRequest = requestDetails;
if (isAuthorized) {
// Make API request
// gapi.client.request(requestDetails)
// Reset currentApiRequest variable.
currentApiRequest = {};
} else {
GoogleAuth.signIn();
}
}
/**
* Listener called when user completes auth flow. If the currentApiRequest
* variable is set, then the user was prompted to authorize the application
* before the request executed. In that case, proceed with that API request.
*/
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
isAuthorized = true;
if (currentApiRequest) {
sendAuthorizedApiRequest(currentApiRequest);
}
} else {
isAuthorized = false;
}
}
I'm trying to write a client-side JS script that will fetch images from my gDrive to display on a website using a service account. I created the service account and added and enabled the google Drive API for the project. But when I run the script, I'm getting a 403 error: Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup. I think it has to do with permissions or scopes maybe? I've looked at several other stack overflows and can't seem to figure it out.
Getting a 403 - Forbidden for Google Service Account
Google Drive service account returns 403 usageLimits
Some of them mention adding roles or scopes, but I can't figure out how to add them or which ones I need to add. Is a GSuite account mandatory? It sounds like I would need to go into the GSuite admin console to add the scopes? I would like to not have to sign up for an account, as it's not free. Any help would be appreciated. My code looks like the following:
function gDrive() {
function init(callback) {
authorizeClient(getJWT()).then(function(token) {
loadClient(token, callback);
});
}
/* Retrieve a signed JWT */
function getJWT() {
// Prepare header, payload, and key
let oHeader = {
"alg": "RS256",
"typ": "JWT"
};
let sHeader = JSON.stringify(oHeader);
let oPayload = {
"iss": "SERVICE ACCOUNT EMAIL",
"sub": "SERVICE ACCOUNT EMAIL",
"aud": "https://www.googleapis.com/oauth2/v3/token",
"iat": KJUR.jws.IntDate.getNow(),
"exp": KJUR.jws.IntDate.get("now + 1hour"),
"scope": "https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/drive.appdata https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/drive.metadata https://www.googleapis.com/auth/drive.metadata.readonly https://www.googleapis.com/auth/drive.photos.readonly https://www.googleapis.com/auth/drive.readonly"
};
let sPayload = JSON.stringify(oPayload);
let privKey = "-----BEGIN PRIVATE KEY-----BLAH BLAH BLAH\n-----END PRIVATE KEY-----\n";
// Sign JWT
return signedJWS = KJUR.jws.JWS.sign(null, sHeader, sPayload, privKey);
}
/* Http POST to Google Auth api */
function authorizeClient(JWS) {
// Request access token
const url = "https://www.googleapis.com/oauth2/v3/token";
let encodedData = "";
let encodedDataPairs = [];
encodedDataPairs.push(encodeURIComponent("grant_type") + '=' + encodeURIComponent("urn:ietf:params:oauth:grant-type:jwt-bearer"));
encodedDataPairs.push(encodeURIComponent("assertion") + '=' + encodeURIComponent(JWS));
encodedData = encodedDataPairs.join('&').replace(/%20/g, '+');
const params = {
headers: {"content-type":"application/x-www-form-urlencoded"},
body: encodedData,
method: "POST"
};
return fetch(url, params).then(accessTokenSucces).then(returnToken).catch(accessTokenFailed);
}
function accessTokenSucces(data) {
console.log("Retrieved access token");
return data.json();
}
function returnToken(resp) {
return resp.access_token;
}
function accessTokenFailed(error) {
console.log("Requesting access token failed: " + error);
}
function loadClient(accessToken, callback) {
gapi.load('client', function() {
console.log("loading client");
gapi.client.setToken(accessToken);
console.log("set access token");
return gapi.client.load("https://content.googleapis.com/discovery/v1/apis/drive/v3/rest").then(clientLoadSuccessful).then(callback).catch(clientLoadFailed);
})
}
function clientLoadSuccessful() {
console.log("Client loaded");
return Promise.resolve();
}
function clientLoadFailed(error) {
console.log("Loading Client failed: " + error);
return Promise.reject();
}
function fetchAllImages(fileName, chapter, callback) {
console.log("fetching images");
let initialRequest = gapi.client.drive.files.list({"q": "mimeType contains \"image\" and name contains '"
+ fileName + "_ch" + chapter + "'"});
retrievePageOfFiles(initialRequest, [], fileName, chapter);
function retrievePageOfFiles(request, result) {
request.execute(function(resp) {
result = result.concat(resp.files);
let nextPageToken = resp.nextPageToken;
if (nextPageToken) {
request = gapi.client.drive.files.list({
"pageToken": nextPageToken,
"q": "mimeType contains \"image\" and name contains '" + fileName + "_ch" + chapter + "'"
});
retrievePageOfFiles(request, result);
} else {
console.log("Images retrieved");
callback(result);
}
}).catch(function(err) {
console.log("Could not retrieve images: " + err);
});
}
}
return {
init: init,
fetchAllImages: fetchAllImages
};
}
gDrive().init(runApp);
function runApp() {
console.log("Running App");
gDrive().fetchAllImages("FILENAME", "1", imageCallback);
}
function imageCallback(data) {
console.log("Images Retrieved!");
console.log(data);
}
When your script is run, the error of Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup. occurs.
You want to remove this error.
If my understanding is correct, how about this modification? I think that the access token retrieved with your script can be used. So please modify your script as follows.
From:
gapi.client.setToken(accessToken);
To:
gapi.client.setToken({access_token: accessToken});
Reference:
gapi.client.setToken(tokenObject)
If this was not the direct solution of your issue, I apologize.
I'm trying to figure out how to use Google's API service, and I have a client and API key for Google OAuth. Specifically, though I want to check a user's organization, and then echo out some info for them. I understand that that info will be visible with a simple CTRL-SHIFT-I or CTRL-U, but that doesn't matter to me right now. Thanks for your help in advance (JavaScript because I want to try to host this on GitHub pages)!
Here's a Google example I've tried, and I just get error 400's (client and API keys have been deleted).
// Enter an API key from the Google API Console:
// https://console.developers.google.com/apis/credentials
var apiKey = 'AIzaSyDyyNLwHpVqy88tRamPt1NbyVWFzYkLuhA';
// Enter the API Discovery Docs that describes the APIs you want to
// access. In this example, we are accessing the People API, so we load
// Discovery Doc found here: https://developers.google.com/people/api/rest/
var discoveryDocs = ["https://people.googleapis.com/$discovery/rest?version=v1"];
// Enter a client ID for a web application from the Google API Console:
// https://console.developers.google.com/apis/credentials?project=_
// In your API Console project, add a JavaScript origin that corresponds
// to the domain where you will be running the script .apps.googleusercontent.com.
var clientId = '873243932753-jfebiqi1ja0b9a2jiqdiirb8vtjlk4n9.apps.googleusercontent.com.apps.googleusercontent.com';
// Enter one or more authorization scopes. Refer to the documentation for
// the API or https://developers.google.com/people/v1/how-tos/authorizing
// for details.
var scopes = 'profile';
var authorizeButton = document.getElementById('authorize-button');
var signoutButton = document.getElementById('signout-button');
function handleClientLoad() {
// Load the API client and auth2 library
gapi.load('client:auth2', initClient);
}
function initClient() {
gapi.client.init({
apiKey: apiKey,
discoveryDocs: discoveryDocs,
clientId: clientId,
scope: scopes
}).then(function() {
// Listen for sign-in state changes.
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle the initial sign-in state.
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
authorizeButton.onclick = handleAuthClick;
signoutButton.onclick = handleSignoutClick;
});
}
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
makeApiCall();
} else {
authorizeButton.style.display = 'block';
signoutButton.style.display = 'none';
}
}
function handleAuthClick(event) {
gapi.auth2.getAuthInstance().signIn();
}
function handleSignoutClick(event) {
gapi.auth2.getAuthInstance().signOut();
}
// Load the API and make an API call. Display the results on the screen.
function makeApiCall() {
gapi.client.people.people.get({
'resourceName': 'people/me',
'requestMask.includeField': 'person.names'
}).then(function(resp) {
var p = document.createElement('p');
var name = resp.result.names[0].givenName;
p.appendChild(document.createTextNode('Hello, ' + name + '!'));
document.getElementById('content').appendChild(p);
});
}
<p>Say hello using the People API.</p>
<!--Add buttons to initiate auth sequence and sign out-->
<button id="authorize-button">Authorize</button>
<button id="signout-button">Sign Out</button>
<div id="content"></div>
<script async defer src="https://apis.google.com/js/api.js" onload="this.onload=function(){};handleClientLoad()" onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>
Edit: I found out that this needs to be done with Admin SDK. Still a bit confused on how to do this though.
As you mentioned this needs to be done using the Admin sdk API. under the users > get section you can try that API and it will provide you an example about how to use it on JS.
function authenticate() {
return gapi.auth2.getAuthInstance()
.signIn({scope: "https://www.googleapis.com/auth/admin.directory.user https://www.googleapis.com/auth/admin.directory.user.readonly"})
.then(function() { console.log("Sign-in successful"); },
function(err) { console.error("Error signing in", err); });
}
function loadClient() {
gapi.client.setApiKey("YOUR_API_KEY");
return gapi.client.load("https://content.googleapis.com/discovery/v1/apis/admin/directory_v1/rest")
.then(function() { console.log("GAPI client loaded for API"); },
function(err) { console.error("Error loading GAPI client for API", err); });
}
// Make sure the client is loaded and sign-in is complete before calling this method.
function execute() {
return gapi.client.directory.users.get({
"userKey": "<user email address>"
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error", err); });
}
gapi.load("client:auth2", function() {
gapi.auth2.init({client_id: "YOUR_CLIENT_ID"});
});`
Also I recommend you to to use the Quickstart to get more familiar about how to use the Google API's.
I've written some client-side app and tried to test it. How it turned out only I can use it. Anyone else will get such error.
{
"error": {
"errors": [
{
"domain": "global",
"reason": "forbidden",
"message": "Forbidden"
}
],
"code": 403,
"message": "Forbidden"
}
}
What does it mean? How to solve this?
There is my code. There i'm getting Email, name, surname and user photo. I want to get the number of youtube channel subscribers and work with youtube later. For example I want to rate some videos directly from the site.
function resultFindUserByEmail()
{
if (ajaxRet['isUserFinded'])
{
cf_JSON.clear();
cf_JSON.addItem( 'email',email );
var jsonstr = cf_JSON.make();
ajax_post('doyoutubelogin','loginres','index.php',jsonstr,c_dologin);
}else{
gapi.client.init({
discoveryDocs: ["https://www.googleapis.com/discovery/v1/apis/people/v1/rest"],
clientId: OAUTH2_CLIENT_ID,
scope: OAUTH2_SCOPES
}).then(function () {
var request = gapi.client.people.people.get({
'resourceName': 'people/me'
}).then(function(response) {
var parsedResponse = JSON.parse(response.body).names;
surname = parsedResponse[0].familyName;
name = parsedResponse[0].givenName;
photo = JSON.parse(response.body).photos[0].url;
addYoutubeUser();
});
});
}
}
function addYoutubeUser() {
cf_JSON.clear();
cf_JSON.addItem( 'Email',email );
cf_JSON.addItem( 'Firstname',name );
cf_JSON.addItem( 'Lastname',surname );
cf_JSON.addItem( 'Image',photo );
var jsonstr = cf_JSON.make();
ajax_post('addyoutubeuser','loginres','index.php',jsonstr,c_dologin);
}
var API_KEY = '<Key removed for posting>';
var API_KEY1='<Key removed for posting>';
var OAUTH2_CLIENT_ID = '<Key removed for posting>';
var OAUTH2_CLIENT_ID1 = '<Key removed for posting>';
var OAUTH2_SCOPES = 'https://www.googleapis.com/auth/youtube.force-ssl';
var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest"];
var GoogleAuth;
function handleClientLoad() {
// Load the API's client and auth2 modules.
// Call the initClient function after the modules load.
gapi.load('client:auth2', initClient);
}
function initClient() {
// Retrieve the discovery document for version 3 of YouTube Data API.
// In practice, your app can retrieve one or more discovery documents.
var discoveryUrl = 'https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest';
// Initialize the gapi.client object, which app uses to make API requests.
// Get API key and client ID from API Console.
// 'scope' field specifies space-delimited list of access scopes.
gapi.client.init({
'apiKey': API_KEY,
'discoveryDocs': [discoveryUrl,"https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest"],
'clientId': OAUTH2_CLIENT_ID,
'scope': OAUTH2_SCOPES
}).then(function () {
GoogleAuth = gapi.auth2.getAuthInstance();
//GoogleAuth.grant(OAUTH2_SCOPES);
// Listen for sign-in state changes.
GoogleAuth.isSignedIn.listen(updateSigninStatus);
// Handle initial sign-in state. (Determine if user is already signed in.)
var user = GoogleAuth.currentUser.get();
setSigninStatus();
// Call handleAuthClick function when user clicks on
// "Sign In/Authorize" button.
$('#sign-in-or-out-button').click(function() {
handleAuthClick();
});
$('#revoke-access-button').click(function() {
revokeAccess();
});
});
}
function handleAuthClick() {
if (GoogleAuth.isSignedIn.get()) {
// User is authorized and has clicked 'Sign out' button.
GoogleAuth.signOut();
} else {
// User is not signed in. Start Google auth flow.
GoogleAuth.signIn();
}
}
function revokeAccess() {
GoogleAuth.disconnect();
}
function setSigninStatus(isSignedIn) {
var user = GoogleAuth.currentUser.get();
var isAuthorized = user.hasGrantedScopes(OAUTH2_SCOPES);
if (isAuthorized) {
$('#sign-in-or-out-button').html('Sign out');
$('#revoke-access-button').css('display', 'inline-block');
$('#auth-status').html('You are currently signed in and have granted ' +
'access to this app.');
//// get gmail Email
gapi.client.init({
'apiKey': API_KEY,
'discoveryDocs': ["https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest"],
'clientId': OAUTH2_CLIENT_ID,
'scope': OAUTH2_SCOPES
}).then(function () {
var request = gapi.client.gmail.users.getProfile({
'userId': 'me'
}).then(function(response) {
email = JSON.parse(response.body).emailAddress;
cf_JSON.clear();
cf_JSON.addItem( 'email',email );
var jsonstr = cf_JSON.make();
tryFindUserByEmail(jsonstr);
});
});
// try to find email
} else {
$('#sign-in-or-out-button').html('Вход через Youtube');
$('#revoke-access-button').css('display', 'none');
$('#auth-status').html('You have not authorized this app or you are ' +
'signed out.');
}
}
function updateSigninStatus(isSignedIn) {
setSigninStatus();
}
How to manage permissions:
When you authenticate a user you are given access to that users account data and only that user. So if you are trying to access data on someone else's account they are not going to have permissions to access it and you are going to get the 403 forbidden error.
Without seeing your code its hard to know what you are doing, but I can guess.
You are using Oauth2 to authenticate users.
You are trying to access something with a hard coded id belonging to your personal account which the user does not have access.
How to fix it will depend on what it is you are trying to do.
You need to check some authentication in the API url like
username , ipaddress , token etc.
Based on the parameter you can control the permission on your API request.for example
http://some/thing?username="testuser"&ipaddress="323.2323.232.32"
You can find the parameters value using the function below
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
And then make you check and implement your error and redirection for specific users.
I guess it will help full for you , Thanks !