I'm trying to follow Microsoft's guide to generate a SAS Token, and here's my script:
function createSharedAccessToken(uri, saName, saKey) {
uri = // '...'
saName = // '...'
saKey = // '...'
if (!uri || !saName || !saKey) {
throw "Missing required parameter";
}
var encoded = encodeURIComponent(uri);
var now = new Date();
var week = 60 * 60 * 24 * 7;
var ttl = Math.round(now.getTime() / 1000) + week;
var signature = encoded + '\n' + ttl;
var signatureUTF8 = utf8.encode(signature);
var hash = crypto.createHmac('sha256', saKey).update(signatureUTF8).digest('base64');
return 'SharedAccessSignature sr=' + encoded + '&sig=' +
encodeURIComponent(hash) + '&se=' + ttl + '&skn=' + saName;
}
createSharedAccessToken()
But I'm getting a:
var signatureUTF8 = utf8.encode(signature);
^
ReferenceError: utf8 is not defined
Any idea on why that is happening?
Related
I am currently working is a calendar. I added start date and end date but My client also wants start time and end time. Here is a method subject. addEvent. With that I send start date and end date. I do not know how to send start time and end time. Please help with it.
My code:
$scope.addToCalRestaurantEvent = function() {
console.log(" calender event button hit ... ");
var icsObject = ics();
console.log("## pickupdate : ## " + $scope.completeBookingInfo.date);
//11/12/1987', '11/12/1987
//$scope.completeBookingInfo.date, $scope.completeBookingInfo.date
icsObject.addEvent('addRestaurantEvent', 'This is the best day to demonstrate a single event.',
'New York', '2/17/2017', '2/17/2017');
var downloadFileName = "addRestaurantEvent";
icsObject.download(downloadFileName);
console.log("The addRestaurantEvent file downloaded ... ");
}
The ICS library:
/* global saveAs, Blob, BlobBuilder, console */
/* exported ics */
var ics = function() {
'use strict';
if (navigator.userAgent.indexOf('MSIE') > -1 && navigator.userAgent.indexOf('MSIE 10') == -1) {
console.log('Unsupported Browser');
return;
}
var SEPARATOR = (navigator.appVersion.indexOf('Win') !== -1) ? '\r\n' : '\n';
var calendarEvents = [];
var calendarStart = [
'BEGIN:VCALENDAR',
'VERSION:2.0'
].join(SEPARATOR);
var calendarEnd = SEPARATOR + 'END:VCALENDAR';
return {
/**
* Returns events array
* #return {array} Events
*/
'events': function() {
return calendarEvents;
},
/**
* Returns calendar
* #return {string} Calendar in iCalendar format
*/
'calendar': function() {
return calendarStart + SEPARATOR + calendarEvents.join(SEPARATOR) + calendarEnd;
},
/**
* Add event to the calendar
* #param {string} subject Subject/Title of event
* #param {string} description Description of event
* #param {string} location Location of event
* #param {string} begin Beginning date of event
* #param {string} stop Ending date of event
*/
'addEvent': function(subject, description, location, begin, stop) {
// I'm not in the mood to make these optional... So they are all required
if (typeof subject === 'undefined' ||
typeof description === 'undefined' ||
typeof location === 'undefined' ||
typeof begin === 'undefined' ||
typeof stop === 'undefined'
) {
return false;
};
//TODO add time and time zone? use moment to format?
var start_date = new Date(begin);
var end_date = new Date(stop);
var start_year = ("0000" + (start_date.getFullYear().toString())).slice(-4);
var start_month = ("00" + ((start_date.getMonth() + 1).toString())).slice(-2);
var start_day = ("00" + ((start_date.getDate()).toString())).slice(-2);
var start_hours = ("00" + (start_date.getHours().toString())).slice(-2);
var start_minutes = ("00" + (start_date.getMinutes().toString())).slice(-2);
var start_seconds = ("00" + (start_date.getMinutes().toString())).slice(-2);
var end_year = ("0000" + (end_date.getFullYear().toString())).slice(-4);
var end_month = ("00" + ((end_date.getMonth() + 1).toString())).slice(-2);
var end_day = ("00" + ((end_date.getDate()).toString())).slice(-2);
var end_hours = ("00" + (end_date.getHours().toString())).slice(-2);
var end_minutes = ("00" + (end_date.getMinutes().toString())).slice(-2);
var end_seconds = ("00" + (end_date.getMinutes().toString())).slice(-2);
// Since some calendars don't add 0 second events, we need to remove time if there is none...
var start_time = '';
var end_time = '';
if (start_minutes + start_seconds + end_minutes + end_seconds != 0) {
start_time = 'T' + start_hours + start_minutes + start_seconds;
end_time = 'T' + end_hours + end_minutes + end_seconds;
}
var start = start_year + start_month + start_day + start_time;
var end = end_year + end_month + end_day + end_time;
var calendarEvent = [
'BEGIN:VEVENT',
'CLASS:PUBLIC',
'DESCRIPTION:' + description,
'DTSTART;VALUE=DATE:' + start,
'DTEND;VALUE=DATE:' + end,
'LOCATION:' + location,
'SUMMARY;LANGUAGE=en-us:' + subject,
'TRANSP:TRANSPARENT',
'END:VEVENT'
].join(SEPARATOR);
calendarEvents.push(calendarEvent);
return calendarEvent;
},
/**
* Download calendar using the saveAs function from filesave.js
* #param {string} filename Filename
* #param {string} ext Extention
*/
'download': function(filename, ext) {
if (calendarEvents.length < 1) {
return false;
}
ext = (typeof ext !== 'undefined') ? ext : '.ics';
filename = (typeof filename !== 'undefined') ? filename : 'calendar';
var calendar = calendarStart + SEPARATOR + calendarEvents.join(SEPARATOR) + calendarEnd;
var blob;
if (navigator.userAgent.indexOf('MSIE 10') === -1) { // chrome or firefox
blob = new Blob([calendar]);
} else { // ie
var bb = new BlobBuilder();
bb.append(calendar);
blob = bb.getBlob('text/x-vCalendar;charset=' + document.characterSet);
}
saveAs(blob, filename + ext);
return calendar;
}
};
};
I am using YQL to parse an RSS feed on my wordpress website. I have the code working and displaying entries from my RSS feed, but how do I limit the number of entries it displays? Is there a way to display 5 at a time? My code is as follows:
function parseFeed(url, container) {
// yql query
var query = 'https://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from feednormalizer where url="' + url + '"' ) + '&format=json';
// send request
$.getJSON(query, function (data, status, errorThrown) {
// if successful... *
if (status === 'success') {
// log object data in console
console.log(data);
// append feed link and title in container
$(container).append('<span class="iconicstroke-rss-alt"></span>');
$(container).append('<h1 class="feed">' + data.query.results.rss.channel.title );
// for each entry... *
$.each(data.query.results.rss.channel.item, function (key, value) {
// * create new date object and pass in entry date
var date = new Date(value.pubDate);
// * create months array
var months = new Array(12);
months[0] = 'January';
months[1] = 'February';
months[2] = 'March';
months[3] = 'April';
months[4] = 'May';
months[5] = 'June';
months[6] = 'July';
months[7] = 'August';
months[8] = 'September';
months[9] = 'October';
months[10] = 'November';
months[11] = 'December';
// * parse month, day and year
var month = date.getMonth();
var day = date.getDate();
var year = date.getFullYear();
// * build content snippet
var content = $(value.description).text().substring(0, 340);
if (value.description.length > content.length ) {
content += ' ...';
}
// * assign entry variables
var title = '<h3 class="title">' + value.title + '</h3>';
var time = '<p class="time">' + day + ' ' + months[month] + ' ' + year + '</p>';
var snippet = '<p class="snippet">' + content + '</p>';
var entry = '<div class="entry">' + title + time + snippet + '</div>';
// * append entire entry in container
$(container).append(entry);
});
// if there's an error... *
} else if (status === 'error' || status === 'parsererror') {
// * log error message in console
console.log(errorThrown);
// * show error message
alert('Could not load RSS feed!');
}
});
}
$(document).ready(function () {
parseFeed('http://www.vatlive.com/feed/', '#vatrss', '');
});
I have a problem with a field name that has a period "." to it
I can only make it work if the field name is something like input_1 or input_1_2
But when it is something like input_1.2 it doesn't work.
function CalculateSig(stringToSign, privateKey){
//calculate the signature needed for authentication
var hash = CryptoJS.HmacSHA1(stringToSign, privateKey);
var base64 = hash.toString(CryptoJS.enc.Base64);
return encodeURIComponent(base64);
}
var d = new Date;
var expiration = 3600;
var unixtime = parseInt(d.getTime() / 1000);
var future_unixtime = unixtime + expiration;
var publicKey = "mupubkey";
var privateKey = "pyprikey";
var method = "POST";
var route = "forms/6/submissions";
stringToSign = publicKey + ":" + method + ":" + route + ":" + future_unixtime;
sig = CalculateSig(stringToSign, privateKey);
var url = 'https://www.localhostlbahblah.com/gravityformsapi/' + route + '?api_key=' + publicKey + '&signature=' + sig + '&expires=' + future_unixtime;
var values = {input_values:{'input_1.3':"test",// not working first name value
"input_2":"testetest", // this is working
}}
values_json = JSON.stringify(values);
$.post(url, values_json, function(data){
console.log(data.response);
});
i need to upload file to google cloud storage using signed url. i need to upload by diffrent steps.
Create a signedUrl using bucketName, service key and needed security credentials.(using any node.js library)
upload a single file with created signed url using a Postman or restClient.
This is my code for creating signedUrl for uploading
var crypto = require("crypto");
var fs = require("fs");
var URL_VALID_DURATION = 1000 * 120;//for 120 seconds
var expiry = Math.floor(((new Date).getTime() + URL_VALID_DURATION) / 1000);
var key = 'filename';
var bucketName = 'bucketName';
var accessId = 'gserviceaccount.com';
var stringPolicy = "POST\n" + "\n" + "\n" + expiry + "\n" + '/' + bucketName + '/' + key;
var base64Policy = Buffer(stringPolicy, "utf-8").toString("base64");
var privateKey = fs.readFileSync("google-services-private-key.pem", "utf8");
var signature = encodeURIComponent(crypto.createSign('sha256').update(stringPolicy).sign(privateKey, "base64"));
var signedUrl = "https://" + bucketName + ".commondatastorage.googleapis.com/" + key + "?GoogleAccessId=" + accessId + "&Expires=" + expiry + "&Signature=" + signature;
console.log(signedUrl);
But i got error, when using with postman or rest client
<?xml version='1.0' encoding='UTF-8'?>
<Error>
<Code>SignatureDoesNotMatch</Code>
<Message>The request signature we calculated does not match the signature you provided. Check your Google secret key and signing method.</Message>
<StringToSign>PUT
multipart/form-data
1458024549
/bucketName/fileName</StringToSign>
</Error>
Just changed stringPolicy method to PUT. and also send image as binary.
var crypto = require("crypto");
var fs = require("fs");
var URL_VALID_DURATION = 1000 * 120;//for 120 seconds
var expiry = Math.floor(((new Date).getTime() + URL_VALID_DURATION) / 1000);
var key = 'filename';
var bucketName = 'bucketName';
var accessId = 'gserviceaccount.com';
var stringPolicy = "PUT\n" + "\n" + "\n" + expiry + "\n" + '/' + bucketName + '/' + key;
var base64Policy = Buffer(stringPolicy, "utf-8").toString("base64");
var privateKey = fs.readFileSync("google-services-private-key.pem", "utf8");
var signature = encodeURIComponent(crypto.createSign('sha256').update(stringPolicy).sign(privateKey, "base64"));
var signedUrl = "https://" + bucketName + ".commondatastorage.googleapis.com/" + key + "?GoogleAccessId=" + accessId + "&Expires=" + expiry + "&Signature=" + signature;
console.log(signedUrl);
I am trying to POST JSOn data to a cloud with this function in function node.
var accx = 15;
var accy = 45;
var accz = 12;
//JSON FORMING BY JAVASCRIPT OBJECT
var output = [];
output[0] = {
name: "Accel_X",
value: accx.toString(), // retrieve x
};
output[1] = {
name: "Accel_Y",
value: accy.toString(), // retrieve y
};
output[2] = {
name: "Accel_Z",
value: accz.toString() // retrieve z
};
var record = [];
record[0] = {
starttime: formatDate(new Date()),
output: output,
};
var observations = [];
observations[0] = {
sensor: "C2105",
record: record,
};
var fromData = {};
fromData.version = "1.0.1";
fromData.observations = observations;
//MONTH NAME FUNCTION
function show_now(){
var my_month=new Date()
var month_name=new Array(12);
month_name[0]="JAN"
month_name[1]="FEB"
month_name[2]="MAR"
month_name[3]="APR"
month_name[4]="MAY"
month_name[5]="JUN"
month_name[6]="JUL"
month_name[7]="AUG"
month_name[8]="SEP"
month_name[9]="OCT"
month_name[10]="NOV"
month_name[11]="DEC"
return month_name[my_month.getMonth()];
}
//RETURN DATE AT FORMATTED WAY THAT IS ACCEPTED BY CLOUD
function formatDate(d) {
return d.getDate() + '-' + (show_now()) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + " IST";
}
var fromDatan = JSON.stringify(fromData);
//alert(fromDatan);
//POST JSON SENSOR DATA
fromDatan.headers = {
"x-api-key": "ucrFr234r23rrxfAIH2L4=",
"content-type": "application/json;charset=UTF-8"
}
return fromDatan;
I have given correct url in url node but it is returning no response and I am not seing any data is being post
Anyone please worked with node-red.js please help.
Your function node needs to return an object with a payload property containing the data you want to send in the http request. It is also not necessary to stringify the object as the http request node will do that for you.
var fromDatan = {};
fromDatan.payload = fromData;
fromDatan.headers = ...
return fromDatan