adding post to blogger nodejs - node.js

I have been trying to add post to blogger using api in nodejs. I get the success message but no title or content being added to the post. Just blank posts are being created. Here is my code:
var express = require('express');
var app = express();
var request = require('request');
var rp = require('request-promise');
const google = require ('googleapis');
const Youtube = require("youtube-api");
const blogger = google.google.blogger('v3')
, fs = require("fs")
, readJson = require("r-json")
, Lien = require("lien")
, Logger = require("bug-killer")
, opn = require("opn")
, prettyBytes = require("pretty-bytes")
;
// I downloaded the file from OAuth2 -> Download JSON
const CREDENTIALS = readJson('./bcreds.json');
// Init lien server
let server = new Lien({
host: "localhost"
, port: 6111
});
let oauth = Youtube.authenticate({
type: "oauth"
, client_id: CREDENTIALS.web.client_id
, client_secret: CREDENTIALS.web.client_secret
, redirect_url: CREDENTIALS.web.redirect_uris[0]
});
opn(oauth.generateAuthUrl({
access_type: "offline"
, scope: ["https://www.googleapis.com/auth/blogger"]
}));
// Handle oauth2 callback
server.addPage("/oauth2callback", lien => {
Logger.log("Trying to get the token using the following code: " + lien.query.code);
oauth.getToken(lien.query.code, (err, tokens) => {
if (err) {
lien.lien(err, 400);
return Logger.log(err);
}
Logger.log("Got the tokens.");
oauth.setCredentials(tokens);
lien.end("The post is being uploaded. Check out the logs in the terminal.");
// write below
blogger.posts.insert({
auth: oauth,
blogId: "blog id here",
resource: {
content: "postContent",
title: "postTitle",
},
}, function(err, success){
console.log(success);
});
// end
});
});
Please help in getting understand that where is the problem. The code runs correctly and it do add post but the post is just blank.

Related

how to set expiration of password in aws-cognito with node js

I am trying to do something like -
All user passwords should expire every 90 days.
Users should be forced to reset their expired passwords upon login to share with last password.
anybody have any idea, how to do it in aws-cognito with nodejs ?
thanks in advance.
Cognito does not have an option for password expiration, but you can add the custom user attribute "custom:passwordUpdateDate" where you are going to check when the password was updated and use AdminResetUserPassword. Amazon Cognito: Enforcing password expiration policy
you can use api of aws-cognito user:
aws cognito-idp admin-get-user --user-pool-id us-east-1poolID --username youUser name or email --profile default
const AWS = require('aws-sdk');
AWS.config.update({region:'us-east-1'});
var http = require('http')
const express = require('express');
const app = express();
/*Initializing CognitoIdentityServiceProvider from AWS SDK JS*/
var RecivedData = {}
// var server = http.createServer(function (req, res) { //create web server
// if (req.url == '/') { //check the URL of the current request
// }
// }
// )
const cognito = new AWS.CognitoIdentityServiceProvider({
apiVersion: "2016-04-18",
});
const USERPOOLID = "you-pool id here";
const Check = async (event, context) => {
const EMAIL = "your email or user name ";
const cognitoParams = {
UserPoolId: USERPOOLID,
Username: EMAIL
};
let response = await cognito.adminGetUser(cognitoParams).promise();
console.log(JSON.stringify(response, null, 2));
RecivedData = {...RecivedData,response}
console.log(RecivedData)
}
(async ()=>{Check();})();
app.get('/' , (req,res)=>{
// Server will send resonse
res.send(RecivedData);
})
// Server setup
app.listen(4000 , ()=>{
console.log("server running 4000");
});
you will response in response you will get like this
{
response: {
Username: 'something',
UserAttributes: [ [Object], [Object], [Object] ],
UserCreateDate: 2022-03-21T13:17:05.246Z,
UserLastModifiedDate: 2022-03-21T13:42:09.303Z,
Enabled: true,
UserStatus: 'CONFIRMED'
}
}
here you see UserLastModifiedDate using this you can set password expiry of the aws-cognito user.
hope this will help you

Error: No access, refresh token or API key is set. Google Youtube API V3

