How to manage User docs permission setting using Google Drive Api? (Javascript) - javascript

I am new to Google Drive SDK.
I followed
https://developers.google.com/drive/v2/reference/permissions/insert?hl=en
this examples where they show how to change permissions for file. I'm able run this code but my problem is that i want to change permission of more than one file.i tried some loop for user and inside it fileId loop but because javascript not wait for child function complete(asynchronous calling function), it wont work for me
Please Help me
Following is my Code...
i get very confused in it please help me to sort out this
This the Code Please Correct me here Please
var scopes = 'https://www.googleapis.com/auth/drive';
// Use a button to handle authentication the first time.
function handleClientLoad() {
gapi.client.setApiKey(apiKey);
//window.setTimeout(checkAuth,1);
checkAuth();
}
function checkAuth() {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthResult);
}
function handleAuthResult(authResult) {
var authorizeButton = document.getElementById('authorize-button');
if (authResult && !authResult.error) {
authorizeButton.style.visibility = 'hidden';
makeApiCall();
} else {
authorizeButton.style.visibility = '';
authorizeButton.onclick = handleAuthClick;
}
}
function handleAuthClick(event) {
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
return false;
}
// Load the API and make an API call. Display the results on the screen.
function makeApiCall() {
var fileID = new Array();
var email = new Array();
fileID[0] = "1fEYDfB9owJAdxQ7lI0";
fileID[1] = "1YYcKn1ZsiPYWA";
email[0] = "email1#email.com";
email[1] = "email2#email.com";
email[2] = "email3#email.com";
gapi.client.load('drive', 'v2', function() {
for(var i=0;i<email.length;i++)
{
var body = {
'value': email[i],
'type': "user",
'role': "reader"
};
for(var j=0;j<fileID.length;j++)
{
var fileid = fileID[j];
excuteRequest(body, fileid, function() {
var request = gapi.client.drive.permissions.insert({
'fileId': fileid,
'resource': body
});
request.execute(function(resp) { });
});
}
}
});
}
function excuteRequest(param1, param2, callback) {
if (callback && typeof(callback) === "function") {
callback();
}
}

Use a flow control library, similar to async: https://github.com/caolan/async
var files = ["id1", "id2", "id3"];
async.each(files, function(fileId, callback){
gapi.client.drive.permissions.insert({
'fileId': fileId,
'resource': body
}).execute(function(response) {
callback(null, response);
});
}, function(err){
if (!err) { console.log('done.'); }
});

Related

Client-side authentication using AngularJS

I have created login page and trying to do client-side authentication. I know it's a bad practice, but I want to learn it. I am accessing the data using JSON server. When I submit the button , my data is getting posted in the server, but I am failing when I am trying to match the content on success call. Please let me know what I am doing wrong.
Any help / advice would be greatly appreciated.
AngularJS :
app.factory('Authentication', function($http, $q, session) {
var service = {};
service.isAuthenticated = function() {
return isAuthenticated = false,
username = ""
};
service.login = function(username, password) {
return $q(function(resolve, reject) {
$http.post('http://localhost:3000/loginfo', {
username,
password
})
.then(
function successCallback(response) {
var data = response.data;
var user = {};
for (var i = 0; i < data; i++) {
alert('go');
if (data[i].username === username && data[i].password === password) {
user = data[i];
break;
}
}
session.create(response.data.id, response.data.username);
resolve(response.data);
console.log(response.data)
},
function(err) {
reject(err);
});
});
};
return service;
});
/* client-side */
app.controller('credientials', function($scope, $http, auth) {
$scope.userCred = {
username: '',
password: ''
};
/*-----Form Submition-----*/
$scope.log = function(userCred) {
$scope.isAuthenticated = true;
Authentication.login(userCred.username, userCred.password)
.then(function(result) {
console.log(result);
}, function(err) {
console.error(err);
});
};
}]);

authClient.request is not a function

