Laravel 5.5 Sessions not saving after using Paypal - php

I have checked several questions already and tried everything but it did not help.
I want to use Laravel Sessions to store some data but they don't persist.
The code is something like this:
public function payment (Request $request)
{
$data = "somedata";
$provider = new Provider();
$request->session()->put("data",$data);
$request->session()->put("provider",$provider);
$response = $provider->setExpressCheckout($data);
return redirect($response['paypal_link']);
}
This happens when I open, let's say www.mypage.com/pay
When I use dd($request->sesion()->all()); here, the session has been saved.
Now the user gets redirected to Paypal, does the check out and it gets redirected somewhere in my application.
public function aferpay(Request $request)
{
dd($request->sesion()->all());
}
When this function gets called, the previous url is fine "url" => "www.mypage.com/pay" even though it comes from Paypal, but the rest of the data is not there anymore.
Any help?

Check your session config for any oversights, especially the session domain.
Make sure the session driver is working, and if you are using file sessions make sure the session directory is writable and there's enough free disk space.
Finally, msure you are not accessing mypage.com/pay without www first, and paypal redirects to www.mypage.com/pay and the session doesn't stick because of that - setting .mypage.com as the session domain will fix this.
If all else fails, please attach the set-cookie response headers of your mypage.com/pay page.

Related

Session not writing when redirecting

EDIT:
I've found the problem, this has been done in some legacy code and for some reason there was a session_write_close() call in a different part of the code which closed the session before i wrote to the session.
I've been making a little php class to write to the session(mostly for single request things) and i've been having trouble writing to the session.
When i write to the session it looks like it's working and i can see it in xdebug, then i try to redirect back to the other page but when i get into the new request it is not saved to the session.
I write to the session like this:
public function flash($key, $value = null)
{
if (is_null($value)) {
return $this->flash[$key];
}
$_SESSION['flash'][$key] = $value;
}
and then redirect like this:
session_write_close();
header('Location: ' . $location, true, $status);
exit;
I can't seem to figure out why the session variable doesn't save, the session_write_close() function returns false so i know it isn't saving. But when i don't use the redirect it does save.
EDIT: the session gets started on every request using session_start()
I hope someone knows what might be happening and can help me.
Thanks in advance :)
EDIT:
With session_status() i get a return value of 1 which according to the documentation means PHP_SESSION_NONE or sessions are enabled, but none exists but i can see that other session values have been set and saved.
I've checked the session id and if it is the same as the one in my cookies, these are identical. I've also tries writing to the session outside the class/method and that also seems to work and i tried to set the header without the statuscode to see if that changed something but it doesn't.

Logging out one browser session from another browser - LARAVEL 5.2

I am tracking the login history of a user in my website, and for that I need to display if there is any other session open in another browser or device. Plus, I need to provide a functionality wherein a user can logout a session that is open in a different browser/device from the current session. I am using redis-server. The things which I have done so far are as follows.
In the .env file, I have updated the CACHE_DRIVER and SESSION_DRIVER to redis.
In session.php and cache.php, I have set driver to redis.
Next, at the time of login, I connect to the redis server and store the session id for a specific user.
$redis = Redis::connection();
$redis->sadd('user:sessions:'. Auth::user()->id, $session_id);
Once this is done, I can see the multiple session id's per user using redis-cli command.
> SMEMBERS user:sessions:1
> "95008658737a7f937c614bccbb748443a649c515"
> "f1f14db9b1760254a4072fe9b440f9acbacc8974"
> GET laravel:95008658737a7f937c614bccbb748443a649c515
> "s:332:\"a:5:{s:6:\"_token\";s:40:\"HAuA200irzF63fgFw4vCVkrsZNuqTk6o2XLkHzlu\";s:9:\"_previous\";a:1:{s:3:\"url\";s:33:\"http://localhost:8000/security\";}s:5:\"flash\";a:2:{s:3:\"old\";a:0:{}s:3:\"new\";a:0:{}}s:50:\"login_web_59ba36addc2b2f9401580f014c7f58ea4e30989d\";i:1;s:9:\"_sf2_meta\";a:3:{s:1:\"u\";i:1464957596;s:1:\"c\";i:1464957416;s:1:\"l\";s:1:\"0\";}}\";"
This output makes me assume that the redis option for storing sessions in laravel is working fine.
Next, for logging out a user from a specific session, I am using the following set of instructions:
public function logoutSession($session_id) {
$redis = Redis::connection();
$redis->del('laravel:' . $session_id);
$redis->srem('user:sessions:' . Auth::user()->id, $session_id);
}
Once this function is called, the corresponding session id is successfully deleted.
Running the SMEMBERS and GET commands again in redis-cli proves it.
So the scenario is, I try to delete a session opened in say, Firefox from another browser say, Chrome. Cliking on the logout link (for Firefox session from Chrome session) deletes the Firefox session from redis-server successfully, but if I try to refresh the Firefox browser, I am still logged in.
Just an image displaying the functionality I am trying to achieve
I cannot understand where I am going wrong exactly. Any sort of help will be highly appreciated.
Thanks
NOTE: I am already using the 'auth' middleware, so that cannot be the problem. Plus, if I try to debug the code, I am seeing different session_ids in $_COOKIE variable and http request variable. Is this normal?
I had a similar issue once myself. I was frustrating myself with cache invalidation etc... and then after going through the "log in" process again I had forgotten to check for the "remember me" cookie.
https://laravel.com/docs/master/authentication#remembering-users
Turns out I had cleared the Cache successfully, but needed to call:
Auth::logout();
In order to remove the "remember_token" from the database. Otherwise, Laravel sees this as a valid way to reboot the Auth system, logging the user back in and setting a new session cookie.
Using your code:
public function logoutSession($session_id) {
$redis = Redis::connection();
$redis->del('laravel:' . $session_id);
$redis->srem('user:sessions:' . Auth::user()->id, $session_id);
Auth::logout();
}
But this logs out from ALL sessions, including the one you're working with.
For your problem, I propose using the Auth::viaRemember() method to determine if the client creating the request along with the cookie is the one you're currently operating with. It differentiates between your current session cookie and a "remember me" cookie:
if (Auth::viaRemember())
{
// Check Redis for session info
// Do something if not found, otherwise just proceed
}
**EDIT**: I found this after posting my answer: Laravel Auth::logout not removing remember me cookie
So to recap:
if (Auth::viaRemember())
{
if (!Redis::get($key))
{
// Get remember_me cookie name
$rememberMeCookie = Auth::getRecallerName();
// Tell Laravel to forget this cookie
$cookie = Cookie::forget($rememberMeCookie);
return Redirect::to('/')->withCookie($cookie);
}
}