I am going to get my subscription list with the help of the YouTube api. I wrote this piece of code.
const { google } = require('googleapis');
const oauth2 = google.oauth2('v2');
const express = require('express')
const app = express()
const port = 3000
const oauth2Client = new google.auth.OAuth2(
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"xxxxxxxxxxxxxxxxxxxxxxx",
"http://localhost:3000/auth/google/callback"
);
google.options({
auth: oauth2Client
});
// generate a url that asks permissions for Blogger and Google Calendar scopes
const scopes = [
'https://www.googleapis.com/auth/youtube',
'https://www.googleapis.com/auth/youtube.channel-memberships.creator'
];
const url = oauth2Client.generateAuthUrl({
// 'online' (default) or 'offline' (gets refresh_token)
access_type: 'offline',
// If you only need one scope you can pass it as a string
scope: scopes
});
app.get('/',(req,res,next)=>{
res.send(url);
})
let tok = "";
app.get('/auth/google/callback',(req,res,next)=>{
res.send('Susses Authrations');
console.log("Code authrations : "+req.query.code);
const {tokens} = oauth2Client.getToken(req.query.code)
oauth2Client.setCredentials(tokens);
oauth2Client.on('tokens', (tokens) => {
if (tokens.refresh_token) {
// store the refresh_token in my database!
console.log("refresh_token : "+ tokens.refresh_token);
tok = tokens.access_token;
}
console.log("Assess Token : "+ tokens.access_token);
});
})
app.get('/youtube',(req,res,next)=>{
const youtube = google.youtube('v3',{
'access_token':oauth2Client.credentials.access_token,
'refresh_token':oauth2Client.credentials.refresh_token,
'api_key':oauth2Client.credentials.api_key
});
youtube.channels.list({
"part": [
"snippet,contentDetails,statistics"
],
"id": [
"UC_x5XG1OV2P6uZZ5FSM9Ttw"
]
}).then(e=>{
console.log(e.request)
})
})
app.listen(port,()=>{
console.log("Hello World")
});
But unfortunately I encounter an error (Error: No access, refresh token or API key is set.) Which apparently does not recognize my refresh token. I am a novice and thank you for guiding me. I also use the clinet id and clinet secret I also built a console inside Google and activated YouTube related libraries.

Post Request Firebase Cloud Functions Timing Out

I know that each HTTP function must end with end() or send(), so I'm thinking that might be related to my issue. I'm building a Shopify app that I want to host on Firebase. I've gotten it to authenticate and install, but when I try to capture the permanent access token via POST, Firebase times out. This same code works fine with ngrok. Entire route function below.
const dotenv = require('dotenv').config();
const functions = require('firebase-functions');
const express = require('express');
const app = express();
const crypto = require('crypto');
const cookie = require('cookie');
const nonce = require('nonce')();
const querystring = require('querystring');
const request = require('request-promise');
const apiKey = process.env.SHOPIFY_API_KEY;
const apiSecret = process.env.SHOPIFY_API_SECRET;
const scopes = 'read_products,read_customers';
const forwardingAddress = 'https://my-custom-app.firebaseapp.com/app';
app.get('/app/shopify/callback', (req, res) => {
const { shop, hmac, code, state } = req.query;
const stateCookie = cookie.parse(req.headers.cookie).__session;
if (state !== stateCookie) {
return res.status(403).send('Request origin cannot be verified');
}
if (shop && hmac && code) {
// DONE: Validate request is from Shopify
const map = Object.assign({}, req.query);
delete map['signature'];
delete map['hmac'];
const message = querystring.stringify(map);
const generatedHash = crypto
.createHmac('sha256', apiSecret)
.update(message)
.digest('hex');
if (generatedHash !== hmac) {
return res.status(400).send('HMAC validation failed');
}
// Collect permanent access token
const accessTokenRequestUrl = 'https://' + shop + '/admin/oauth/access_token';
const accessTokenPayload = {
client_id: apiKey,
client_secret: apiSecret,
code,
};
// Everything works up until here
request.post(accessTokenRequestUrl, { json: accessTokenPayload })
.then((accessTokenResponse) => {
const accessToken = accessTokenResponse.access_token;
// If below is uncommented, it will not show on browser, Firebase seems to timeout on the above request.post.
//res.status(200).send("Got an access token, let's do something with it");
// Use access token to make API call to 'shop' endpoint
const shopRequestUrl = 'https://' + shop + '/admin/shop.json';
const shopRequestHeaders = {
'X-Shopify-Access-Token': accessToken,
};
request.get(shopRequestUrl, { headers: shopRequestHeaders })
.then((shopResponse) => {
res.end(shopResponse);
})
.catch((error) => {
res.status(error.statusCode).send(error.error.error_description);
});
})
.catch((error) => {
res.status(error.statusCode).send(error.error.error_description);
});
} else {
res.status(400).send('Required parameters missing');
}
});
exports.shopifyValidate = functions.https.onRequest(app);
You're calling response.end() incorrectly:
request.get(shopRequestUrl, { headers: shopRequestHeaders })
.then((shopResponse) => {
res.end(shopResponse);
})
As you can see from the linked documentation, end() doesn't take a parameter. It just ends the response. You probably want to be calling send() instead if you have data to send.
If you're unsure how your function is executing, also use console.log() to log messages to figure out exactly what it's doing. It's rarely a good idea to just hope that a bunch of code is just working - you should verify that it's working the way you expect.
Solved. Turns out you need a paid plan (Blaze, pay as you go) to access external APIs. I upgraded and that solved the issue.
What is the request module that you are using for the request.post()
Please see : https://www.npmjs.com/package/request#promises--asyncawait
I hope you are using the https://github.com/request/request-promise module instead of request.

OT_AUTHENTICATION_ERROR: Invalid token format (1004)

