How to extend express.js session - session

How can I make sure a session for a client on my express.js app lasts longer than a few hours? I don't want them to log in anew every time they visit my site.
I tried to fiddle with the expires option on the express.session method, but that doesn't seem to have any effect.

You can use req.session.cookie.expires = aSpecificDateAndTime; or req.session.cookie.maxAge = aNumberOfMilliseconds;. Both are equivalent, according to the docs.
Forgot to mention, you can also set these options when setting the middleware (i.e. express.session({secret: "whatever", cookie: {maxAge: 60000}});

cookie: {
path: '/'
,expires: false
,httpOnly: true
,domain:'.example.com'
}
Above setting gives you to have session alive until browser closes.
Available among all pages ( path set to root ).

Related

how to use Sinatra-cache?

I am developing sinatra web app and
I would like to cache in server-side with sinatra-cache gem.
http://www.rubydoc.info/gems/sinatra-cache/0.3.7/frames
I can install it and it worked.
But now it cache all method.
Next what I want to do is limit a specific method to cache.
For example,
get '/cache-me'
will be cached but
get '/nocache'
won't be cached.
How can I control this ?
And also once cached , I want to expire after specified time duration.
How can I do it ?
You have to disable cache by your self.
In your get methods, just add no-cache parameter :cache => false to erb or haml calls. E.g.:
# To turn off caching on certain pages:
get('/nocahce') {
haml(:view_name, :cache => false) # <- here
}
Take a look on documentation for more details. Have a nice day!

Cherrypy creating hundreds of thousands of sessions a day for a site recieving 500 average unique users. Should it be handled the following way?

Having trouble with many sessions files being created sometimes as high as 400,000! I thought I could detect if a session variable is not None using a get but strangely checking a session variable actually creates a session file:
if(cherrypy.session.get('Something')):
I know a session file is create for every request but if I don't run cherrypy.session.get the session file gets deleted. If you run the following code on Cherrypy 3.2.4 after requesting 127.0.0.1:8080/main
the session file is deleted.
import cherrypy
class Root:
def main(self):
return 'Howdy'
main.exposed = True
cherrypy.config.update({'tools.sessions.on': True,
'tools.sessions.storage_type': "File",
'tools.sessions.storage_path': 'sessions',
'tools.sessions.timeout': 1440
})
cherrypy.quickstart(Root(),'/')
However executing this code will create session variable that will timeout in 1440 mins.
import cherrypy
class Root:
def main(self):
if(cherrypy.session.get('Something')):
asdf = 'asdf'
return 'Howdy'
main.exposed = True
cherrypy.config.update({'tools.sessions.on': True,
'tools.sessions.storage_type': "File",
'tools.sessions.storage_path': 'adf',
'tools.sessions.timeout': 1440
})
cherrypy.quickstart(Root(),'/')
So How can I check if a user has a session variable without creating a server side session file that is not deleted?
Any help would be appreciated,
Andrew
Ok this seems to work. Since executing cherrypy.session.get('_cp_Email') causes a permanent session I found a way to check if a session file exists. When a permanent session exists there is a "session-" + cherrypy.session.id file (one without a .lock extension). This code checks for that...
def check_for_session(self=None):
return os.path.isfile(os.path.join(os.getcwd(), 'sessions/session-' + cherrypy.session.id))
def index(self=None):
if(check_for_session() and cherrypy.session.get('_cp_Email')):
Email = cherrypy.session[('_cp_Email']
Hope this helps someone!

Loosing session between requests in Play 1.2.2

I'm having a really odd issue. I'm reusing a piece of code that was fully functional in a previous project but now fails. The code does something like this (code simplified to minimal failing scenario):
if (OpenID.isAuthenticationResponse()) {
UserInfo verifiedUser = OpenID.getVerifiedID();
String value = session.get(AppKeys.AUTH_METHOD); << ERROR
Application.index();
} else {
OpenID openid = getOpenId(client);
session.put(AppKeys.AUTH_METHOD, value);
if (!openid.verify()) {
Application.index();
}
}
Previously I could retrieve the value in the line marked as ERROR. Now that line sets value to null. I've done some tests and, somehow, the session values are lost during the requests although the session id is the same always (so the session in itself doesn't get lost).
I'm sure there is some configuration I've broken, but I'm not being able to find which one. Anyone knows?
In one of those situations of "find the answer just as you sent the question" I discovered the issue. This was the setting screwing the process:
# application.defaultCookieDomain=.xxxxx.com
As I'm in localhost the cookie was not retrieved, and in Play the session values are stored in the cookie as Play is stateless.
Yes, it's time to go to bed...

MooTools AJAX Request on unload

i'm trying to lock a row in a db-table when a user is editing the entry.
So there's a field in the table lockthat I set 1 on page load with php.
Then I was trying to unlock the entry (set it 0) when the page is unloaded.
This is my approach. It works fine in IE but not in Firefox, Chrome etc....
The window.onbeforeunload works in all browsers, I tested that.
They just don't do the Request
BUT
if I simple put an alert after req.send(); it works in some browsers but not safari or chrome. So I tried putting something else after it just so that's there's other stuff to do after the request but it doesn't work.
function test() {
var req = new Request({
url: 'inc/ajax/unlock_table.php?unlock_table=regswimmer&unlock_id=',
});
req.send();
alert('bla'); // ONLY WORKS WITH THIS !?!?!?
}
window.onbeforeunload = test;
i've already tried different ways to do the request but nothing seems to work. And the request itself works, just not in this constellation.
ANY help would be appreciated!
Thanks
the request is asynchronous by default. this means it will fork it and not care of the complete, which may or may not come (have time to finish). by placing the alert there you ensure that there is sufficient time for the request to complete.
basically, you may be better off trying one of these things:
add async: false to the request object options. this will ensure the request's completion before moving away.
use an image instead like a tracking pixel.
move over to method: "get" which is a bit faster as it does not contain extra headers and cookie info, may complete better (revert to this if async is delayed too much)
you can do the image like so (will also be $_GET)
new Element("img", {
src: "inc/ajax/unlock_table.php?unlock_table=regswimmer&unlock_id=" + someid + "&seed=" + $random(0, 100000),
styles: {
display: "none"
}
}).inject(document.body);
finally, use window.addEvent("beforeunload", test); or you may mess up mootools' internal garbage collection

Set Rack session cookie expiration programmatically

I'm using Rack to try to implement "Remember Me" functionality in my Sinatra app.
I'm able to set the session cookie to expire when the session ends or in X seconds time but I'd like to do both.
For example, if a user has clicked "remember me" then I wish for their session to end after X seconds. Eg, my app.rb has a line that looks like this:
use Rack::Session::Cookie, :expire_after => 2592000, #30 days in seconds
:secret => MY_SECRET
I've tried to do the following when the user logs in:
if (!remember_me)
env['rack.session.options'][:expire_after] = nil
end
However, this does not set the cookie value.
How to set this?
I was trying to do the exact same thing and I figured out what the problem for me was. The session cookie gets set on every request if you have an expire_after time set. So when you say if (!remember_me), for that request the cookie's expire time gets set to nil. However, on the very next request, the session cookie is reinitialized with an expire time of 2592000. It seems the fix is to not set a default expire_after time and instead say:
# don't set default expire time
use Rack::Session::Cookie, :secret => MY_SECRET
if(remember_me)
env['rack.session.options'][:expire_after] = 2592000
end
I have unfortunately not figured out how to have a default expire_after time and to permanently extend that time programatically.
This probably has to be done before the session is loaded.
See Rack::Session::Cookie#load_session and Rack::Session::Cookie#commit_session
Chris' answer actually didn't work for me. I found that I had to make sure that I included the original session 'options' with the new 'expire_after' value, so instead of:
env['rack.session.options'][:expire_after] = 2592000
I would use:
env['rack.session.options'].merge! expire_after: 2592000
and be sure to put the use Rack::Session::Cookie statement (without an expire_after setting) in you configure block, if you are using Sinatra.
This did the trick.

Resources