Yii2 DbSession lost after redirect, 90% of the time - yii

My login worked perfectly with PHP sessions. I tried switching to DbSession engine but login will not work anymore, as the session is empty after the page redirection.
Here's the workflow:
User enters his user id and clicks submit to post the data
Validation works (I tested) and a new identity cookie is created with the key sess = XXXX (tested with log just before redirect).
The $_SESSION is filled with the user data (tested with log just before redirect)
The page redirects with the new response cookie.
The password page loads and the request cookie has the same XXXX value (tested with log just after redirect + in chrome developer tools).
The session now only contains
[__flash] => Array
(
)
response cookie "sess" = request cookie "sess" = id in the session table, so the same key is everywhere, yet the session is still empty on the password page, 90% of the time (because in some random cases, the session is still there, but I can't reproduce it on demand)
I already checked these questions, not the same problem:
PHP session lost after redirect
Session lost after redirect in Codeigniter
Has anyone seen something similar before? I can't figure out what's causing this.
Addendas:
Session configuration
'session' => [
'class' => 'yii\web\DbSession',
'name' => 'sess',
'timeout' => 3600,
'db' => 'session_db',
'sessionTable' => 'session',
],
Session db config
$config['components']['session_db'] = [
'class' => 'yii\db\Connection',
...
],
Login action
// authenticate() Just checks if the user is valid, etc
Yii::$app->user->authenticate();
// login() just calls parent::login(), sets some session values then returns !$this->getIsGuest()
Yii::$app->user->login(Yii::$app->user);
update!! I have just noticed that if I use the same database instead of "db" (my main db) instead of "session_db", it works perfectly, even if both tables have exactly the same schema in the 2 databases.

Related

datatables / jquery / session variable / login form

Scenario:
1) login.php verifies the username and password and sets a session with the user id
$_SESSION['id'] = $id;
2) datatables / jquery calls an action.php file to fill the table with data
"ajax":{
url:"action.php",
type:"POST",
data:{action:'listTable'},
dataType:"json"
},
3) the action.php file calls the function listTable()
include('table.php');
$table = new table();
$table->listTable();
4) the listTable function (table.php) returns the whole data which is landing in the datatable
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => $numRows,
"recordsFiltered" => $numRows,
"data" => $tableData
);
echo json_encode($output);
5) the data was selected with a sql command and was put into the tableData variable
Everything works fine in that case.
Ideas:
I wanted to acccess the session variable within the sql select command. This is not possible, because of the jquery / action.php api. Those are complete different files and have no access to that session. It is possible to set the user id within a hidden formular field, but this is not secure and easy to manipulate. A cookie file is also user editable. Furthermore Javascript cannot read server side session variables.
Question:
How can i use / access that php session variable in that scenario?
Update:
Thats not working too :/
overview.php
$userID = $_SESSION['id'];
data.js
"ajax":{
url:"action.php",
type:"POST",
data:{userID:userID, action:'listTable'},
dataType:"json"
},
table.php
$userID = $_POST["userID"];
I really don't understand here the problem, because of $_SESSION variable is available across the php files even if an ajax calls the php file. Until you call the AJAX call from the same browser and the ajax call includes the cookies (one of the cookie will be the session ID) then you will be able to reach your user ID in the SQL query on the PHP side, without passing to javascript/jquery your user's ID.
As you wrote in login.php:
$_SESSION['id'] = $id;
In your table.php where the SQL command is living:
echo isset($_SESSION['id']) ? "I'm existing!" : "I'm NOT existing!";
It will print "I'm existing!" if the user logged in and "I'm NOT existing!" if the user didn't log in. All the $_SESSION variables are available across the php files until the server gets the SESSION ID from the browser (which is a cookie). Cookies are automatically sent if you calling the same domain.

Laravel Auth attempt hashing

In a login form, I have this Auth check:
$auth = Auth::attempt([
'email' => Input::get('email'),
'password' => Input::get('password'),
'active' => 1
], $remember);
Now this Auth check is taking the raw input from the input field. Yet my database of which this is Authorising against stores the password in an encrypted state using Hash::make().
This login form works perfectly fine. The user logs in with the correct password, but it uses a raw password in the Auth function against a hashed password, yet returns true.
Why is this?
The Auth class does the hashing in the background and compares the password the same way you would normally.