I am getting a 1004 error when trying to run the opentok api on the server, it is running fine on the localhost but when i ran the same code on the server, it gave me this opentok_authentication_error.
I have checked the apikey and serverkey multiple times and they both are correct, and the session id is also the same.
I can publish and subscribe sessions on the localhost, everything is working fine there but when i uploaded my website on the server and ran it their it gave me this error.
I've also checked the token value generated as well and it is the same which is being generated on the opentok website.
For frontend, I am using angular.js, I dont know what I am doing wrong and when it is working fine on localhost why is giving this error when running on a server.
server.js
Opentok = require('opentok');
var OTConfig = require('./config/otconfig');
var opentok = new Opentok(OTConfig.apiKey, OTConfig.secretKey);
var OT = require('./routes/opentok')(opentok, app);
routes/opentk.js
var OT_config = require('../config/dbconfig');
var express = require('express');
var router = express.Router();
module.exports = function(opentok, app) {
app.post('/opentok/join', function(req, res) {
var token,
sessionId = req.body.ot_session,
tokenOptions = {};
tokenOptions.role = "publisher";
tokenOptions.data = "username=" + req.body.name;
tokenOptions.data += "courseId=" + req.body.course;
tokenOptions.data += "role=" + req.body.role;
// Generate a token.
token = opentok.generateToken(sessionId, tokenOptions);
res.send(token);
});
}
controller.js
var opent = opentokService.generateToken(sessionId);
opent.then(function(data) {
$rootScope.token = data.data;
});
opentok service
return {
generateToken: function(id) {
let info = {
name: $rootScope.username,
id: id,
role: $rootScope.role,
ot_session: $rootScope.sessionId
}
return $http({
method: 'post',
url: '/opentok/join',
data: info
});
}
}
First, check your opentok account subscription is paused or not if it is paused then do the need full to activate your account.

How to keep node-dbox token between page refreshes in NodeJS/Express

Im trying to put together a little application using NodeJS, node-dbox and Express.
When requesting for DropBox authorization - it's a 3 step process, first need to get request_token, then user authorizes them visiting dropbox page, and only then request for access_token, based on request_token and the fact that user has authorized request.
However, by the time I served the page for step 1 and 2 (getting request_token, and providing user with url) - request_token instance is gone!, so in step 3 I can't request for an access_token, because it requires request_token being passed
I'm trying to save request_token in a cookie, but given that contains sensitive data, sending it to the client may not be such a good idea. Any ideas?
Simplified code is below:
(function() {
var dbox = require('dbox'),
config = require('easy-config'),
express = require('express'),
dboxApp = dbox.app(config.dropbox_credentials),
app = express();
app.use(express.cookieParser());
app.get('/', function(req, res) {
dboxApp.requesttoken(function(status, request_token) {
res.cookie('request_token', JSON.stringify(request_token));
res.send("<a href='" + request_token.authorize_url + "' targe='_new'>authorize via dropbox</a><br/>" + "<a href='/next'>next</a>");
});
});
app.get('/next', function(req, res) {
var request_token = JSON.parse(req.cookies.request_token);
if(request_token) {
dboxApp.accesstoken(request_token, function(status, access_token) {
var client = dboxApp.client(access_token);
client.account(function(status, reply){
res.send(reply);
});
});
} else {
res.send('sorry :(');
}
});
app.listen(3000);
})();
bonus question: client is created with access_token, so either instance of client or access_token need to be maintained across page refreshes as well, whats the best approach?
I managed to get it working by doing the following:
According to the Dropbox Developer reference you can provide a callback url by specifying it along with the request as stated here:
https://www.dropbox.com/developers/blog/20
https://www.dropbox.com/1/oauth/authorize?oauth_token=<request-token>&oauth_callback=<callback-url>
By storing the request token in the session and redirecting to the callback url you can then access the request token and be on your way.
A couple of Express route handlers, passed a member id as a parameter, to request and then handle the response might look like this:
linkAccount : function(req, res){
var memberId = req.params.memberId,
appKey = 'MYAPPKEY',
appSecret = 'MYAPPSECRET',
dbox = require('dbox'),
dboxApp = dbox.app({ "app_key": appKey, "app_secret": appSecret });
req.session.dboxStore = {};
req.session.dboxStore.dboxApp = dboxApp;
dboxApp.requesttoken(function(status, request_token){
req.session.dboxStore.request_token = request_token;
console.log("request_token = ", request_token);
res.redirect('https://www.dropbox.com/1/oauth/authorize?oauth_token='+request_token.oauth_token+
'&oauth_callback=http://myhost.local/linksuccess/dropbox/'+memberId);
res.end;
});
},
linkSuccess : function(req, res){
var memberId = req.params.memberId;
var appKey = 'MYAPPKEY';
var appSecret = 'MYAPPSECRET';
var dbox = require('dbox');
var dboxApp = dbox.app({ "app_key": appKey, "app_secret": appSecret });
var request_token = req.session.dboxStore.request_token;
dboxApp.accesstoken(request_token, function(status, access_token){
console.log('access_token = ', access_token);
Member.setAuthToken(memberId, 'dropbox', access_token, function(err, member){
res.render('index', { title:'SUCCESSFUL DROPBOX AUTH' });
res.end;
});
});
}

Resources