Kohana 3.2 regenerating session id on every request - kohana-3

i hope this hasn't already been answered, I've looked through for awhile and haven't really seen an answer.
I am using Kohana 3.2 sessions with database driver. The problem is that every time the page is loaded or refreshed, it is creating a new session id.
I've set the Session::$default = 'database' in my bootstrap. My session config looks like this:
return array(
'database' => array(
/**
* Database settings for session storage.
*
* string group configuation group name
* string table session table name
* integer gc number of requests before gc is invoked
* columns array custom column names
*/
'name' => 'trucero_session',
'lifetime' => 1200,
'group' => 'default',
'table' => 'sessions',
'gc' => 500,
'columns' => array(
/**
* session_id: session identifier
* last_active: timestamp of the last activity
* contents: serialized session data
*/
'session_id' => 'session_id',
'last_active' => 'last_active',
'contents' => 'contents'
),
),
);
Thank you in advance.

I don't think Laurent really understood your question, because there should be only one single session id created and used between page refreshes - that's the whole point of having sessions is so you can re-use the same session every time when you access a page.
A new session ID is created when you open the page either with a new browser, or close the existing browser and then open a new one, or destroy the current session (like by logging out from your page) and then create a new one (..by logging in).
But I did find a similar problem in Kohana 3.2 where my scripts were generating multiple session IDs per each page read and the sessions weren't being "read" back because a new session_id was created at each page refresh/access. I was able to track this issue down to Google Chrome browser (in my case) and after digging around I found this post:
http://forum.kohanaframework.org/discussion/10303/session-problem-with-ie-and-chrome/p1
Which basically says that you have to set Cookie::domain to either FALSE or to a specific domain for the Kohana database session to work properly in Chrome and in IE.

You cannot rely on the session ID because it's indeed regenerated on every request. If you need some sort of ID, you'll have to use a custom one.

Related

SetTimeout is not working in Mongoose schema post middleware

I am trying to update forgetpassword_token to null in mongodb document after 24 hours of generating forgetpassword_token. So I am using Mongoose schema middleware and setTimeout, but setTimeout is not working.
I have tried to implement async await which is also not working as per my result.
CompanySchema.post('updateOne',true, function(doc,next){
next();
setTimeout(this.update({},{ $set: { forgetpassword_token: null } }).then(result=>{
console.log(result);
}),10000000000);
});
The main problem here is that this implementation is flawed, because if your node application is restarted during the 24-hour window, your timeout will disappear (is an in memory object, not persisted) and the token will remain active, exposing you to security risks.
Manual token verification
A very common solution is to save the token_expiration_date alongside the token, making a date comparison during the related password reset request. If the token_expiration_date is expired, the request return an error and the server must delete the token on the db.
You can also make the opposite: store the token_creation_date and the max-token-ttl in your app code (e.g. 24 hours). In any case you make the date comparison at request time.
#NikKyriakides suggested (see comments) a more sophisticated version of this approach: you create a single JWT token that contains itself the expiration date. When the user request the reset password page you need only to verify if the token is valid calling a single method (no manual date comparison).
The Mongo expire option
A more elegant and effective solution is to create a different mongoose schema for your forgetpassword_token and use the native mongo/mongoose expire option to auto delete documents after a fixed time from their creation.
const secondsInADay = 60 * 60 * 24;
const tokenSchema = mongoose.Schema({
value: String
}, {timestamps: true});
tokenSchema.index({createdAt: 1},{expireAfterSeconds: secondsInADay});
const Token = mongoose.model('Token', tokenSchema);
Then add to your existing CompanySchema a reference to this schema:
forgetpassword_token: {type: mongoose.Schema.Types.ObjectId, ref: 'Token'}
A lot of question exists on this topic, so please also check them alongside with the related mongoose documentation.
The job scheduler
Another approach is to use a job scheduler like agenda to hourly check for expired tokens and delete them. Yes, you can write a setTimeout based check as a module for your app, but if the right tools exists yet, why don't use it? Also check #NikKyriakides comments below for potential drawbacks of this solution.

Sencha Touch: Ext.getStore and Ext.getStore.load

What is the difference between these Sencha Touch API functions.
Ext.getStore('myStore') and Ext.getStore('myStore').load()
I found at many places including sencha docs but could not find any appropriate answer.
Let's take a look at this:
var myStore = Ext.getStore( 'myStore' );
myStore.load();
Ext.getStore( id ) will search the StoreManager for a store with the provided id. If it finds one it will return it otherwise it will return null.
If you have a store object you can load it via store.load(); That's a function of the store.
Only getting the store via getStore does not mean that the data is up to date. To assure it you have to load the store.
Update:
Let's assume you have a localstore. You have already stored some data in it. Now the user closes the app and restarts it.
When your store is not set to autoLoad: true sencha will create the store object for you which you can access by var store = Ext.getStore( 'myLocalStore' ); This store object will NOT contain any data from the underlying localstorage. You have to load the store manually by store.load();. Now you can add some more data and sync it, so the underlying localstorage will get the new data.

Shiro resets the session after 2 min