YII2 AuthClient onAuthSuccess session Not Saving

Hope someone could help me with this issue.
We are using AuthClient for Social Signup and Login. Feature is working fine locally on Windows XAMPP (PHP 5.6) but on the server (Amazon Ec2 AMI, PHP 5.6), code is not saving session data.
public function onAuthSuccess($client)
{
//.... COMMENTED CODE
$session = Yii::$app->session;
//Store social info in session
$session['socialClient'] = $_GET['authclient'];
return;
}
When we are trying to access the session data set in the above function in the following Controller Action, the session data is never saved.
Weirdly after hours of research, if we use the PHP standard header() and exit() then it all works, fine.
header("Location: " . $authObj->getSuccessUrl());
exit();
I have tried all the combination, but still no luck.
e.g. return $this->redirect()
I am not sure if its a PHP issue or something to do with YII2 session handling. There are few other screens, where I believe the session is not saving as client has logged few bugs recently related to data loss, while the code logic is fine and works locally.
Any help would be of great help.
Thanks
Try using $session->open();
to open a session first before assigning some values.
Therefore, your code should be like:
`public function onAuthSuccess($client)
{
$session = Yii::$app->session;
$session->open();//Open session.
//Store social info in session
$session['socialClient'] = $_GET['authclient'];
return;
}
You said onAuthSuccess() is an action right? If yes then please use actionOnAuthSuccess(). This might be the reason you are not getting the values in the session because this action was never found.
In their example:
public function successCallback($client)
{
$attributes = $client->getUserAttributes();
// user login or signup comes here
}
Your code:
//Store social info in session
$session['socialClient'] = $_GET['authclient'];
It's a callback function, you wouldn't get any parametes from $_GET.
You may use the variable '$client' to get some data.

Laravel login bypass clears Session on first redirect

Here's my issue. When I use the login form to login, my user is able to navigate within the application with no issues with a saved session.
What I'm trying to do is create a different path to login without credentials. For example, going to /login_for_mike, I store a session with the username (bypassing any login) and then redirect them to the homepage.
The odd part is, on that redirect the session is clear and kicks me out of the application.
Now if I go back to /login_for_mike a second time. It seems the session has been created and I'm good.
Something on that first redirect is not carrying over my session and after the fact, it creates a new session and then it persists.
Is there something I'm missing, or something that Laravel is skipping the first time when I hit that open route?
Here is how we handle our login:
1) User submits login form.
2) We process form by checking with our ldap server. If suucessful, we store a session variable user. Then we redirect to homepage. If session variable is not set (middleware) - kick user to login page.
Other path:
1) Using a different route, we bypass the ldap check and login form.
2) We use the same code as above, however when we store the session, the middle ware checks the session and it is completely clear and kicks user to login form.
3) Now if I hit this route AGAIN, it checks the session and user is THERE! and they can proceed.
It seems, something different happens when I hit the login form, that doesnt happen when I bypass the form.
This is the pseudo code:
Routes:
Route::post('ldap', 'LdapController#ldap'); //Form posts here
Route::get('login_for_mike', 'LdapController#bypass_login');
LdapController
function ldap() {
process_ldap($request->input('email'), $request->input('password')); //Works perfectly
}
function bypass_login() {
process_ldap('mike#email.com', 0, 1);
}
function process_ldap($user,$pass,$bypass=false)
{
if (!$bypass)
{
$return = check_with_ldap_if_this_valid($user,$pass);
if (!$return)
Redirect::to('/login')->withErrors('Wrong credentials')->send();
}
Session::put('user', $user);
Redirect::to('home-page')->send(); //This works when entering through /login/for/mike but fails on middleware for session check
}
Middleware that fails when entering through /login_for_mike
But works if I try to hit it again after the first fail
public function handle($request, Closure $next)
{
$user=Session::get('user'); //No session when entering though /login_for_mike
if(!$user){
return redirect('login');
}
return $next($request);
}
As we discussed, in theory your logic is sound, but you need to make sure the controller eventually returns something.
Thus, I would rewrite your code as:
protected function ldap()
{
return $this->process_ldap($request->input('email'), $request->input('password'));
}
protected function bypass_login()
{
return $this->process_ldap('mike#email.com', 0, 1);
}
private function process_ldap($user, $pass, $bypass = false)
{
if (!$bypass) {
$return = check_with_ldap_if_this_valid($user,$pass);
if (!$return) {
return redirect('/login')->withErrors('Wrong credentials');
}
}
Session::put('user', $user);
return redirect('home-page');
}
(Although since I was not able to reproduce your problem exactly, I am not able to explain how this directly caused your issue, but again your logic does make sense so if you call everything the way it should be used, it should work.)
This is unlikely, but I've seen it once before with hard to debug login issues. The send() method is flushing output, and that might be telling the browser to start another connection before the session is written to the file. The next request is sent from the browser while the session is being written to, the session is unserialized uncleanly, and you have nothing in your session at all, completely blank. The next request should read the session properly from the initial request no matter if you go back to the login-for-mike or not.
To test this var_dump $_SESSION() on the login page.
OR
add session_write_close() before any redirect send().

Login not working sometime in cakephp

I have customers_contoller.php in frontend
function login() {
if(!empty($this->data)) {
# Call function from Customer to insert Registration Data
$loginData = ClassRegistry::init('Customer')->checkLogin($this->data['email'], $this->data['password']);
if(isset($loginData) && !empty($loginData)) {
$this->Session->write('Session.userid',$loginData['Customer']['id']);
$this->Session->write('Session.email',$loginData['Customer']['email']);
$this->redirect(HTTP_PATH."my-profile");
exit;
} else {
$this->Session->setFlash('Please enter valid Username/Password','default',array('class'=>'flash_bad'));
$this->redirect(HTTP_PATH."customer/login");
exit;
}
}
}
and in model customer.php,
function checkLogin($email,$password) {
$loginData = $this->find('first', array('conditions' => array('Customer.email' => $email, 'Customer.password' => sha1($password), 'Customer.is_active' => 'Yes')));
return $loginData;
}
most of time Login working fine, but sometime login not working and also doesn't get Error Message. Only refresh page every time on login.
I have just check all this things i found that when i can't login in my website at that time browser's cache show '/app/' for Session path but i have set actual Session path in before_filter() function in app_controller.php using $this->Session->path = '/';
I just remove all the browser's cache and try for login, now it is working fine.
Can anyone explain me what is the issue?
it occurs randomly so i can't find root of the issue.
Possible reason of your problem is that Session is lost because of improper Cookie Path transmitted to browser. It may be happened randomly because of mixing of Session binding strategies of PHP (like by GET-parameter or by Cookies).
You have wrongly set up $this->Session->path parameter. It maps to session.cookie_path option of PHP. See quite similar example in this post.
session.cookie_path should exclude protocol, host and eventually port, so leave just root of you website '/':
$this->Session->path = '/';
See also description of Domain and Path options of cookies.
EDIT: In order to further investigate reason of Session misconfiguration, debug SessionComponent and CakeSession classes near $base argument passed to constructor:
/cake/libs/controller/components/session.php
/cake/libs/cake_session.php
I guess it was somehow passed wrongly, and you received /app/ cookie path in the browser.
For anyone else that may be interested, I had a similar problem on a new user's machine. It turned out that the machine was not syncing correctly with the internet time, and the machine had the date set to one day in the future. No errors were displayed, but the Auth session was destroyed on redirect, and I would always be redirected to the login page. Updating the time on the computer and restarting Chrome helped.
(Strangely, this wasn't a problem in Firefox.)

Categories