I am trying to create events using the google calendar api however, I am having trouble with the authorization. I created a google login, a different way so I am not sure the best way to go about connecting to the google calendar, this is my hwapi file:
var Homework = require('../models/homework');
var mongoose = require('mongoose');
var google = require('googleapis');
var jwt = require('jsonwebtoken');
var secret = 'check123';
var googleAuth = require('google-auth-library');
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
var googleAuth = require('google-auth-library');
// function authorize(credentials, callback) {
// var clientSecret = credentials.installed.client_secret;
// var clientId = credentials.installed.client_id;
// var redirectUrl = credentials.installed.redirect_uris[0];
// var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
// // Check if we have previously stored a token.
// fs.readFile(TOKEN_PATH, function(err, token) {
// if (err) {
// getNewToken(oauth2Client, callback);
// } else {
// oauth2Client.credentials = JSON.parse(token);
// callback(oauth2Client);
// }
// });
// }
//mongoose.connect('mongodb://localhost:27017/test');
var auth = new googleAuth();
var clientSecret = '4etHKG0Hhj84bKCBPr2YmaC-';
var clientId = '655984940226-dqfpncns14b1uih73i7fpmot9hd16m2l.apps.googleusercontent.com';
var redirectUrl = 'http://localhost:8000/auth/google/callback';
var auth = new googleAuth();
var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
//console.log(auth);
module.exports = function(hwRouter,passport){
hwRouter.post('/homeworks', function(req, res){
var homework = new Homework();
homework.summary = req.body.summary;
homework.description = req.body.description;
homework.startDate = req.body.startDate;
homework.endDate = req.body.endDate;
if(req.body.summary == null || req.body.summary == '' || req.body.description == null || req.body.description == '' || req.body.startDate == null || req.body.startDate == '' || req.body.endDate == null || req.body.endDate == ''){
res.send("Ensure all fields were provided!");
}
else{
homework.save(function(err){
if(err){
res.send('Homework already exists!');
}
else{
res.send('Homework created successfully!');
}
});
}
})
var calendar = google.calendar('v3');
hwRouter.get('/retrieveHW/:summary', function(req,res){
Homework.find({},function(err,hwData){
console.log(hwData);
var event = {
'summary': 'Google I/O 2015',
'location': '800 Howard St., San Francisco, CA 94103',
'description': 'A chance to hear more about Google\'s developer products.',
'start': {
'dateTime': '2015-05-28T09:00:00-07:00',
'timeZone': 'America/Los_Angeles',
},
'end': {
'dateTime': '2015-05-28T17:00:00-07:00',
'timeZone': 'America/Los_Angeles',
},
'recurrence': [
'RRULE:FREQ=DAILY;COUNT=2'
],
'attendees': [
{'email': 'lpage#example.com'},
{'email': 'sbrin#example.com'},
],
'reminders': {
'useDefault': false,
'overrides': [
{'method': 'email', 'minutes': 24 * 60},
{'method': 'popup', 'minutes': 10},
],
},
};
console.log(auth)
calendar.events.insert({
auth: auth,
calendarId: 'primary',
resource: event,
}, function(err, event) {
if (err) {
console.log('There was an error contacting the Calendar service: ' + err);
return;
}
console.log('Event created: %s', event.htmlLink);
});
res.json({success: true, message: "successfull retrieved the homework!"});
});
})
return hwRouter;
}
As you can see Ive tried using some of the code that the goog api has provided just to make sure I can connect to it. The part my code gets stuck is I believe when I pass it the auth: auth in the calendar.event.create portion. it gives me the error: authClient.request is not a function. any advice would help thanks!
Try following the JavaScript sample:
/**
* Initializes the API client library and sets up sign-in state
* listeners.
*/
function initClient() {
gapi.client.init({
discoveryDocs: DISCOVERY_DOCS,
clientId: CLIENT_ID,
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;
});
}
/**
* Called when the signed in status changes, to update the UI
* appropriately. After a sign-in, the API is called.
*/
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
listUpcomingEvents();
} else {
authorizeButton.style.display = 'block';
signoutButton.style.display = 'none';
}
}
In this code, after the initClient() runs, the gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus); listens for any state changes. updateSigninStatus function handles if initClient() successfully logged in or not. If yes, it call the listUpcomingEvents() function, in your case you will call the create event function.
Here is a related SO post that can help you with a JS client library code implementation.
Hope this helps.

Sharing client variable with Meteor.onCreateUser function on server

