Using Google Sheets API with Node - node.js

I am trying to load one of my google sheets with node. I am able to get my access tokens from google but when I try and load the sheet I get the error:
Error: No access to that spreadsheet, check your auth.spreadsheet
Here is my app.js file:
var express = require('express')
var app = express()
CLIENT_ID = "MY_CLIENT_ID";
CLIENT_SECRET = "MY_SECRET";
REDIRECT_URL = "http://127.0.0.1:3000/oauth/callback";
var oauth2Client = new OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);
var google = require('googleapis');
var GoogleSpreadsheets = require('google-spreadsheets');
var oauth2Client = new google.auth.OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);
var url = oauth2Client.generateAuthUrl({
access_type: 'online',
scope: 'https://www.googleapis.com/auth/drive'
});
app.get('/', function (req, res) {
res.redirect(url);
res.send('Hello World');
});
app.get('/oauth/callback', function (req, res) {
var code = req.param('code');
GoogleSpreadsheets({
key: 'MY_SHEET_KEY',
auth: oauth2Client.getToken(code, function(err, tokens) {
// Now tokens contains an access_token and an optional refresh_token. Save them.
if(!err) {
oauth2Client.setCredentials(tokens);
}
console.log(tokens); //this prints my tokens as an array
})
}, function(err, spreadsheet) {
console.log(err + "spreadsheet");
});
res.send('Hello World');
});
app.listen(3000)

Related

Functions in Nodejs

I am new to Nodejs and am trying to figure out why I cannot pass the returned value of my function into my function when I call it. Here is my code:
const SpotifyWebApi = require('spotify-web-api-node');
const http = require("http");
const request = require('request');
const querystring = require('querystring');
const { post } = require('request');
const express = require('express');
const { response } = require('express');
const https = require('follow-redirects').https;
//sets express server vars
const app = express()
const port = 8080
app.get('/', (req, res) => {
res.send('Server Connected')
})
app.listen(port, () => {
console.log(`Now serving on ${port} at ${process.env.URI} `)
})
require('dotenv').config();
//authenticate to SpotifyAPI
var spotifyApi = new SpotifyWebApi({
clientId: process.env.CLIENT_ID,
clientSecret: process.env.SECRET_ID,
redirectUri: process.env.URI,
});
const scope = 'user-read-private user-read-email ';
const authUrl = 'https://accounts.spotify.com/api/token?grant_type=client_credentials';
//Headers needed to auth to SpotifyAPI for Bearer token
const tokenHeaders = {
'Authorization': process.env.ACCESSTOKEN,
'Content-Type': 'application/x-www-form-urlencoded',
};
//spotify Auth Payload
const options = {
'method': 'POST',
'url': authUrl,
'headers': tokenHeaders
};
function accessTokenAuth(bearerToken){
request(options, (error, response) => {
if (error) throw new Error(error);
const accessTokenBody = response.body;
// console.log(accessTokenBody)
// console.log(request)
const obj = JSON.parse(accessTokenBody);
const bearerToken = ("Bearer " + obj.access_token); //add this bearerAuth part to a function to make it repeatable. Times out in 3600???
// console.log(bearerToken);
return bearerToken;
});
}
//Add first playlists request using the bearer token
accessTokenAuth(bearerToken);
In the function "accessTokenAuth" I create a series of calls that essentially posts data from the above dictionaries into a function that then sends the data to the URL to receive a token back. My question is this, at the bottom of the function when I return "bearerToken", how come I cannot pass "bearerToken" into the function when I call it on line 67. Also, when I comment out calling the function and just run the program it prints out the "bearerToken" when I console.log it in the function. Why is this possible? Aren't you not able to access the function unless it is called?
Thank you!

Digest auth using http-auth

