Search code examples
sessionfat-free-framework

fatfree sessions, different values in database and echo stmt


I have this in my beforeroute() of a controller

    public function beforeroute()
{
    new \DB\SQL\Session($this->db);

    $mapper = new \DB\SQL\Mapper($this->db, 'users');

    $auth = new \Auth($mapper, array(
        'id' => 'username',
        'pw' => 'password'
    ));

    if (!$auth->login('validuser', '1234')) {
        die('username or password wrong');
    } else {
        echo ($csrf = $this->db->exec('SELECT csrf FROM sessions')[0]['csrf']);
    }
}

After I hit the page, I have different values for csrf in database and what's been echoed out on page. Why is that?


Solution

  • The csrf token is renewed on every request. You see different values on the page and in the database, because the value in the database was updated after your page has rendered.

    To be more specific, the SQL Session handler replaces the default php session handler, and that's why the call to session_commit within the unload method https://github.com/bcosca/fatfree-core/blob/master/base.php#L1903 (is called when the framework shut down) will update your session database table with the new value.

    To have a way to reuse that single csrf token for your purpose, just put it back into the session itself:

    $s = new \DB\SQL\Session($f3->get('DB'));
    // old value from last request
    echo $f3->get('SESSION.csrf');
    // remember current value for next request
    $f3->set('SESSION.csrf',$s->csrf());
    

    Maybe there`s an easier way, but I haven't figured it out yet.