user990664
user990664

Reputation: 37

Kohana 3.2 AJAX form token keeps chaning

I want to use a token in my ajax form. The form is loaded from an ajax controller that generates a unique token. Then the form posts to the same controller.

But I cant get it right! When the form is loaded and then posted, the session is empty or a new token is created! This is I guess because the form and token are created when the ajax call is made.

Here is what I did :

I placed the create the token function at before() in the ajax controller , everytime ajax loads the page it creates a new token which will never validate because it is always changing.

So then I moved the token function to the main controller and it creates the token there, the ajax controller does not extend the main controller, its separate. because I thought now the ajax call wont load the token function. Instead the ajax controller will just get the token created at main. but......its empty

I tried Session::instance()->get('securitytoken') It is supposed to access all sessions across the application right?

Does any one know how I can get this right? or why I cant access a session created in another controller?

This test function gets the token through ajax

class Controller_Ajax extends Controller_Temp{ 
public function action_test(){
$user2 =  Session::instance()->get('securitytoken');
echo $user2; }
}

In my Main controller :

$token = md5(uniqid(microtime(), true));    


Session::instance()->set('securitytoken', $token);

Thank you

Upvotes: 0

Views: 559

Answers (1)

Andrew
Andrew

Reputation: 12809

inside your view:

<?php echo Form::hidden('csrf', Security::token()) ?>

Now inside your controller, check this via the Validation library:

<?php

$post = Validation::factory($_POST)
    ->rule('name', 'not_empty')
    ->rule('email', 'not_empty')
    ->rule('email', 'email')
    ->rule('csrf', 'not_empty')
    ->rule('csrf', 'Security::check')
;
if($post->check()) { ... }
?>

Upvotes: 1

Related Questions