Trying to implement Digest auth in nodejs. Below is the code
var http = require('http');
var auth = require('http-auth');
var express = require('express');
var app = express();
var user;
var basic = auth.basic({
realm: 'Sample',
file: __dirname + "/users.htpasswd",
algorithm:'md5'
});
basic.on('success', (result, req) => {
console.log(`User authenticated: ${result.user}`);
user = result.user;
});
basic.on('fail', (result, req) => {
console.log(`User authentication failed: ${result.user}`);
console.log(req.headers.authorization);
});
basic.on('error', (error, req) => {
console.log(`Authentication error: ${error.code + " - " + error.message}`);
});
http.createServer(app).listen(8000);
app.use(auth.connect(basic));
app.get('/', function(req, res) {
console.log(req.headers);
console.log(basic);
res.json('Hello from '+ user);
res.end();
});
app.post('/', function(req, res) {
console.log(req.headers);
console.log(basic);
res.json('Hello from '+ user);
res.end();
});
This is the content of users.htpasswd file:-
ankit:Sample:e4b2d19b03346a1c45ce86ad41b85c5e
Using postman to call the end point with username ankit, pwd ankit & realm Sample, everytime I am getting 401.
Please let me know where I am doing wrong.
Thanks
You're mixing basic auth and digest auth. Replace auth.basic with auth.digest and your code should work as-is.

Can't get Extended User Access Token from Facebook with OAuth2 NodeJS

I'd try to get Extended User Access Token from OAuth2 with Nodejs
Actually, the program send out a message (on Browser) with:
XMLHttpRequest cannot load https://www.facebook.com/dialog/oauth?redirect_uri=http%3A%2F%2Flocalhost%3…2Fcallback&scope=user_about_me%2Cpublish_actions&client_id=487932668044758. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
Using standard express generator, I modified a code in a index.js as below:
var express = require('express');
var request = require('request');
var OAuth2 = require('oauth').OAuth2;
var router = express.Router();
var oauth2 = new OAuth2("487932668044758",
"0793918b3ab637b2096787e10643980a",
"", "https://www.facebook.com/dialog/oauth",
"https://graph.facebook.com/oauth/access_token",
null);
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', {
// title: 'Express'
});
});
router.post('/userToken', function(req, res) {
if (!req.body) {
return
res.sendStatus(400)
}
var uid = req.body.uid;
var token = req.body.token;
validate_uid_token(uid, token, res);
console.log('req:', req.body);
console.log("uid: ", uid);
console.log('token: ', token);
// res.send("okie");
});
router.get("/callback", function(req, res) {
console.log('here..form callback');
res.header('Access-Control-Allow-Origin', 'http://localhost3000');
res.header('Access-Control-Allow-Origin', 'https://www.facebook.com/dialog/oauth');
res.header('Access-Control-Allow-Origin', 'https://graph.facebook.com/oauth/access_token');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
if (req.error_reason) {
res.send(req.error_reason);
}
if (req.query.code) {
var loginCode = req.query.code;
var redirect_uri = "/"; // Path_To_Be_Redirected_to_After_Verification
// For eg. "/facebook/callback"
oauth2.getOAuthAccessToken(loginCode, {
grant_type: 'authorization_code',
redirect_uri: redirect_uri
},
function(err, accessToken, refreshToken, params) {
if (err) {
console.error(err);
res.send(err);
return;
}
var access_token = accessToken;
console.log('access_token : ', access_token);
// var expires = params.expires;
// console.log('expires : ', expires);
req.session.access_token = access_token;
// req.session.expires = expires;
}
);
}
// res.send('okie');
});
function validate_uid_token(uid, token, res) {
var redirect_uri = "http://localhost:3000" + "/callback";
// For eg. "http://localhost:3000/facebook/callback"
var params = {
'redirect_uri': redirect_uri,
'scope': 'user_about_me,publish_actions'
};
res.redirect(oauth2.getAuthorizeUrl(params));
}
module.exports = router;
Click on a url in error message. Browser throws out ma JSON message as
{"statusCode":400,"data":"{\"error\":{\"message\":\"redirect_uri isn't an absolute URI. Check RFC 3986.\",\"type\":\"OAuthException\",\"code\":191}}"}
Could someone help me please...Thank to much..
I'd recommend to use Passport.js together with the passport-facebook strategy. This hides away most of the complexity involved.
See
http://passportjs.org/
https://github.com/jaredhanson/passport-facebook

express-jwt Not respecting unprotected paths

