Keep session data set after logout in magento 2 - session

I try to find a way to disconnect a customer in magento 2 and to set data in the magento session.
Logout function well with $this->_customerSession->logout();
I set my data with $this->_perso->addSessionTmpUserId($id_reportage); It set data with Magento\Customer\Model\Session;
My problem is when I logout and set data direct after , I got my data in session
But if I refresh the page without sending any data, the data session is empty.
If I'm not logged in and I set data in session It function without problem
Any idea How to keep the set session data after logout ?
<?php
namespace Company\Illico\Controller\Index;
use Magento\Framework\App\Action\Action;
class Index extends Action
{
/**
* #var \Magento\Customer\Model\Session
*/
protected $_customerSession;
/**
* #var \North\Perso\Helper\Customer
*/
protected $_perso;
/**
* #param \Noveo\perso\Helper\Customer $perso
*/
public function __construct(
\Noveo\perso\Helper\Customer $perso,
\Magento\Customer\Model\Session $customerSession,
\Magento\Framework\App\Action\Context $context
)
{
$this->_perso = $perso;
$this->_customerSession = $customerSession;
return parent::__construct($context);
}
public function execute()
{
$reportage=$this->getRequest()->getParam('reportage');
$id_reportage=$this->getRequest()->getParam('id_reportage');
$customer_id=$this->_customerSession->getCustomerId();
if(isset($id_reportage)){
if(isset($customer_id)){
$this->_customerSession->logout();
}
$this->_perso->addSessionTmpUserId($id_reportage);
}
$this->_view->loadLayout();
$this->_view->getLayout()->initMessages();
$this->_view->renderLayout();
}
}

Related

How can I prevent Laravel from setting a session cookie when the user is not auth?

By default, Laravel sets a Cookie called [APP_NAME]_session on every request. It's used for features as redirect()->back().
This cookie prevents my cache mechanism to work properly (FastCGI, Varnish, you name it)
If I'm one hundred percent sure I won't need it, is there a way to remove this cookie when the user is not auth, without preventing them to log in as usual ?
I'd like to show a different menu when my user is authed, so I can't apply a different middleware on some routes.
I created a new class, which extends the StartSession Middleware (referenced in app/Middleware/Kernel.php, inside the web group).
<?php
namespace App\Http\Middleware;
use Illuminate\Contracts\Session\Session;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;
use Symfony\Component\HttpFoundation\Response;
class StartSession extends \Illuminate\Session\Middleware\StartSession
{
/**
* Start the session for the given request.
*
* #param Request $request
* #param Session $session
* #return Session
*/
protected function startSession(Request $request, $session): Session
{
return tap($session, function ($session) use ($request) {
$session->setRequestOnHandler($request);
if (Cookie::get(config("session.cookie"))) {
$session->start();
}
});
}
/**
* Add the session cookie to the application response.
*
* #param Response $response
* #param Session $session
* #return void
*/
protected function addCookieToResponse(Response $response, Session $session)
{
if (!auth()->check()) {
return;
}
if ($this->sessionIsPersistent($config = $this->manager->getSessionConfig())) {
$response->headers->setCookie(new \Symfony\Component\HttpFoundation\Cookie(
$session->getName(), $session->getId(), $this->getCookieExpirationDate(),
$config['path'], $config['domain'], $config['secure'] ?? false,
$config['http_only'] ?? true, false, $config['same_site'] ?? null
));
}
}
}
The two importants part are :
in startSession() :
if (Cookie::get(config("session.cookie"))) {
$session->start();
}
This part prevents the session from being created when the user wasn't already authed.
in addCookieToResponse() :
if (!auth()->check()) {
return;
}
This part prevents Laravel from setting the cookie as long as the user is not authed.

How does the Session table records delete itself?