I would like to share a variable that is set in the client with the Meteor.onCreateUser function call on the server.
I have this code that sets some user properties before a user is created
Accounts.onCreateUser(function(options, user, err) {
if (options.profile) {
user.profile = options.profile;
// Images
var picturelrg = "http://graph.facebook.com/" + user.services.facebook.id + "/picture/?type=large";
var picturesm = "http://graph.facebook.com/" + user.services.facebook.id + "/picture/?type=small";
options.profile.picturelrg = picturelrg;
options.profile.picturesm = picturesm;
options.profile.upvotes = 0;
options.profile.neutralvotes = 0;
options.profile.downvotes = 0;
// ip = response.ip;
return user;
}
});
Here is the client code
if (Meteor.isClient) {
fbLogin = function() {
Meteor.loginWithFacebook({
requestPermissions: ['public_profile', 'email', 'user_location']
}, function(err) {
if (err)
// redirect to register if popup comes and user isn't on register
Session.set('errorMessage', err.reason || 'Unknown Eror');
console.log(Session.get('errorMessage'));
});
}
locate = function(){
function ipLocate(whenDone) {
var api = "http://ipinfo.io?callback=?";
$.getJSON(api, {
format: "jsonp"
})
.done(function(response) {
var result = ""
// show all the props returned
for (var prop in response) {
result += prop + ": " + response[prop] + "<br>";
}
var selectedResponse = {
city: response.city,
region: response.region,
country: response.country,
ip: response.ip,
latLng: response.loc
}
console.log(selectedResponse);
whenDone(selectedResponse);
return selectedResponse
});
}
// HACK: Async
function ipDone(selectedResponse) {
response = selectedResponse;
}
// Set response
ipLocate(ipDone);
return response
}
Template.ModalJoin.events({
'click .modJoinFB-Btn ': function() {
locate();
fbLogin();
}
});
}
On the client I have an event handler that sets some values when the user clicks the "Sign Up with Facebook" button. How can I send these values to the onCreateUser function to be accessed.
Ex: I want to store user geolocation info ( city, state) when the user registers but I don't know how this can be sent from the client to server.
I'm not sure how I would use Meteor.call() if I could
Looks like you should run a Meteor.call function inside fbLogin, passing that location data, if no error is returned. Something like this:
fbLogin = function() {
Meteor.loginWithFacebook({
requestPermissions: ['public_profile', 'email', 'user_location']
}, function(err) {
if (err) {
Session.set('errorMessage', err.reason || 'Unknown Eror');
console.log(Session.get('errorMessage'));
} else {
//if no error was returned, then Meteor.call the location
var userId = Meteor.userId(); //you should send that userId for the method.
Meteor.call('storeLocation', locationData, userId, function(err,res){
if (err) {
console.log(err);
}
});
}
});
}
And on server, you create a Method for updating that user profile data with the location. Maybe something like this:
Meteor.methods({
'storeLocation': function(locationData, userId) {
var locationData = {
// based on what you have gathered on your client location function
'city': response.city,
'region': response.region,
'country': response.country,
'ip': response.ip,
'latLng': response.loc
}
Meteor.users.update(
//I suggest placing it inside profile, but do as it is better to you
{'_id': userId},
{$addToSet: {'profile.locations': locationData }}
);
}
});
Not sure if you will store like that, but this is how I have done for myself. Let me know if any problems or doubts, we can try to solve it together.

Google Drive API JavaScript having trouble getting file properties

