why is my express middleware session undefined? - session

I'm trying to use the express middleware for sessions (I'm not understanding but I feel that I am very close).
the reason I have ended up asking is that the express docs (http://expressjs.com/api.html#middleware) are calling it express.cookieSession where as everyone else (mostly on here) Ive seen discussing it have been calling it express.session. I'm really not sure now, I just have a big lump of possibly useful code ??? but every example I see is different ... how does it work?
var express = require('express')
, http = require('http');
, app = express();
store = new express.session.MemoryStore;
app.use(express.cookieParser());
//app.use(express.cookieSession());
app.use(express.session({secret:'whateverman',key:'express.sid',store:store}));
app.use(app.router);
app.all('/*',function(req,res,next){res.header("Access-Control-Allow-Origin","*");res.header("Access-Control-Allow-Headers","X-Requested-With");next();});
var server = http.createServer(app);
server.listen(8000);
var io = require('socket.io').listen(server);
io.sockets.on('connection',function(socket){
socket.on('reglogin',function(_){_.session.e='some#email.com';});
});
socket.on('reglogin' produces:
TypeError: Cannot set property 'e' of undefined
//-------------------------------update on question
if express is dependant on connect but express can access connects middleware as if it were its own, eg:
app.use(express.cookieSession()); //app is express
app.use(connect.cookieSession()); //does exactly the same
then surely the same logic would apply to socket.io which is dependant on express:
io.use(connect.CookieSession()); //io is socket.io
Am I wrong here? does Socket.io have the same .use method? update:(answer is no to io.use)
io.interoperate(app.use(express.cookieSession())); LOL
----------------------------UPDATE---------------------------------
I've followed the following npm modules guide lines in a despirate attemp to get sessions working and filed each and every time on handshake with no cookie:
express.io
session.socket.io
session.io + sessionstore
currently using the latter with console log:
warn - handshake error Could not find cookie with key: connect.sid

Related

How to receive private messages from the stream using Socket.IO in .Net Core 3.0

I am trying to receive private meesages from SocketIO stream. I have IP address but I am getting problem in connection. Also, if connection will happen then also I have to authorize the connection using token then only I can get the messages. I dont how to implement this as I am vey much New to this thing.
I have tried with the following code from the stack overflow but no luck yet.
Also, can anybody tell me which library is best to use:
SocketIO4Net.Client
SocketIOClientDotNet
I am using 2nd one.
var socket = IO.Socket("myip");
socket.On("xx", async (data) =>
{
var test = await Update(data.ToString());
});
Can anybody help me on this. I am .net server side developer.Thanks in advance!!

RetryPolicy on Web Api causes timeout

I have a Web Api that invokes another web api call to get some information. In order to make the app more resilient, I implemented a HttpTransientErrorDetectionStrategy following the steps at: https://alexandrebrisebois.wordpress.com/2013/02/21/defining-an-http-transient-error-detection-strategy-for-rest-calls/
After that, I use code like below to invoke the other web app:
RetryPolicy _retryPolicy = new RetryPolicy<HttpTransientErrorDetectionStrategy>(
new ExponentialBackoff(retryCount: 2, minBackoff: TimeSpan.FromSeconds(0), maxBackoff: TimeSpan.FromSeconds(10), deltaBackoff: TimeSpan.FromSeconds(2)));
var _httpClient = new HttpClient
{
BaseAddress = new Uri("http://www.microsoft.com")
};
HttpResponseMessage response = _retryPolicy.ExecuteAsync(async () => await _httpClient.GetAsync($"", HttpCompletionOption.ResponseContentRead)).Result;
The _httpClient.GetAsync call gets stuck, and I have no idea why. If I remove the _retryPolicy, and just use _httpClient.GetAsync directly, it returns in a matter of seconds.
I have similar code on a console app, to invoke the same web app, and that is working fine, so this seems to be specific to the way I am using it in my web API. This is intended to be an app on Azure, but it happens when I debug locally as well. Does anybody have any idea why this is getting stuck? How can I debug this?
Thank you!
I have similar code on a console app, to invoke the same web app, and that is working fine, so this seems to be specific to the way I am using it in my web API.
The code you posted is blocking right here:
HttpResponseMessage response = _retryPolicy.ExecuteAsync(...).Result;
Don't block on async code. Instead, use await:
HttpResponseMessage response = await _retryPolicy.ExecuteAsync(...);
If I remove the _retryPolicy, and just use _httpClient.GetAsync directly, it returns in a matter of seconds.
If your original code is blocking, and you must block on asynchronous code (for some reason), then you can either use the ConfigureAwait(false) hack:
HttpResponseMessage response = _retryPolicy.ExecuteAsync(async () => await _httpClient.GetAsync($"", HttpCompletionOption.ResponseContentRead).ConfigureAwait(false)).Result;
or elide async/await:
HttpResponseMessage response = _retryPolicy.ExecuteAsync(() => _httpClient.GetAsync($"", HttpCompletionOption.ResponseContentRead)).Result;
P.S. Check out DecorrelatedJitterBackoffV2.

Gmail Gadget Error 406 being thrown on osapi.http.post

We have multiple marketplace Apps that use Gmail Contextual Gadgets. These have been running for years successfully.
We are now noticing the following intermittent error being thrown when calling out to an external web server using open social osapi.http.post
"{"id":"http.post","error":{"message":"Response not valid JSON","code":406}}"
We have checked and there is nothing wrong with our server. We can make the call directly to our server successfully without fail.
We can replicate the issue calling to multiple servers running different apps/gadgets. The only commonality appears to be the use of osapi.http.post.
Here is the post
osapi.http.post({
'body': postdata,
'href': serverUrl + 'iLinkStreamer.ashx?data=' + "" + setTimeStamp() + debugString,
'format': 'json',
'authz': 'signed',
'noCache': true
}).execute(displayStreamList);
which raises the 406 error as above
Has anybody else noticed this issue?? Not sure how we can address it?
I had the same issue for a while and finally found the problem. I was also invoking external resources using osapi.http.post. I read the new documentation and found that there is a new way to do the same.
Check this url for more details, but the idea is that now you'll need to use makeRequest API, it will look something like this:
var params = {};
params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
params[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.SIGNED;
params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
gadgets.io.makeRequest("https://your.backend.com", on_response_function, params);
...
def on_response_function(response){ ... }
I hope this helps someone.
I'm not sure if I'm the only one, but I never received a notification message that the previous API will be deprecated. :(

Using Parse master key from the server and not cloud code

I recently implemented the security of my Parse app thinking that I could use the master key on my server (express not cloud code) to securely bypass my security implementations for admin/server level functions.
I'm using "parse": "^1.5.0",
in my package.json.
Right now in each of my express modules I have:
var Parse = require('parse').Parse;
Parse.initialize("Application ID", "Javascript Key", "Master Key");
Everything works fine without CLPs activated but with CLPs I can't do any read/write of the data with the server. I understand that I can move this to Cloud code and get it to work however I need to use a number of libraries in my code that Parse does not support and transporting all of the code to cloud code would be very tough.
What am I doing wrong?
Here's what worked for me.
/////////////////////////////////this is the top of the JS page/module/////
'use strict';
var Parse = require('parse/node');
Parse.initialize('app-id','js-key','master-key');
exports.create = function(req, res) {
Parse.Cloud.useMasterKey();
//now when you do a parse query or action you can bypass your security settings.
};

Node.js server restart drops the sessions

I'm having fully functional user signup/authentication system using express and connect middleware.
app.use(express.session({store: require('connect').session.MemoryStore( {reapInterval: 60000 * 10} ) }))
The only problem is that sessions drop every time you perform server restart.
https://github.com/remy/nodemon - and nodemon restarts node.js every time it detects a file change.
How can I have persistent sessions ?
Like your code is telling you are using MemoryStore. This is volatile and gets cleared on restart. I would advise you to use connect_redis to persist your session. Redis is an extremely fast store.
Download redis
compile redis: make
Start server: ./redis-server
npm install connect-redis
var connect = require('connect') , RedisStore = require('connect-redis');
connect.createServer(
connect.cookieParser(),
// 5 minutes
connect.session({ store: new RedisStore })
);
This is just to get you started quickly. You should read the documentation and configure redis if you want to get most out of redis.
I was trying to get Redis on track using express.js, Google sent me here. The express implementation changed:
var express = require('express'),
RedisStore = require('connect-redis')(express);
Another important thing is the order of express configurations.
app.configure(function(){
app.enable('strict routing'); // removes trailing slash
app.set('views', __dirname + '/views');
app.set('view engine', 'jqtpl');
app.register('.html', require('jqtpl').express);
app.use(express.favicon());
app.use(express.methodOverride());
app.use(express.compiler({src: __dirname + '/public', enable: ['sass']}));
app.use(express.static(__dirname + '/public'));
app.use(app.router);
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({secret: _.config.secret, store: new RedisStore}));
});
cookieParser & session configurations need to be at the end of the configurations, and cookieParser must be placed right before express.session.
Hope that helps, I ran in both of these problems.
I agree with everybody about Redis, but I think that different technologies are a problem in terms of software maintenance. If you are using MongoDB for example there is connect-mongo (https://npmjs.org/package/connect-mongo), if you are using MySQL there is connect-MySQL (https://npmjs.org/package/connect-mysql), connect-couchdb for CouchDB (https://npmjs.org/package/connect-couchdb) and so on.
also, if you're using express, you need to provide a secret when telling the app to use the redis middleware.
so, follow Alfred's recipe above, but do the following...
var express = require( 'express' );
var RedisStore = require('connect-redis');
app.use( express.cookieParser() );
app.use( express.session( { secret: "keyboard cat", store: new RedisStore }));
When node dies I would imagine the memory store you're using dies.
Persist the sessions to disk?

Resources