Information on the express-jwt module can be found here:
https://github.com/auth0/express-jwt
https://www.npmjs.com/package/express-jwt
In my main.js server file, I have the following:
import ExpressJwt from 'express-jwt';
// import other crap...
let token = ExpressJwt({
secret: 'whatever',
audience: 'whatever',
issuer: 'whatever'
});
app.all('/apiv1', token.unless({ path: ['apiv1/user/create', '/apiv1/auth/login']}));
app.use('/apiv1/user', user);
app.use('/apiv1/auth', auth);
Where user and auth are the middlewares that handle my routes. What I want to do is obvious; deny API access to all unauthenticated users, except when they attempt to create a new user via apiv1/user/create and/or login via apiv1/auth/login.
Any time I try to make a request to the aforementioned unprotected paths however, I get the error:
UnauthorizedError: No authorization token was found
It's still protecting the routes I specified to be unprotected! I also tried:
app.use('/apiv1/user', token.unless({ path: ['/apiv1/user/create'] }), user);
app.use('/apiv1/auth', token.unless({ path: ['/apiv1/auth/login'] }), auth);
But that didn't work. I also tried using regex for the unless paths, but that didn't work either.
I arrived at app.all('/apiv1', token...) via this answer, but that solution does not yield me the desired functionality.
Instead of using all:
app.all('/apiv1', token.unless({ path: ['apiv1/user/create', '/apiv1/auth/login']}));
Try using use and adding in the path route a slash / at the beginning:
app.use('/apiv1', token.unless({ path: ['/apiv1/user/create', '/apiv1/auth/login']}));
Here it is an example that is working:
app.js:
var express = require('express');
var app = express();
var expressJwt = require('express-jwt');
var jwt = require('jsonwebtoken');
var secret = 'secret';
app.use('/api', expressJwt({secret: secret}).unless({path: ['/api/token']}));
app.get('/api/token', function(req, res) {
var token = jwt.sign({foo: 'bar'}, secret);
res.send({token: token});
});
app.get('/api/protected', function(req, res) {
res.send('hello from /api/protected route.');
});
app.use(function(err, req, res, next) {
res.status(err.status || 500).send(err);
});
app.listen(4040, function() {
console.log('server up and running at 4040 port');
});
module.exports = app;
test.js:
var request = require('supertest');
var app = require('./app.js');
describe('Test API', function() {
var token = '';
before(function(done) {
request(app)
.get('/api/token')
.end(function(err, response) {
if (err) { return done(err); }
var result = JSON.parse(response.text);
token = result.token;
done();
});
});
it('should not be able to consume /api/protected since no token was sent', function(done) {
request(app)
.get('/api/protected')
.expect(401, done);
});
it('should be able to consume /api/protected since token was sent', function(done) {
request(app)
.get('/api/protected')
.set('Authorization', 'Bearer ' + token)
.expect(200, done);
});
});

Google+ Domains 403 Forbidden when listing circles

This is the source code that requests the permissions and try to list the circles,
What I want to make is to be able to list the circle's person, add/remove people from the circles but I get a forbidden error when I try to do it, and I get the access to those scopes.
var express, router, nconf, OAuth2, oauth2Client, scopes, google;
scopes = [
'https://www.googleapis.com/auth/plus.me',
'https://www.googleapis.com/auth/plus.circles.read',
'https://www.googleapis.com/auth/plus.circles.write'
];
google = require('googleapis')
nconf = require('nconf');
OAuth2 = google.auth.OAuth2;
express = require('express');
router = express.Router();
oauth2Client = new OAuth2(CLIENT_ID, SECRET_ID, REDIRECT_URL);
router.get('/', function(req, res) {
var url = oauth2Client.generateAuthUrl({
access_type: 'offline', // 'online' (default) or 'offline' (gets refresh_token)
scope: scopes // If you only need one scope you can pass it as string
});
res.redirect(url);
});
router.get('/auth', function(req, res) {
console.log("code >> " + req.query.code);
oauth2Client.getToken(req.query.code, function(err, tokens) {
if(!err) {
console.log("TOKENS >> " + JSON.stringify(tokens));
oauth2Client.setCredentials(tokens);
var plusDomains = google.plusDomains('v1');
plusDomains.circles.list({ userId: 'me', auth: oauth2Client }, function(err, circles) {
console.log('Result circles: ' + (err ? err.message : JSON.stringify(circles)));
});
}
res.send({tokens: tokens});
});
});
module.exports = router;

Resources