I'm working with the Session table in Laravel and I just don't see how these records delete themselves after some time.
I haven't found any comprehensive guide on how the Session table works.
Here's my code so far:
SessionHandler.php
<?php
namespace App\Extensions;
class SessionHandler implements \SessionHandlerInterface
{
public function open($savePath, $sessionName) {}
public function close() {}
public function read($sessionId) {}
public function write($sessionId, $data) {}
public function destroy($sessionId) {}
public function gc($lifetime) {}
}
App\Session.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
class Session extends Model
{
protected $hidden = ['payload'];
/**
* The database table used by the model.
*
* #var string
*/
public $table = 'sessions';
public $timestamps = false;
/**
* Returns the user that belongs to this entry.
*/
public function user()
{
return $this->belongsTo('User');
}
/**
* Returns all the guest users.
*
* #param $query
* #return \Illuminate\Database\Eloquent\Builder
*/
public function scopeGuests($query)
{
return $query->whereNull('user_id')->where('last_activity', '>=', strtotime(Carbon::now()->subMinutes(25)));
}
/**
* Returns all the registered users.
*
* #param $query
* #return \Illuminate\Database\Eloquent\Builder
*/
public function scopeRegistered($query)
{
return $query->whereNotNull('user_id')->where('last_activity', '>=', strtotime(Carbon::now()->subMinutes(25)))->with('user');
}
/**
* Updates the session of the current user.
*
* #param $query
* #return \Illuminate\Database\Eloquent\Builder
*/
public function scopeUpdateCurrent($query)
{
return $query->where('id', Session::getId())->update([
'user_id' => ! empty(Auth::user()) ? Auth::id() : null
]);
}
}
AppServiceProvider.php
Session::extend('handler', function ($app) {
// Return implementation of SessionHandler
return new SessionHandler;
});
.env
SESSION_LIFETIME = 1
session.php
'lifetime' => env('SESSION_LIFETIME', 1),
'expire_on_close' => false,
What I'm basically trying to do is show each Guests/Users activity, but once their session/time limit is over -- POP! It deletes from the database too. Can anyone please share some insight on how to achieve this?
I think I just had to narrow down my search (or search better xD) --
You can set your session.php 'lifetime' value to however long you want the session to last -- and then for the 'lottery' value you can set it to 1,1 so that it fires every time a request is sent (I'm not sure of the performance effect of setting it to this) instead of the default 2,100. You probably should also change .env file SESSION_LIFETIME value to whenever you want it to expire (i.e. 1 for 1 minute).
So after 1 minute, on a request (via 'lottery' firing everytime), it deletes the session records with an expiry time of over one minute.

Conditionally redirect users after login in laravel backpack

I have some roles asigned to users. I would like to have a user redirected after login to different urls in order the role that user belongs to.
I have followed this post but it didn't work to me. I don't know if using backpack it would be different.
Best regards.
Edit.
This is the code in the login controller.
<?php
namespace Backpack\Base\app\Http\Controllers\Auth;
use Backpack\Base\app\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
class LoginController extends Controller{
protected $data = []; // the information we send to the view
protected $redirectTo = '/home';
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers {
logout as defaultLogout;
}
protected function authenticated(Request $request, $user){
/*if ( $user->isAdmin() ) {// do your margic here
return redirect('/home1');
}*/
return redirect('/myhome');
}
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$guard = backpack_guard_name();
$this->middleware("guest:$guard", ['except' => 'logout']);
// ----------------------------------
// Use the admin prefix in all routes
// ----------------------------------
// If not logged in redirect here.
$this->loginPath = property_exists($this, 'loginPath') ? $this->loginPath
: backpack_url('login');
// Redirect here after successful login.
$this->redirectTo = property_exists($this, 'redirectTo') ? $this->redirectTo
: backpack_url('dashboard');
// Redirect here after logout.
$this->redirectAfterLogout = property_exists($this, 'redirectAfterLogout') ? $this->redirectAfterLogout
: backpack_url();
}
/**
* Return custom username for authentication.
*
* #return string
*/
public function username()
{
return backpack_authentication_column();
}
/**
* Log the user out and redirect him to specific location.
*
* #param \Illuminate\Http\Request $request
*
* #return \Illuminate\Http\Response
*/
public function logout(Request $request)
{
// Do the default logout procedure
$this->guard()->logout();
// And redirect to custom location
return redirect($this->redirectAfterLogout);
}
/**
* Get the guard to be used during logout.
*
* #return \Illuminate\Contracts\Auth\StatefulGuard
*/
protected function guard()
{
return backpack_auth();
}
// -------------------------------------------------------
// Laravel overwrites for loading backpack views
// -------------------------------------------------------
/**
* Show the application login form.
*
* #return \Illuminate\Http\Response
*/
public function showLoginForm()
{
$this->data['title'] = trans('backpack::base.login'); // set the page title
$this->data['username'] = $this->username();
return view('backpack::auth.login', $this->data);
}
}
If I put this code in the path
vendor\backpack\base\src\app\Http\Controllers\Auth\LoginController.php
It works fine. But If I put the code in
app\Http\Controllers\Auth\LoginController.php
It does not work
I'm trying to extend the controller like this
use Backpack\Base\app\Http\Controllers\Auth\LoginController as OriginalLoginController;
class MyLoginController extends OriginalLoginController{
.....
}
To create a redirect in Laravel:
<?php
if($x){
return redirect()->route('routeName1', [$arr, $of, $params]);
}
else if($y){
return redirect()->route('routeName2', [$arr, $of, $params]);
}

