How to pass cookie options in cookie-session 1.0.2 - javascript

I'm trying to learn the "cookie-session" module for Node.
https://github.com/expressjs/cookie-session
I have a hard time understanding how to pass options for the cookie. For example expiration. Default seems to be a year!
This is the instructions about options for the cookie:
"Other options are passed to cookies.get() and cookies.set() allowing you to control security, domain, path, and signing among other settings."
But i dont get it!
Am I supposed to require cookies module as well?
Or do I somehow change the options trough var session = require('cookie-session')?
I have tried session.cookies.set(), but that doesnt seems to work.
I have tried to read the sourcecode in the "cookie-session" and "cookies" module for clues, but I dont know what to look for!

Short answer
Define the options you want to specify in the creation of the session, as illustrated in the docs: https://github.com/expressjs/cookie-session. They will be used when creating the cookie (including the expires option).
app.use(session({
keys: ['key1', 'key2'],
secureProxy: true // if you do SSL outside of node
// more options here...
}))
Long answer
Using the example above, when you pass in the configuration object into session, you are sending this object into the function here. This opts is passed around, but in particular, stored as req.sessionOptions here. req is passed in when creating a new Session, and stored as this._ctx. Finally, when save is called on the Session, these options are pulled from the sessionOptions and used in the set call for the cookies:
Session.prototype.save = function(){
var ctx = this._ctx;
var json = this._json || encode(this);
var opts = ctx.sessionOptions;
var name = ctx.sessionKey;
debug('save %s', json);
ctx.sessionCookies.set(name, json, opts);
};
So the options you pass in originally are passed to the set call when creating the cookie.

Related

Save data from GET request as variable

I've got a simple axios GET request that is working with Azure directline 3.0. The GET request pulls back data and shows it in the console (as seen in the picture).
The data I want to save into a variable is the conversationId. I then want to use this variable with Axios Post in another JS file to post as part of the link e.g. let URL = "https://directline.botframework.com/v3/directline/conversations/"+convID"/activities". With convID being the variable I wish to create. Right now I am manually changing the convID with the new conversation ID, but I want to create a variable so I can place it in the post javascript file so it is automatic.enter image description here
There are various ways you can solve this problem. Easiest one being, exposing the data on a shared object window.convID = convID and then accessing it wherever required.
You could also look to make singleton objects, which can be instantiated only once and hence will share it's variables across the lifespan of the application.
axios.get(/* URL */).then(res => {
window.convID = res.data.conversationId;
});
You can save that variable value in LocalStorage. Something like this:
let routeToYourApi = '/api/conversations'; // or something like this...
axios.get(routeToYourApi).then((response) => {
let conversationId = response.data.conversationId; // not sure if data object from your image is directly nested inside response that you get from server, but you get the idea...
window.localStorage.setItem("convId", conversationId);
}) // here you can fetch your conversation id
Than you can access it anywhere in your app:
let conversationId = window.localStorage.getItem("convId");
... and eventually remove it from local storage:
window.localStorage.removeItem("convId")
Hope this will help you!

javascript - make facebook page post

