I have a login function. When I login, the session gets saved. But when I refresh the page or redirect to another function, then the session (userdata) is shown blank. I have loaded the session library in autoload, but the userdata is deleted after every page refresh.
Here is my code.
public function index () {
$user = $this->input->post('user');
// after successful user checking
$this->session->set_userdata('user', $user);
// when I print session here,
print_r($this->session->all_userdata());
// session user gets print
}
But when I redirect to a function (suppose 'test'), then no any session is shown.
public function test() {
print_r($this->session->all_userdata());
die;
}
When you read the post value with $this->input->post('user'); and there isn't any post the function returns null and save this in the user value.
You have to check before setting.
if ($this->input->post('user')) {
$this->session->set_userdata('username', $this->input->post('user'));
}
I solved the problem. Actually, accidentally I had destroyed the session at the beginning of the code. So, my session was all destroyed. I removed the code and it's working fine.
Related
I'm having trouble updating session values using Inertia.js. The behavior I was expecting was that the redirect to 'Home' would happen only once. Once the session gets cleared, any page reloads would go into 'Nok.' But that's not what happens. The $request->session()->forget(['ok']); is not persisted and always falls back to 'Home'. How do I get the expected behavior?
Example
public function home(Request $request)
{
$ok = $request->getSession()->get('ok', null);
if ($ok) {
$request->session()->forget(['ok']);
return Inertia::render('Home', [...]);
} else {
return Inertia::render('Nok', [...]);
}
}
When the user press the reset button on the filter, I want to delete the cookie that I previously created to save the user inputs and redirect to the same page "/search/influencers". I have searched all over stackoverflow and none of the listed ways to delete the cookie works. Please help!
/**
* resets the cookie that holds previous filter query
*/
public function resetFilter(Request $request){
if(Cookie::has('if_query_pref')) {
Cookie::queue(
Cookie::forget('if_query_pref')
);
}
return redirect()->route('influencerSearch'); //change the expiration time
}
Your code seems like fine, Please check that after removing cookie, it shouldn't reassign cookie.
I have used following code to remove cookie.
public function resetFilter(Request $request){
return redirect()->route('/influencerSearch')->withCookie(Cookie::forget('if_query_pref'));
}
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?
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.
I'm using AJAX in my web-app stuffs like search but if the user has been logged out, the ajax function return nothing because the redirection (from the action 'search' to the action 'login') has not been handled correctly.
Is it possible to redeclare the method 'redirect' in AppController to render the right action when a redirect hapend in an AJAX call ?
Thank you,
Sébastien
I think your best bet would be to setup you ajax to call to respond correctly to an invalid response. As it seems to be an important part of your app I would pass a 'loggedin' variable with every ajax request, so the client can tell as soon as the user has been logged out.
Update
In the case you want to keep a user logged in, you simply have to put the logged in/cookie check in something like your AppController::beforeFilter() that gets run with every request. for example:
public function beforeFilter() {
if($this->Auth->user() {
// USer is logged in, it's all gravy
} else {
// User is not logged in, try to log them in
$userData = $this->Cookie->read('User');
if(!empty($userData)) {
// Function that grabs info from cookie and logs in user
}
}
}
This way there will be no redirect as the user will be logged in as long as they have a cookie.
Another approach would be to allow everyone access to the Ajax function:
public function beforeFilter() {
$this->Auth->allow(array('my_ajax_method'));
}
And then check the user is authenticated in the method itself:
public function my_ajax_method() {
if (!$this->Auth->user()) {
//user not authenticated
$result = "requires auth";
}
else {
// use is authenticated
// do stuff
$result = 'result of stuff';
}
$this->set(compact('result'));
}
You will need to check the result of the ajax call in your javascript and act accordingly.
In my code, I have logout function as below
function logout()
{
$this->session->sess_destroy();
// but, don't destroy this session
$this->session->userdata('admin_id');
}
How to destroy all session, except 'admin_id'?
The Session destroy in CI is performed at the next request, so you can't destroy a session and open a new session without a request in between.
But you could unset all session data except the data you like to keep and the data Codeigniter needs to keep the session. This Depends how session is configured, by default is it the User Agent, the last activity and the session ID. See CI-Session class preferences (at bottom of page)
This function deletes all session data except the admin_id
$sessionData = $this->session->all_userdata();
foreach($sessionData as $key =>$val){
if($key!='session_id'
&& $key!='last_activity'
&& $key!='ip_address'
&& $key!='user_agent'
&& $key!='admin_id'){
$this->session->unset_userdata($key);
}
}
You might want to save the admin_id temporarily and just put it back to session after you destroyed all your session vars.
$temp = $this->session->userdata('admin_id');
$this->session->sess_destroy();
$this->session->set_userdata('admin_id', $temp);
you must save some of keys in session, here is correct code.
$sess_array = $this->session->all_userdata();
foreach($sess_array as $key =>$val){
if($key!='session_id'
&& $key!='last_activity'
&& $key!='ip_address'
&& $key!='user_agent'
&& $key!='RESERVER_KEY_HERE')$this->session->unset_userdata($key);
}
This will work for you :)
$this->session->sess_destroy(); destroys the session_id and last_activity of the session. So the session no longer exist. So this wont work.
Try this:
$sess_array = $this->session->all_userdata();
foreach($sess_array as $key =>$val){
if($key!='session_id'||$key!='last_activity'||$key!='admin_id'){
$this->session->unset_userdata($key);
}
}