Logging in a user?

I'm having trouble with logging users in, everything appears to be in the right place, I get no errors in the log, but users fail to log in, I am using the correct credentials that are in my database.
Please note I have a different set up to the normal one:
My table is called test_users
My model sits in a separate namespace called Test
Here's my code:
In config>auth I have set:
'model' => '\Test\User',
'table' => 'test_users',
Here is how I call the Auth:
public function logIn()
{
$input = Input::all();
$credentials = array('email' => $input['email'], 'password' => $input['password']);
$input['remember-me'] = isset($input['remember-me']) ? true : false;
if(Auth::attempt($credentials, $input['remember-me']))
{
$this->output['message'] = 'ok';
}
else
{
$this->output['message'] = 'fail';
}
return $this->output;
}
Here's my model:
<?php namespace Test;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
use Eloquent;
class User extends Eloquent implements UserInterface, RemindableInterface {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'test_users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password');
/**
* Get the unique identifier for the user.
*
* #return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the e-mail address where password reminders are sent.
*
* #return string
*/
public function getReminderEmail()
{
return $this->email;
}
}
Auth::attempt checks for a hashed password. It appears you might be trying to set them with plaintext. Try setting your passwords with Hash::make('password') if you aren't already.

Typo3 Extbase Set and Get values from Session