I am not using the Javascript SDK because that is client-side whereas I'm making a server-side call.
I want to make a page post so that I can make an ad creative with it. I can do the call perfectly fine in the Graph API Explorer tool, but I cannot make the same call (with the same long-lived access tokens that continue to work in the Graph Explorer) from Javascript. Here is my code:
tok = <valid and never expiring user token>;
var pg_tok = <valid and never expiring page token>;
var act_id = <account_id>;
var pg_id = <page_id>;
var call_to_action = 'INSTALL_MOBILE_APP';
var fb_app_url = 'https://itunes.apple.com/us/app/id284882215';
var msg = 'Test creative, ya see';
var pic_url = 'https://s3.amazonaws.com/<path_to_my_image>';
var ROOT = 'https://graph.facebook.com/';
var pagepost_endpoint = ROOT+pg_id+'/feed';
console.log(pagepost_endpoint);
var pagepost_params = {
access_token: pg_tok,
call_to_action: {
type: call_to_action,
value: {link: fb_app_url}
},
message: msg,
picture: pic_url,
published: false
};
console.log(pagepost_params);
var pagepost_res = HTTP.post(pagepost_endpoint, {params: pagepost_params});
console.log(pagepost_res);
I have played around a bunch with params vs. data for where pagepost_params goes in the HTTP.post that is giving the error (that is Meteor's HTTP btw).
-Putting everything in params gives the error: {"error":{"type":"Exception","message":"No Call To Action Type was parseable. Please refer to the call to action api documentation","code":1373054,"is_transient":false}}.
-Putting everything in data gives the error: {"error":{"message":"(#200) This API call requires a valid app_id.","type":"OAuthException","code":200}}.
-Putting access_token in params and everything else in data gives the error: {"error":{"message":"Invalid parameter","type":"FacebookApiException","code":100,"error_subcode":1349125}}.
One more clue for everyone, if I change the HTTP.post to HTTP.get, and just put access_token in params and include no other parameters (in params or in data), the call succeeds and I see past posts I have made on this page through the Graph Explorer (only the ones with published: true, though), so the access token and endpoint do work, just something is faulty about POST-ing instead of GET-ing and the specific parameters I'm using.
Have you tried posting to /photos instead of /feed? The error subcode is the same as mentioned here Posting to facebook wall using graph api
Hope this helps
Turned out to be an issue with Meteor's HTTP. It does not handle nested JSON very well, and we're going to submit a pull request for that. But for those seeing this, the important thing to take away is that the call_to_action may not be a valid JSON object, and even if it is, it may not be being stringified/parsed as expected. My fix was using request.post instead of HTTP.post. (then instead of params or data, you use form. look up node's request https://github.com/mikeal/request)

Why is node.js variable persisting

I'm making a temporary fake API and am trying to set up a simple request response script in node using express.js to achieve this. It's very strraightforward, A request comes in, is validated and, if valid, is merged with a .json template file and the result returned, thus giving the impression the user was successfully created.
app.post('/agent/user', function(req, res){
var responseTemplate = new jsonRequired('post_user');
var errorTemplate = new jsonRequired('post_user_error');
var payload = req.body;
var responseData;
var hasErrors = false;
console.log('Creating new user');
//Recursive Merge from http://stackoverflow.com/a/383245/284695
responseData = new mergeRecursive(responseTemplate,payload);
if(!payload.username){
hasErrors = true;
errorTemplate.errors.username.push('A username is required.');
}
if (hasErrors){
res.send(errorTemplate,422);
}else{
res.send(responseData,200);
}
});
The problem I'm having is that data is persisting between calls. So if I define a username and name[first] in 1 request and just a username in the 2nd one, both requests come back with the name[first] property.
I have a feeling it's something to do with js closures. Unfortunately, every tutorial I find seems to be about making closures, not avoiding them.
It should work like this:
The client POST's username=user1&name[first]=joe&name[last]=bloggs
The Server loads a json file containing a prepopulated user object: e.g.
{"username":"demo","name":{"first":"John","last":"Doe"}...}
mergeRecursive() merges the payload from the POST request over the template object and returns the new object as the POST response text.
The problem is that with every new request, the server is using the result of step 3 in step 2 instead of reloading the .json file.
That mergeRecursive function has the same caveat as jQuery.extend: it modifies the first object sent into it. In fact, you don't even need to use its return value.
You didn't show the code of jsonRequired function (it's not even clear why you've used new when invoking it), but it looks like this function doesn't create a new object each time it's called, instead fetching this object from some outer repository. Obviously, mergeRecursive modifications for it won't be lost after that function ends.
The solution is using your data object for merging. Like this:
var responseData = {};
...
mergeRecursive(responseData, responseTemplate);
mergeRecursive(responseData, payload);
Merging two objects will make this for you.
If your responseTemplate has parameter, which actual request did not have, then you will end up having it there.
Check definition of word merge ;)
While this doesn't resolve the issue I had, I have found a workaround using the cloneextend package available via npm:
$ npm install cloneextend
This allows me to use the following js:
var ce = require('cloneextend');
...
ce.extend(responseData, responseTemplate);
ce.extend(responseData, payload);

What's the best way use caching data in js on client side?

My application receives data from the another server, using API with limited number of requests. Data changing rarely, but may be necessary even after refresh page.
What's the best solution this problem, using cookie or HTML5
WebStorage?
And may be have other way to solve this task?
As much as cross browser compatibility matters, cookie is the only choice rather than web storage.
But the question really depends on what kind of data you are caching?
For what you are trying, cookie and web-storage might not be needed at all.
Cookies are used to store configuration related information, rather than actual data itself.
Web storage supports persistent data storage, similar to cookies but with a greatly enhanced capacity and no information stored in the HTTP request header. [1]
I would rather say, it would be stupid to cache the entire page as cookie or web-storage both. For these purposes, server-side caching options might be the better way.
Update:
Quoting:
data about user activity in some social networks (fb, vk, google+)
Detect the web-storage features, using libraries like mordernizr and if does not exists fall back to cookie method. A simple example
if (Modernizr.localstorage) {
// browser supports local storage
// Use this method
} else {
// browser doesn't support local storage
// Use Cookie Method
}
[1]: http://en.wikipedia.org/wiki/Web_storage
I wrote this lib to solve the same problem:
Cache your data with Javascript using cacheJS
Here are some basic usages
// just add new cache using array as key
cacheJS.set({blogId:1,type:'view'},'<h1>Blog 1</h1>');
cacheJS.set({blogId:1,type:'json'}, jsonData);
// remove cache using key
cacheJS.removeByKey({blogId:1,type:'json'});
// add cache with ttl and contextual key
cacheJS.set({blogId:2,type:'view'},'<h1>Blog 2</h1>', 3600, {author:'hoangnd'});
cacheJS.set({blogId:3,type:'view'},'<h1>Blog 3</h1>', 3600, {author:'hoangnd'});
// remove cache with con textual key
// cache for blog 2 and 3 will be removed
cacheJS.removeByContext({author:'hoangnd'})
Here is an example of caching data from JQuery AJAX. So if you only want to make the call when you don't have the data yet, its really simple. just do this (example). Here we first check if we have the load information (keyed on line, location and shipdate), and only if we dont, we make the AJAX call and put that data into our cache:
var dict = [];
function checkCachedLoadLine(line, location, shipDate, callback) {
var ret = 0;
if(!((line+location+shipDate) in dict)) {
productionLineService.getProductionLoadLine(line, location, shipDate, callback);
}
return dict[line+location+shipDate];
}
...then in the call back write the value to the cache
function callback(data) {
if (!data) {
document.getElementById('htmlid').innerHTML = 'N/A';
} else {
document.getElementById('htmlid').innerHTML = data[0];
dict[data[2]+data[3]+data[4]] = data[0];
}
}

Javascript Web App Best Practices

I'm having a hard time writing my question succinctly and clearly, so let me describe what I'm working with.
I'm building a web application that:
has it's own API hosted on a subdomain (https://api.example.com)
has the main application hosted on the tld (https://www.example.com)
the tld doesn't have any database access, but instead interacts with the API to work with data
the tld authenticates with the api through OAuth and stores the access token and access token secret in a session
when the session ends, the access token is no longer used, thus logging the user out
I have a route in the tld (let's call it /ajax for this question) that the javascript calls (GET, PUT, POST, OR DELETE) to make requests to the api. This way, nobody ever has to see the access token, access token secret, consumer key, or consumer secret.
The way I see it, the access token and access token secret are really the only things I need to store in a session since I can grab everything else using the API, but instead of making a call every single time for every piece of data I need, I think some things should persist, like aspects of the user's profile, layout preferences, etc.
What is the best way for me to accomplish this? Local storage? Cookies? Should I scrap this and just store it in sessions?
And if you have some time, what other best practices are there for building sites like this that I may not know of?
You are on the right track I would say, but store your data in JavaScript primarily. And couple it with Local Storage when suitable.
When I build apps such as the one you are describing I usually take care to set up JavaScript representations of the data I receive via the API.
One such representation could look as follows below. Bear in mind that my example code below makes a couple of assumptions.
It makes the assumption that you have an api object defined which takes care of API calls, and invokes a callback on completion.
that the data returned by the API is JSON that simply can be assigned to a JavaScript variable,
That the JSON returned is a list of objects, each with an "id" field.
That you have some sort of event object, I usually build my own custom events that basically carry function objects as listeners and when fired go through the listeners and invoke the functions with or without a payload depending on the situation.
Data container example:
MYAPP.data.BaseContainer = function (api_url, loadedEvent) {
var self = {
// Array to store the data returned via the APIs
_data : [],
// The API URL used to fetch data
api_url : api_url,
// Boolean flag to signify whether the _data variable has been populated
is_loaded : false,
// The even to fire once _data has been populated
loadedEvent : loadedEvent,
/**
* Returns the state of the is_loaded variable
*/
loaded : function () {
return self.is_loaded;
},
/**
* Takes an ID and returns any member of the _data array
* that has that ID.
*
* #param id : an String or integer representing the ID.
* #returns {Object}
*/
byId : function (id) {
var toReturn = null;
for (var i = 0, len = self._data.length; i < len; i++) {
if (self._data[i].id == id) {
toReturn = self._data[i];
break;
}
}
return toReturn;
},
/**
* Returns the entire _data array.
*/
all : function () {
return self._data;
},
/**
* This simple callback just stores the json response in
* its entirety on the _data variable.
*/
callback : function(data) {
self._data = data;
self.is_loaded = true;
loadedEvent.fire(self._data);
},
/**
* Calls the API, if no callback has been specified as a parameter
* self.callback is used.
*/
getFromAPI : function(callback) {
if (typeof callback === 'undefined') {
callback = self.callback;
}
api.get(self.api_url, callback);
}
};
self.getFromAPI();
return self;
};
With this blueprint I can now create specific data containers like this:
/**
* Stores a list of "friends" gotten from the API.
* This is basically an instance of the BaseContainer object defined above.
*/
MYAPP.data.Friends = (function () {
var self = MYAPP.data.BaseContainer("API_URL_TO_FECTH_FRIENDS_LIST", FriendsLoadedEvent);
return {
byId : self.byId,
all : self.all,
loaded : self.loaded
};
}());
As soon as this code is run, an API call is made, and the FriendsLoadedEvent will be fired when it is done. So, to put it bluntly, I use JavaScript to store my stuff usually. But if you want to throw LocalStorage into the mix that is easy too!
Just add local storage code to the BaseContainer object that first detects whether the client actually supports localstorage, and if so mirror the _data field in local storage. This is handy to keep often used data quickly available between sessions. Use the readily available JSON parsing tools to convert the data from JSON to LocalStorage "text"and back.
Just keep in mind that you cannot rely on LocalStorage as your primary data structure, you have no guarantee that the client supports it, and even when it does the upper bounds for how much data you can actually store is different between the browsers. So use it to store data that:
You want access to very often,
that you feel should just be there, immediately as soon as the user logs in,
and that does not change often enough to warrant refreshing API calls constantly.
Congratulation! You've answered most of your question already. If you want to persist user data, you'll need to use something like local storage or cookies. In your case local storage is best. With cookies, each page request sends to cookies along in the header.
Best of Luck with your app.

Categories