I am using Apache Shiro in my webapp.
I store some parameters in the session notably the primary key of an object stored in the database.
When the user logs in, I load the object from the database and save the primary key in the session. Then within the app the user can edit the object's data and either hit a cancel or a save button.
Both buttons triggers a RPC that gets the updated data to the server. The object is then updated in the database using the primary key stored in the session.
If the user remains active in the app (making some RPCs) everything works fine. But if he stays inactive for 3 min and subsequently makes a RPC then Shiro's securityUtils.getSubject().getSession() returns null.
The session timeout is set to 1,200,000 ms (20 min) so I don't think this is the issue.
When I go through the sessions stored in the cache of my session manager I can see the user's session org.apache.shiro.session.mgt.SimpleSession,id=6de78f10-b58e-496c-b40a-e2a9a4ad069c but when I try to get the session ID from the cookie and to call SecurityUtils.getSecurityManager().getSession(key) to get the session (where key is a SessionKey implementation): I get an exception.
When I try building a new subject from the session ID I lose all the attributes saved in the session.
I am happy to post some code to help resolve the issue but I tried so many workarounds that I don't know where to start... So please let me know what you need.
Alternatively if someone knows a better documented framework than Shiro I am all ears (Shiro's lack of documentation makes it really too time consuming)
The issue was related to the session config in the ini file. As usual with shiro the order mattered and some of my lines were out of place.
Below is the config that worked for me:
sessionDAO = org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO
#sessionDAO.activeSessionsCacheName = dropship-activeSessionCache
sessionManager = org.apache.shiro.web.session.mgt.DefaultWebSessionManager
sessionManager.sessionDAO = $sessionDAO
# cookie for single sign on
cookie = org.apache.shiro.web.servlet.SimpleCookie
cookie.name = www.foo.com.session
cookie.path = /
sessionManager.sessionIdCookie = $cookie
# 1,800,000 milliseconds = 30 mins
sessionManager.globalSessionTimeout = 1800000
sessionValidationScheduler =
org.apache.shiro.session.mgt.ExecutorServiceSessionValidationScheduler
sessionValidationScheduler.interval = 1800000
sessionManager.sessionValidationScheduler = $sessionValidationScheduler
securityManager.sessionManager = $sessionManager
cacheManager = org.apache.shiro.cache.ehcache.EhCacheManager
securityManager.cacheManager = $cacheManager
It sounds as if you have sorted out your problem already. As you discovered, the main thing to keep in mind with the Shiro INI file is that order matters; the file is parsed in order, which can actually be useful for constructing objects used in the configuration.
Since you mentioned Shiro's lack of documentation, I wanted to go ahead and point out two tutorials that I found helpful when starting:
http://www.javacodegeeks.com/2012/05/apache-shiro-part-1-basics.html
and
http://www.ibm.com/developerworks/web/library/wa-apacheshiro/.
There are quite a few other blog posts that provide good information to supplement the official documentation if you look around.
Good luck!

Kohana sessions and database

I have hard time with kohana sessions, i would like to store my sessions data in database i've already created default sessions table, and i have this config file in
\application\config\session.php
And here is config content: http://pastebin.com/MqqQpH5W
Also my login works just fine, i've tried var_dump(Auth::instance()) and i see some stuff like { ["_session":protected]=> object(Session_Native)#20 so i guess my session does get started, but i'm quite lost on how do i set my session id to the database or some other stuff?
I guess i could just make a normal query for that, but i think there has to be better way to do it.
And btw my main goal is to make list of online users, and i see that i have in table row with name last_active, so my guess is that something should update that table automaticaly, right?
EDIT So after some googling and search in various files i found out that it loads native session type from config file in application/auth, so i've tried to change it to database and now it keeps putting session data in my database every time i refresh page, and login doesn't work anymore, any sugguestions?
In Kohana 3.2 you do it like this:
Put this in your bootstrap.php file:
Session::$default = 'database';
And also make sure your cookie configuration is correct. Put this in your bootstrap.php file also
Kohana_Cookie::$salt = md5('secret');
Kohana_Cookie::$expiration = 1209600; // 14 days
Kohana_Cookie::$domain = '.yourdomain.com';
Where .yourdomain.com will be your host name, make sure you put a dot (.) before it so it will include sub-domains too.

cakephp secure keyword like login method

I want to achieve something like below scenario mention in CakePHP 1.3.8 a latest version:
Ask for Username / Password or directly ask for Secret Keyword
If correct, ask for Secret Keyword
If correct, access more details of website
If wrong, don't allow any further access
There is Auth component into CakePHP for authentication like username/password however I want to implement this extra step of Secret Keyword to access information which should be stored in somefile, encrypted way or some other better way you suggest in a single computer usage only.
Any ideas would be appreciated.
Thanks !
I typically turn off autoRedirect so I can do extra stuff in my login method. I typically don't do this much work, but you can probably repurpose accordingly by, after authentication is complete/successful. It's not a complete answer, nor is the following a complete code snippet for your requirement, but it may be enough to get you started.
/** Logging in and authenticated */
if ( !empty( $this->data ) && $this->Auth->user() ) {
$this->User->id = $this->Auth->user( 'id' );
$this->set_user_type();
$this->User->saveField( 'last_login', date( 'Y-m-d H:i:s' ) );
if( $this->User->has_building( $this->Auth->User('id') ) ) {
$this->redirect( array( 'controller' => 'buildings', 'action' => 'incentives' ) );
}
else {
$this->redirect( $this->Auth->redirect() );
}
}
This is a snippet from one of my own projects. In your case, you might look for a secret key value next. If that doesn't exist, drop into a view to retrieve that and submit back to this same method. On the second pass, if the user is authenticated and the secret key is passed and exists, then redirect as required. If the secret key is wrong, then de-authenticate the user and redirect.
Like I said, not a complete answer and a very simple look at a hard problem, but hopefully it helps you get started.

Resources