I am writing an extbase extension on typo3 v6.1
That extension suppose to do a bus ticket booking.
Here what my plan is, user will select date and number of seats and submit the form.
Here my plan to push the date and rate of the selected seat to session (Basket).
And while making payment, I wanted to get that values from session and after payment I need to clear that particular session.
So In short, How to Push and retrieve the values to and from the session in extbase.
Any suggestions ?
Thank you.
There are different ways. The simplest would be for writing in the session
$GLOBALS['TSFE']->fe_user->setKey("ses","key",$value)
and for reading values from the session
$GLOBALS["TSFE"]->fe_user->getKey("ses","key")
I'm using for this a service class.
<?php
class Tx_EXTNAME_Service_SessionHandler implements t3lib_Singleton {
private $prefixKey = 'tx_extname_';
/**
* Returns the object stored in the userĀ“s PHP session
* #return Object the stored object
*/
public function restoreFromSession($key) {
$sessionData = $GLOBALS['TSFE']->fe_user->getKey('ses', $this->prefixKey . $key);
return unserialize($sessionData);
}
/**
* Writes an object into the PHP session
* #param $object any serializable object to store into the session
* #return Tx_EXTNAME_Service_SessionHandler this
*/
public function writeToSession($object, $key) {
$sessionData = serialize($object);
$GLOBALS['TSFE']->fe_user->setKey('ses', $this->prefixKey . $key, $sessionData);
$GLOBALS['TSFE']->fe_user->storeSessionData();
return $this;
}
/**
* Cleans up the session: removes the stored object from the PHP session
* #return Tx_EXTNAME_Service_SessionHandler this
*/
public function cleanUpSession($key) {
$GLOBALS['TSFE']->fe_user->setKey('ses', $this->prefixKey . $key, NULL);
$GLOBALS['TSFE']->fe_user->storeSessionData();
return $this;
}
public function setPrefixKey($prefixKey) {
$this->prefixKey = $prefixKey;
}
}
?>
Inject this class into your controller
/**
*
* #var Tx_EXTNAME_Service_SessionHandler
*/
protected $sessionHandler;
/**
*
* #param Tx_EXTNAME_Service_SessionHandler $sessionHandler
*/
public function injectSessionHandler(Tx_EXTNAME_Service_SessionHandler $sessionHandler) {
$this->sessionHandler = $sessionHandler;
}
Now you can use this session handler like this.
// Write your object into session
$this->sessionHandler->writeToSession('KEY_FOR_THIS_PROCESS');
// Get your object from session
$this->sessionHandler->restoreFromSession('KEY_FOR_THIS_PROCESS');
// And after all maybe you will clean the session (delete)
$this->sessionHandler->cleanUpSession('KEY_FOR_THIS_PROCESS');
Rename Tx_EXTNAME and tx_extname with your extension name and pay attention to put the session handler class into the right directory (Classes -> Service -> SessionHandler.php).
You can store any data, not only objects.
HTH
From Typo3 v7 you can also copy the native session handler (\TYPO3\CMS\Form\Utility\SessionUtility) for forms and change it to your needs. The Class makes a different between normal and logged in users and it support multiple session data seperated by the sessionPrefix.
I did the same and generalized the class for a more common purpose. I only removed one method, change the variables name and added the method hasSessionKey(). Here is my complete example:
use TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController;
/**
* Class SessionUtility
*
* this is just a adapted version from \TYPO3\CMS\Form\Utility\SessionUtility,
* but more generalized without special behavior for form
*
*
*/
class SessionUtility {
/**
* Session data
*
* #var array
*/
protected $sessionData = array();
/**
* Prefix for the session
*
* #var string
*/
protected $sessionPrefix = '';
/**
* #var TypoScriptFrontendController
*/
protected $frontendController;
/**
* Constructor
*/
public function __construct()
{
$this->frontendController = $GLOBALS['TSFE'];
}
/**
* Init Session
*
* #param string $sessionPrefix
* #return void
*/
public function initSession($sessionPrefix = '')
{
$this->setSessionPrefix($sessionPrefix);
if ($this->frontendController->loginUser) {
$this->sessionData = $this->frontendController->fe_user->getKey('user', $this->sessionPrefix);
} else {
$this->sessionData = $this->frontendController->fe_user->getKey('ses', $this->sessionPrefix);
}
}
/**
* Stores current session
*
* #return void
*/
public function storeSession()
{
if ($this->frontendController->loginUser) {
$this->frontendController->fe_user->setKey('user', $this->sessionPrefix, $this->getSessionData());
} else {
$this->frontendController->fe_user->setKey('ses', $this->sessionPrefix, $this->getSessionData());
}
$this->frontendController->storeSessionData();
}
/**
* Destroy the session data for the form
*
* #return void
*/
public function destroySession()
{
if ($this->frontendController->loginUser) {
$this->frontendController->fe_user->setKey('user', $this->sessionPrefix, null);
} else {
$this->frontendController->fe_user->setKey('ses', $this->sessionPrefix, null);
}
$this->frontendController->storeSessionData();
}
/**
* Set the session Data by $key
*
* #param string $key
* #param string $value
* #return void
*/
public function setSessionData($key, $value)
{
$this->sessionData[$key] = $value;
$this->storeSession();
}
/**
* Retrieve a member of the $sessionData variable
*
* If no $key is passed, returns the entire $sessionData array
*
* #param string $key Parameter to search for
* #param mixed $default Default value to use if key not found
* #return mixed Returns NULL if key does not exist
*/
public function getSessionData($key = null, $default = null)
{
if ($key === null) {
return $this->sessionData;
}
return isset($this->sessionData[$key]) ? $this->sessionData[$key] : $default;
}
/**
* Set the s prefix
*
* #param string $sessionPrefix
*
*/
public function setSessionPrefix($sessionPrefix)
{
$this->sessionPrefix = $sessionPrefix;
}
/**
* #param string $key
*
* #return bool
*/
public function hasSessionKey($key) {
return isset($this->sessionData[$key]);
}
}
Don't forget to call the initSession first, every time you want use any method of this class

Resources