My Salesforce password changed and now my Ruby on Rails app is broken

I have a simple demo app set up to be able to access Salesforce.com from a Ruby on Rails app. My code is extremely simple:
def sign_in_salesforce
client = OAuth2::Client.new(ENV['SALESFORCE_CONSUMER_KEY'], ENV['SALESFORCE_CONSUMER_SECRET'], :site => 'https://login.salesforce.com/', :authorize_url => 'services/oauth2/authorize', :token_url => 'services/oauth2/token')
auth_url = client.auth_code.authorize_url(:redirect_uri => 'https://99.44.242.76:3000/users/oauth_callback')
redirect_to auth_url
end
I then have a method to take care of the callback.
def oauth_callback
db_client = Databasedotcom::Client.new
db_client.authenticate(:token => params[:code])
puts db_client.inspect
end
The error in the console is:
ArgumentError (ArgumentError):
app/controllers/users_controller.rb:60:in `oauth_callback'
The line that is causing the error is:
db_client.authenticate(:token => params[:code])
like the token that I am getting is invalid or something.
It worked fine until I changed my Salesforce password (which they required me to do). What am I missing? Thanks for the help.
If the response you receive is that your refresh token is no longer valid then you need to restart the OAuth process from scratch to obtain a new refresh token; you can then use to get new session tokens in subsequent uses of the app as you have been up until now.
Essentially, start the process as you would for the very first time the app is launched.

For every request a new session is getting generated in Yii application

I know I am either skipping something or configured session incorrectly but Yii sessions are not working for me. I have spent a lot of time in debugging and searching but it doesn't result in any concrete answer.
As described in documentation as well as tutorials over internet I have configured my application session as follows:
'components'=>array(
'user'=>array(
// enable cookie-based authentication
'allowAutoLogin'=>true,
),
'session' => array (
'sessionName' => 'Site Session',
'class'=>'CHttpSession',
'useTransparentSessionID' =>($_POST['PHPSESSID']) ? true : false,
'autoStart' => 'true',
'cookieMode' => 'allow',
'timeout' => 300
),
However each time I am sending a request to server, I get a new session object. I have verified same via echo "Session id: ".Yii::app()->session->sessionID;, every time it gives me different id. Also variables which I have added in session previously are not accessible due to this behaviour.
Kindly provide some pointers, I have spent more than 4 hours in debugging and looking for a solution. Tons of thanks for any pointers in advance.
Thanks
~Tarun
It could well be just that you have a space in your sessions name.
I've just done a quick test on my working Yii instance, changed the session name to have a space in it, and the cookie value for the session seems to change every time.
Please read php session name documentation at this url http://php.net/manual/en/function.session-name.php
It clearly mentions that session name should contain only alphanumerical characters. That too it should contain at least one alphabet(session name cannot have all its characters as digits also). Otherwise a new session id is generated every time.
chrome 44 and chrome 47's bug , update it to 51,It's ok.
Just a note cause I ran into this issue in Yii2. I had a constant COOKIE_DOMAIN that was set via php-fpm config and it was for the wrong domain name, causing the session to reset. Make sure this is set to ".example.com" (including the . at the start to support all your hostnames)
'components'=>[
'session' => [
'class' => 'yii\web\DbSession',
'cookieParams' => [
'path' => '/',
'domain' => COOKIE_DOMAIN, // <<<--- check this
'secure' => true,
],
'writeCallback' => function($session){
return [
'user_id' => Yii::$app->user->id
];
},
'sessionTable' => 'session', // session table name. Defaults to 'session'.
],
...
]

cookie expiration time with activerecord session store

This question is a follow-up to this. I can't seem to change the expiration time on the cookie when I switched to ActiveRecord session store. It contains just the session_id like it should, but its expiration time is set to HTTP session. I tried setting it in application.rb:
config.session_store :cookie_store, {
:expire_after => 2.hours,
}
But it doesn't do anything.
I could hack it by creating an additional cookie and storing a session_id there, but that seems wrong.
Nevermind, expiry of the cookie can be set by configuring ActiveRecord Session Store:
AppName::Application.config.session_store :active_record_store,
:key => 'your_cookie',
:expire_after => 2.hours