Hi I'm having trouble getting all images in the root folder in my Google Drive using the Google Drive API. I'm starting simple and getting some info from the first file I retrieve. When I get the ID I get 0By19fyuYeoHHN2M3LWRqRWNucWM, but I have tried other things such as title and thumbnailLink I get undefined. Only thing that seems to work is id and kind. I'm looking here for a list of properties of a file.
https://developers.google.com/drive/v2/reference/files
Not really sure what is wrong. My scope is 'https://www.googleapis.com/auth/drive'.
Thanks in advanced.
Code
function retrieveAllFilesInFolder(folderId, callback)
{
var retrievePageOfChildren = function(request, result)
{
request.execute(function(resp)
{
result = result.concat(resp.items);
var nextPageToken = resp.nextPageToken;
if (nextPageToken)
{
request = gapi.client.drive.children.list(
{
'folderId' : folderId,
'pageToken': nextPageToken
});
retrievePageOfChildren(request, result);
}
else
{
callback(result);
}
});
}
var initialRequest = gapi.client.drive.children.list(
{
'folderId' : folderId
});
retrievePageOfChildren(initialRequest, []);
}
function printToOutdiv(result)
{
document.getElementById("outdiv").innerHTML = result[0].id;
}
function GetFilesButton ()
{
gapi.client.load('drive', 'v2', function()
{
retrieveAllFilesInFolder('root',printToOutdiv);
});
}
Edit : Updated code and it works but you can't specify folder.
function retrieveAllFiles(callback)
{
var retrievePageOfFiles = function (request, result)
{
request.execute(function (resp)
{
result = result.concat(resp.items);
var nextPageToken = resp.nextPageToken;
if (nextPageToken)
{
request = gapi.client.drive.files.list(
{
'pageToken': nextPageToken
});
retrievePageOfFiles(request, result);
}
else
{
callback(result);
}
});
}
var initialRequest = gapi.client.drive.files.list();
retrievePageOfFiles(initialRequest, []);
}

stripe.js: api call that calls stripe.charges.create isn't returning a response

I'm trying to use stripe.js and return the created charge after saving it on the server. The stripe charge saves successfully and is saved in my stripe test account, but it seems like the callback isn't working. From my code below, the console.log('success') gets called, but the "then" callback isn't called, and the console.log('savedChanges') doesn't get called either. Am I doing something wrong? I was following https://stripe.com/docs/tutorials/charges for reference.
/app/scripts/controllers/stripe.js
'use strict';
app.controller('StripeCtrl', function ($scope, $location, $http) {
$scope.charge = {};
$scope.successfulCharge = null;
$scope.submitCharge = function(status, response){
var $form = $('#payment-form');
if (response.error) {
$form.find('.payment-errors').text(response.error.message);
$form.find('button').prop('disabled', false);
} else {
var token = response.id;
var data = {
amount: ($scope.charge.amount * 100),
card: token,
description: "2014 missions donation for " + $scope.charge.missionary,
metadata: {
'email': $scope.charge.email,
'missionary': $scope.charge.missionary
}
};
$http.post('/api/stripe/submitCharge', data).success(function(data, status, headers) {
console.log('submitCharge success!!!');
console.log(data);
$scope.successfulCharge = data;
});
}
}
$scope.getCharges = function(){
$http.get('/api/charges').success(function(charges) {
return charges;
});
}
});
/lib/controllers/api.js
'use strict';
var mongoose = require('mongoose'),
config = require('../config/config'),
stripe = require('stripe')(config.stripe.secret_key),
Charge = mongoose.model('Charge');
exports.charges = function(req, res) {
return Charge.find(function (err, charges) {
if (!err) {
return res.json(charges);
} else {
return res.send(err);
}
});
};
exports.publishable_key = function(req, res){
return res.send(config.stripe.publishable_key);
};
exports.submitCharge = function(req, res){
var savedCharge;
var result = stripe.charges.create({
amount: req.body.amount,
currency: "usd",
card: req.body.card,
description: req.body.description
}, function(err, charge) {
if (err) {
console.log('errors');
console.log(err);
} else {
console.log('success');
}
}).then(function(charge){
savedCharge = Charge.create({
name: charge.card.name,
amount: charge.amount,
email: charge.metadata.email,
address: charge.card.address_line1 + charge.card.address_line1,
city: charge.card.address_city,
state: charge.card.address_city,
zip: charge.card.address_zip,
tax_receipt: charge.metadata.tax_receipt,
missionary: charge.metadata.missionary,
});
});
console.log('savedCharge');
console.log(savedCharge);
return res.send(savedCharge);
};
It looks like the Stripe API gives you the ability to use a callback or a promise, but you're using both in your call to charges.create:
var result = stripe.charges.create({
...data...
}, function (err, charge) { // <-- callback
...
}).then(function(charge) { // <-- promise
...
})
You need to choose one or the other. That is, either put the call to Charge.create inside the callback from stripe.charges.create (where your console.log('success') is) or move your error handling to the promise by providing a second argument to the then() statement: a function with an err parameter.

Categories