Programatically Log User Out [Magento 2]Logout by programming from observer in magento 2Keep products in shopping cart after customer logs outHow to customize the customer account after login according to user groupMagento 2.7 and 2.1.1 - While changing the password form the my account page User group changed to default customer groupHow to remove “NOT LOGGED IN” valueHow to get old id of customer group in observer (Magento 2)Magento 2.1 - User Group Registration FormMagento 2 - Redirect to Account Dashboard During Checkout Funnel LoginHow Do You Invalidate Customer Data In Magento 2?Recently viewed products not showing for NOT LOGGED CUSTOMERS in magento 2Magento 2 Customer and admin users are getting logged out frequently
Does a code snippet compile? Or does it gets compiled?
Can an SPI slave start a transmission in full-duplex mode?
Why should public servants be apolitical?
Dereferencing a pointer in a for loop initializer creates a seg fault
Can I call myself an assistant professor without a PhD
Double blind peer review when paper cites author's GitHub repo for code
Acceptable to cut steak before searing?
Is The Lion King live action film made in motion capture?
SQL Minimum Row count
Is this cheap "air conditioner" able to cool a room?
Looking for a new job because of relocation - is it okay to tell the real reason?
How can I tell if a flight itinerary is fake?
In a topological space if there exists a loop that cannot be contracted to a point does there exist a simple loop that cannot be contracted also?
Does the United States guarantee any unique freedoms?
Short story about a teenager who has his brain replaced with a microchip (Psychological Horror)
What happen if I gain the control of aura that enchants an opponent's creature? Would the aura stay attached?
Ex-contractor published company source code and secrets online
How to mark beverage cans in a cooler for a blind person?
Why are the inside diameters of some pipe larger than the stated size?
Does this smartphone photo show Mars just below the Sun?
Pretty heat maps
How do I explain to a team that the project they will work on for six months will 100% fail?
Generator for parity?
Use of "When" in present vs "whenever"
Programatically Log User Out [Magento 2]
Logout by programming from observer in magento 2Keep products in shopping cart after customer logs outHow to customize the customer account after login according to user groupMagento 2.7 and 2.1.1 - While changing the password form the my account page User group changed to default customer groupHow to remove “NOT LOGGED IN” valueHow to get old id of customer group in observer (Magento 2)Magento 2.1 - User Group Registration FormMagento 2 - Redirect to Account Dashboard During Checkout Funnel LoginHow Do You Invalidate Customer Data In Magento 2?Recently viewed products not showing for NOT LOGGED CUSTOMERS in magento 2Magento 2 Customer and admin users are getting logged out frequently
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
I have written a module which is basically an observer which triggers on 'customer_save_after_data_object
' the content of this observer basically listens out for when the customers group is changed.
The issue we are having is that if the customers' group is changed when they are logged in it doesn't seem to take effect, meaning that they need to log out of the account and then back in.
My question is, is there a way to log the customer out of their dashboard programmatically when I don't have direct access to the customer session and only the observer data?
magento2 magento-2.1 customer-account customer-group
add a comment |
I have written a module which is basically an observer which triggers on 'customer_save_after_data_object
' the content of this observer basically listens out for when the customers group is changed.
The issue we are having is that if the customers' group is changed when they are logged in it doesn't seem to take effect, meaning that they need to log out of the account and then back in.
My question is, is there a way to log the customer out of their dashboard programmatically when I don't have direct access to the customer session and only the observer data?
magento2 magento-2.1 customer-account customer-group
you should get customer session in your observer, try this magento.stackexchange.com/questions/95558/…
– Kyrylo Romantsov
Sep 8 '17 at 7:56
add a comment |
I have written a module which is basically an observer which triggers on 'customer_save_after_data_object
' the content of this observer basically listens out for when the customers group is changed.
The issue we are having is that if the customers' group is changed when they are logged in it doesn't seem to take effect, meaning that they need to log out of the account and then back in.
My question is, is there a way to log the customer out of their dashboard programmatically when I don't have direct access to the customer session and only the observer data?
magento2 magento-2.1 customer-account customer-group
I have written a module which is basically an observer which triggers on 'customer_save_after_data_object
' the content of this observer basically listens out for when the customers group is changed.
The issue we are having is that if the customers' group is changed when they are logged in it doesn't seem to take effect, meaning that they need to log out of the account and then back in.
My question is, is there a way to log the customer out of their dashboard programmatically when I don't have direct access to the customer session and only the observer data?
magento2 magento-2.1 customer-account customer-group
magento2 magento-2.1 customer-account customer-group
edited Sep 8 '17 at 7:54
Amit Bera♦
62.8k16 gold badges84 silver badges183 bronze badges
62.8k16 gold badges84 silver badges183 bronze badges
asked Sep 8 '17 at 7:50
CreativeNerdSamCreativeNerdSam
438 bronze badges
438 bronze badges
you should get customer session in your observer, try this magento.stackexchange.com/questions/95558/…
– Kyrylo Romantsov
Sep 8 '17 at 7:56
add a comment |
you should get customer session in your observer, try this magento.stackexchange.com/questions/95558/…
– Kyrylo Romantsov
Sep 8 '17 at 7:56
you should get customer session in your observer, try this magento.stackexchange.com/questions/95558/…
– Kyrylo Romantsov
Sep 8 '17 at 7:56
you should get customer session in your observer, try this magento.stackexchange.com/questions/95558/…
– Kyrylo Romantsov
Sep 8 '17 at 7:56
add a comment |
3 Answers
3
active
oldest
votes
What you want is the CustomerTokenServiceInterface
In your constructor:
use MagentoIntegrationApiCustomerTokenServiceInterface;
// ...
/** @var CustomerTokenServiceInterface */
private $tokenService;
public function __construct(CustomerTokenServiceInterface $tokenService)
$this->tokenService = $tokenService;
In your code:
$this->tokenService->revokeCustomerAccessToken($customerId);
You can see an example of this in MagentoCustomerControllerAdminhtmlCustomerInvalidateToken
which is the action called by the "Force Sign-In" button for customers in the admin panel.
Don't forget to add <module name="Magento_Integration" />
to your sequence file, and magento/module-integration
in your module's composer.json requirements!
Thanks Navarr, unfortunately this doesn't seem to do the job either. The user continues to be logged in which is a little strange.
– CreativeNerdSam
Sep 8 '17 at 13:19
Even when clicking the force log-in button it still doesn't kick the user out.
– CreativeNerdSam
Sep 8 '17 at 13:32
add a comment |
Try this code.
<?php
namespace PackageModulenameModel;
use MagentoCustomerApiAccountManagementInterface;
use MagentoFrameworkExceptionLocalizedException;
use MagentoIntegrationModelCredentialsValidator;
use MagentoIntegrationModelOauthToken as Token;
use MagentoIntegrationModelOauthTokenFactory as TokenModelFactory;
use MagentoIntegrationModelResourceModelOauthTokenCollectionFactory as TokenCollectionFactory;
use MagentoIntegrationModelOauthTokenRequestThrottler;
use MagentoFrameworkExceptionAuthenticationException;
class CustomerLogout implements PackageModulenameApiCustomerLogoutInterface
/**
* Token Model
*
* @var TokenModelFactory
*/
private $tokenModelFactory;
/**
* Customer Account Service
*
* @var AccountManagementInterface
*/
private $accountManagement;
/**
* @var MagentoIntegrationModelCredentialsValidator
*/
private $validatorHelper;
/**
* Token Collection Factory
*
* @var TokenCollectionFactory
*/
private $tokenModelCollectionFactory;
/**
* @var RequestThrottler
*/
private $requestThrottler;
/**
* Initialize service
*
* @param TokenModelFactory $tokenModelFactory
* @param AccountManagementInterface $accountManagement
* @param TokenCollectionFactory $tokenModelCollectionFactory
* @param MagentoIntegrationModelCredentialsValidator $validatorHelper
*/
public function __construct(
TokenModelFactory $tokenModelFactory,
AccountManagementInterface $accountManagement,
TokenCollectionFactory $tokenModelCollectionFactory,
CredentialsValidator $validatorHelper
)
$this->tokenModelFactory = $tokenModelFactory;
$this->accountManagement = $accountManagement;
$this->tokenModelCollectionFactory = $tokenModelCollectionFactory;
$this->validatorHelper = $validatorHelper;
/**
* @inheritdoc
*/
public function revokeCustomerAccessToken()
$customerId = 1;
$tokenCollection = $this->tokenModelCollectionFactory->create()->addFilterByCustomerId($customerId);
if ($tokenCollection->getSize() == 0)
throw new LocalizedException(__('This customer has no tokens.'));
try
foreach ($tokenCollection as $token)
$token->setRevoked(1)->save();
catch (Exception $e)
throw new LocalizedException(__('The tokens could not be revoked.'));
return true;
add a comment |
It will work. Pro-grammatically logout customer on observer.
<?php
/**
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace VendorModuleNameObserver;
use MagentoCustomerModelSession;
use MagentoFrameworkAppActionContext;
use MagentoFrameworkAppObjectManager;
use MagentoFrameworkStdlibCookieCookieMetadataFactory;
use MagentoFrameworkStdlibCookiePhpCookieManager;
use MagentoFrameworkEventObserverInterface;
class Logout implements ObserverInterface
/**
* @var Session
*/
protected $session;
/**
* @var CookieMetadataFactory
*/
private $cookieMetadataFactory;
/**
* @var PhpCookieManager
*/
private $cookieMetadataManager;
/**
* @param Context $context
* @param Session $customerSession
*/
public function __construct(
Context $context,
Session $customerSession,
CookieMetadataFactory $cookieMetadataManager
)
$this->session = $customerSession;
$this->cookieMetadataManager = $cookieMetadataManager;
parent::__construct($context);
/**
* Retrieve cookie manager
*
* @deprecated 100.1.0
* @return PhpCookieManager
*/
private function getCookieManager()
if (!$this->cookieMetadataManager)
$this->cookieMetadataManager = ObjectManager::getInstance()->get(PhpCookieManager::class);
return $this->cookieMetadataManager;
/**
* Retrieve cookie metadata factory
*
* @deprecated 100.1.0
* @return CookieMetadataFactory
*/
private function getCookieMetadataFactory()
if (!$this->cookieMetadataFactory)
$this->cookieMetadataFactory = ObjectManager::getInstance()->get(CookieMetadataFactory::class);
return $this->cookieMetadataFactory;
/**
* Customer logout action
*
* @return MagentoFrameworkControllerResultRedirect
*/
public function execute()
$lastCustomerId = $this->session->getId();
$this->session->logout()->setBeforeAuthUrl($this->_redirect->getRefererUrl())
->setLastCustomerId($lastCustomerId);
if ($this->getCookieManager()->getCookie('mage-cache-sessid'))
$metadata = $this->getCookieMetadataFactory()->createCookieMetadata();
$metadata->setPath('/');
$this->getCookieManager()->deleteCookie('mage-cache-sessid', $metadata);
/** @var MagentoFrameworkControllerResultRedirect $resultRedirect */
$resultRedirect = $this->resultRedirectFactory->create();
$resultRedirect->setPath('*/*/logoutSuccess');
return $resultRedirect;
This is the magento core logout functionality, we can use as per our wish. Just try.
add a comment |
Your Answer
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "479"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f192492%2fprogramatically-log-user-out-magento-2%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
What you want is the CustomerTokenServiceInterface
In your constructor:
use MagentoIntegrationApiCustomerTokenServiceInterface;
// ...
/** @var CustomerTokenServiceInterface */
private $tokenService;
public function __construct(CustomerTokenServiceInterface $tokenService)
$this->tokenService = $tokenService;
In your code:
$this->tokenService->revokeCustomerAccessToken($customerId);
You can see an example of this in MagentoCustomerControllerAdminhtmlCustomerInvalidateToken
which is the action called by the "Force Sign-In" button for customers in the admin panel.
Don't forget to add <module name="Magento_Integration" />
to your sequence file, and magento/module-integration
in your module's composer.json requirements!
Thanks Navarr, unfortunately this doesn't seem to do the job either. The user continues to be logged in which is a little strange.
– CreativeNerdSam
Sep 8 '17 at 13:19
Even when clicking the force log-in button it still doesn't kick the user out.
– CreativeNerdSam
Sep 8 '17 at 13:32
add a comment |
What you want is the CustomerTokenServiceInterface
In your constructor:
use MagentoIntegrationApiCustomerTokenServiceInterface;
// ...
/** @var CustomerTokenServiceInterface */
private $tokenService;
public function __construct(CustomerTokenServiceInterface $tokenService)
$this->tokenService = $tokenService;
In your code:
$this->tokenService->revokeCustomerAccessToken($customerId);
You can see an example of this in MagentoCustomerControllerAdminhtmlCustomerInvalidateToken
which is the action called by the "Force Sign-In" button for customers in the admin panel.
Don't forget to add <module name="Magento_Integration" />
to your sequence file, and magento/module-integration
in your module's composer.json requirements!
Thanks Navarr, unfortunately this doesn't seem to do the job either. The user continues to be logged in which is a little strange.
– CreativeNerdSam
Sep 8 '17 at 13:19
Even when clicking the force log-in button it still doesn't kick the user out.
– CreativeNerdSam
Sep 8 '17 at 13:32
add a comment |
What you want is the CustomerTokenServiceInterface
In your constructor:
use MagentoIntegrationApiCustomerTokenServiceInterface;
// ...
/** @var CustomerTokenServiceInterface */
private $tokenService;
public function __construct(CustomerTokenServiceInterface $tokenService)
$this->tokenService = $tokenService;
In your code:
$this->tokenService->revokeCustomerAccessToken($customerId);
You can see an example of this in MagentoCustomerControllerAdminhtmlCustomerInvalidateToken
which is the action called by the "Force Sign-In" button for customers in the admin panel.
Don't forget to add <module name="Magento_Integration" />
to your sequence file, and magento/module-integration
in your module's composer.json requirements!
What you want is the CustomerTokenServiceInterface
In your constructor:
use MagentoIntegrationApiCustomerTokenServiceInterface;
// ...
/** @var CustomerTokenServiceInterface */
private $tokenService;
public function __construct(CustomerTokenServiceInterface $tokenService)
$this->tokenService = $tokenService;
In your code:
$this->tokenService->revokeCustomerAccessToken($customerId);
You can see an example of this in MagentoCustomerControllerAdminhtmlCustomerInvalidateToken
which is the action called by the "Force Sign-In" button for customers in the admin panel.
Don't forget to add <module name="Magento_Integration" />
to your sequence file, and magento/module-integration
in your module's composer.json requirements!
answered Sep 8 '17 at 13:01
NavarrNavarr
1,0921 gold badge9 silver badges31 bronze badges
1,0921 gold badge9 silver badges31 bronze badges
Thanks Navarr, unfortunately this doesn't seem to do the job either. The user continues to be logged in which is a little strange.
– CreativeNerdSam
Sep 8 '17 at 13:19
Even when clicking the force log-in button it still doesn't kick the user out.
– CreativeNerdSam
Sep 8 '17 at 13:32
add a comment |
Thanks Navarr, unfortunately this doesn't seem to do the job either. The user continues to be logged in which is a little strange.
– CreativeNerdSam
Sep 8 '17 at 13:19
Even when clicking the force log-in button it still doesn't kick the user out.
– CreativeNerdSam
Sep 8 '17 at 13:32
Thanks Navarr, unfortunately this doesn't seem to do the job either. The user continues to be logged in which is a little strange.
– CreativeNerdSam
Sep 8 '17 at 13:19
Thanks Navarr, unfortunately this doesn't seem to do the job either. The user continues to be logged in which is a little strange.
– CreativeNerdSam
Sep 8 '17 at 13:19
Even when clicking the force log-in button it still doesn't kick the user out.
– CreativeNerdSam
Sep 8 '17 at 13:32
Even when clicking the force log-in button it still doesn't kick the user out.
– CreativeNerdSam
Sep 8 '17 at 13:32
add a comment |
Try this code.
<?php
namespace PackageModulenameModel;
use MagentoCustomerApiAccountManagementInterface;
use MagentoFrameworkExceptionLocalizedException;
use MagentoIntegrationModelCredentialsValidator;
use MagentoIntegrationModelOauthToken as Token;
use MagentoIntegrationModelOauthTokenFactory as TokenModelFactory;
use MagentoIntegrationModelResourceModelOauthTokenCollectionFactory as TokenCollectionFactory;
use MagentoIntegrationModelOauthTokenRequestThrottler;
use MagentoFrameworkExceptionAuthenticationException;
class CustomerLogout implements PackageModulenameApiCustomerLogoutInterface
/**
* Token Model
*
* @var TokenModelFactory
*/
private $tokenModelFactory;
/**
* Customer Account Service
*
* @var AccountManagementInterface
*/
private $accountManagement;
/**
* @var MagentoIntegrationModelCredentialsValidator
*/
private $validatorHelper;
/**
* Token Collection Factory
*
* @var TokenCollectionFactory
*/
private $tokenModelCollectionFactory;
/**
* @var RequestThrottler
*/
private $requestThrottler;
/**
* Initialize service
*
* @param TokenModelFactory $tokenModelFactory
* @param AccountManagementInterface $accountManagement
* @param TokenCollectionFactory $tokenModelCollectionFactory
* @param MagentoIntegrationModelCredentialsValidator $validatorHelper
*/
public function __construct(
TokenModelFactory $tokenModelFactory,
AccountManagementInterface $accountManagement,
TokenCollectionFactory $tokenModelCollectionFactory,
CredentialsValidator $validatorHelper
)
$this->tokenModelFactory = $tokenModelFactory;
$this->accountManagement = $accountManagement;
$this->tokenModelCollectionFactory = $tokenModelCollectionFactory;
$this->validatorHelper = $validatorHelper;
/**
* @inheritdoc
*/
public function revokeCustomerAccessToken()
$customerId = 1;
$tokenCollection = $this->tokenModelCollectionFactory->create()->addFilterByCustomerId($customerId);
if ($tokenCollection->getSize() == 0)
throw new LocalizedException(__('This customer has no tokens.'));
try
foreach ($tokenCollection as $token)
$token->setRevoked(1)->save();
catch (Exception $e)
throw new LocalizedException(__('The tokens could not be revoked.'));
return true;
add a comment |
Try this code.
<?php
namespace PackageModulenameModel;
use MagentoCustomerApiAccountManagementInterface;
use MagentoFrameworkExceptionLocalizedException;
use MagentoIntegrationModelCredentialsValidator;
use MagentoIntegrationModelOauthToken as Token;
use MagentoIntegrationModelOauthTokenFactory as TokenModelFactory;
use MagentoIntegrationModelResourceModelOauthTokenCollectionFactory as TokenCollectionFactory;
use MagentoIntegrationModelOauthTokenRequestThrottler;
use MagentoFrameworkExceptionAuthenticationException;
class CustomerLogout implements PackageModulenameApiCustomerLogoutInterface
/**
* Token Model
*
* @var TokenModelFactory
*/
private $tokenModelFactory;
/**
* Customer Account Service
*
* @var AccountManagementInterface
*/
private $accountManagement;
/**
* @var MagentoIntegrationModelCredentialsValidator
*/
private $validatorHelper;
/**
* Token Collection Factory
*
* @var TokenCollectionFactory
*/
private $tokenModelCollectionFactory;
/**
* @var RequestThrottler
*/
private $requestThrottler;
/**
* Initialize service
*
* @param TokenModelFactory $tokenModelFactory
* @param AccountManagementInterface $accountManagement
* @param TokenCollectionFactory $tokenModelCollectionFactory
* @param MagentoIntegrationModelCredentialsValidator $validatorHelper
*/
public function __construct(
TokenModelFactory $tokenModelFactory,
AccountManagementInterface $accountManagement,
TokenCollectionFactory $tokenModelCollectionFactory,
CredentialsValidator $validatorHelper
)
$this->tokenModelFactory = $tokenModelFactory;
$this->accountManagement = $accountManagement;
$this->tokenModelCollectionFactory = $tokenModelCollectionFactory;
$this->validatorHelper = $validatorHelper;
/**
* @inheritdoc
*/
public function revokeCustomerAccessToken()
$customerId = 1;
$tokenCollection = $this->tokenModelCollectionFactory->create()->addFilterByCustomerId($customerId);
if ($tokenCollection->getSize() == 0)
throw new LocalizedException(__('This customer has no tokens.'));
try
foreach ($tokenCollection as $token)
$token->setRevoked(1)->save();
catch (Exception $e)
throw new LocalizedException(__('The tokens could not be revoked.'));
return true;
add a comment |
Try this code.
<?php
namespace PackageModulenameModel;
use MagentoCustomerApiAccountManagementInterface;
use MagentoFrameworkExceptionLocalizedException;
use MagentoIntegrationModelCredentialsValidator;
use MagentoIntegrationModelOauthToken as Token;
use MagentoIntegrationModelOauthTokenFactory as TokenModelFactory;
use MagentoIntegrationModelResourceModelOauthTokenCollectionFactory as TokenCollectionFactory;
use MagentoIntegrationModelOauthTokenRequestThrottler;
use MagentoFrameworkExceptionAuthenticationException;
class CustomerLogout implements PackageModulenameApiCustomerLogoutInterface
/**
* Token Model
*
* @var TokenModelFactory
*/
private $tokenModelFactory;
/**
* Customer Account Service
*
* @var AccountManagementInterface
*/
private $accountManagement;
/**
* @var MagentoIntegrationModelCredentialsValidator
*/
private $validatorHelper;
/**
* Token Collection Factory
*
* @var TokenCollectionFactory
*/
private $tokenModelCollectionFactory;
/**
* @var RequestThrottler
*/
private $requestThrottler;
/**
* Initialize service
*
* @param TokenModelFactory $tokenModelFactory
* @param AccountManagementInterface $accountManagement
* @param TokenCollectionFactory $tokenModelCollectionFactory
* @param MagentoIntegrationModelCredentialsValidator $validatorHelper
*/
public function __construct(
TokenModelFactory $tokenModelFactory,
AccountManagementInterface $accountManagement,
TokenCollectionFactory $tokenModelCollectionFactory,
CredentialsValidator $validatorHelper
)
$this->tokenModelFactory = $tokenModelFactory;
$this->accountManagement = $accountManagement;
$this->tokenModelCollectionFactory = $tokenModelCollectionFactory;
$this->validatorHelper = $validatorHelper;
/**
* @inheritdoc
*/
public function revokeCustomerAccessToken()
$customerId = 1;
$tokenCollection = $this->tokenModelCollectionFactory->create()->addFilterByCustomerId($customerId);
if ($tokenCollection->getSize() == 0)
throw new LocalizedException(__('This customer has no tokens.'));
try
foreach ($tokenCollection as $token)
$token->setRevoked(1)->save();
catch (Exception $e)
throw new LocalizedException(__('The tokens could not be revoked.'));
return true;
Try this code.
<?php
namespace PackageModulenameModel;
use MagentoCustomerApiAccountManagementInterface;
use MagentoFrameworkExceptionLocalizedException;
use MagentoIntegrationModelCredentialsValidator;
use MagentoIntegrationModelOauthToken as Token;
use MagentoIntegrationModelOauthTokenFactory as TokenModelFactory;
use MagentoIntegrationModelResourceModelOauthTokenCollectionFactory as TokenCollectionFactory;
use MagentoIntegrationModelOauthTokenRequestThrottler;
use MagentoFrameworkExceptionAuthenticationException;
class CustomerLogout implements PackageModulenameApiCustomerLogoutInterface
/**
* Token Model
*
* @var TokenModelFactory
*/
private $tokenModelFactory;
/**
* Customer Account Service
*
* @var AccountManagementInterface
*/
private $accountManagement;
/**
* @var MagentoIntegrationModelCredentialsValidator
*/
private $validatorHelper;
/**
* Token Collection Factory
*
* @var TokenCollectionFactory
*/
private $tokenModelCollectionFactory;
/**
* @var RequestThrottler
*/
private $requestThrottler;
/**
* Initialize service
*
* @param TokenModelFactory $tokenModelFactory
* @param AccountManagementInterface $accountManagement
* @param TokenCollectionFactory $tokenModelCollectionFactory
* @param MagentoIntegrationModelCredentialsValidator $validatorHelper
*/
public function __construct(
TokenModelFactory $tokenModelFactory,
AccountManagementInterface $accountManagement,
TokenCollectionFactory $tokenModelCollectionFactory,
CredentialsValidator $validatorHelper
)
$this->tokenModelFactory = $tokenModelFactory;
$this->accountManagement = $accountManagement;
$this->tokenModelCollectionFactory = $tokenModelCollectionFactory;
$this->validatorHelper = $validatorHelper;
/**
* @inheritdoc
*/
public function revokeCustomerAccessToken()
$customerId = 1;
$tokenCollection = $this->tokenModelCollectionFactory->create()->addFilterByCustomerId($customerId);
if ($tokenCollection->getSize() == 0)
throw new LocalizedException(__('This customer has no tokens.'));
try
foreach ($tokenCollection as $token)
$token->setRevoked(1)->save();
catch (Exception $e)
throw new LocalizedException(__('The tokens could not be revoked.'));
return true;
answered Sep 8 '17 at 13:58
RaghavRaghav
15910 bronze badges
15910 bronze badges
add a comment |
add a comment |
It will work. Pro-grammatically logout customer on observer.
<?php
/**
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace VendorModuleNameObserver;
use MagentoCustomerModelSession;
use MagentoFrameworkAppActionContext;
use MagentoFrameworkAppObjectManager;
use MagentoFrameworkStdlibCookieCookieMetadataFactory;
use MagentoFrameworkStdlibCookiePhpCookieManager;
use MagentoFrameworkEventObserverInterface;
class Logout implements ObserverInterface
/**
* @var Session
*/
protected $session;
/**
* @var CookieMetadataFactory
*/
private $cookieMetadataFactory;
/**
* @var PhpCookieManager
*/
private $cookieMetadataManager;
/**
* @param Context $context
* @param Session $customerSession
*/
public function __construct(
Context $context,
Session $customerSession,
CookieMetadataFactory $cookieMetadataManager
)
$this->session = $customerSession;
$this->cookieMetadataManager = $cookieMetadataManager;
parent::__construct($context);
/**
* Retrieve cookie manager
*
* @deprecated 100.1.0
* @return PhpCookieManager
*/
private function getCookieManager()
if (!$this->cookieMetadataManager)
$this->cookieMetadataManager = ObjectManager::getInstance()->get(PhpCookieManager::class);
return $this->cookieMetadataManager;
/**
* Retrieve cookie metadata factory
*
* @deprecated 100.1.0
* @return CookieMetadataFactory
*/
private function getCookieMetadataFactory()
if (!$this->cookieMetadataFactory)
$this->cookieMetadataFactory = ObjectManager::getInstance()->get(CookieMetadataFactory::class);
return $this->cookieMetadataFactory;
/**
* Customer logout action
*
* @return MagentoFrameworkControllerResultRedirect
*/
public function execute()
$lastCustomerId = $this->session->getId();
$this->session->logout()->setBeforeAuthUrl($this->_redirect->getRefererUrl())
->setLastCustomerId($lastCustomerId);
if ($this->getCookieManager()->getCookie('mage-cache-sessid'))
$metadata = $this->getCookieMetadataFactory()->createCookieMetadata();
$metadata->setPath('/');
$this->getCookieManager()->deleteCookie('mage-cache-sessid', $metadata);
/** @var MagentoFrameworkControllerResultRedirect $resultRedirect */
$resultRedirect = $this->resultRedirectFactory->create();
$resultRedirect->setPath('*/*/logoutSuccess');
return $resultRedirect;
This is the magento core logout functionality, we can use as per our wish. Just try.
add a comment |
It will work. Pro-grammatically logout customer on observer.
<?php
/**
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace VendorModuleNameObserver;
use MagentoCustomerModelSession;
use MagentoFrameworkAppActionContext;
use MagentoFrameworkAppObjectManager;
use MagentoFrameworkStdlibCookieCookieMetadataFactory;
use MagentoFrameworkStdlibCookiePhpCookieManager;
use MagentoFrameworkEventObserverInterface;
class Logout implements ObserverInterface
/**
* @var Session
*/
protected $session;
/**
* @var CookieMetadataFactory
*/
private $cookieMetadataFactory;
/**
* @var PhpCookieManager
*/
private $cookieMetadataManager;
/**
* @param Context $context
* @param Session $customerSession
*/
public function __construct(
Context $context,
Session $customerSession,
CookieMetadataFactory $cookieMetadataManager
)
$this->session = $customerSession;
$this->cookieMetadataManager = $cookieMetadataManager;
parent::__construct($context);
/**
* Retrieve cookie manager
*
* @deprecated 100.1.0
* @return PhpCookieManager
*/
private function getCookieManager()
if (!$this->cookieMetadataManager)
$this->cookieMetadataManager = ObjectManager::getInstance()->get(PhpCookieManager::class);
return $this->cookieMetadataManager;
/**
* Retrieve cookie metadata factory
*
* @deprecated 100.1.0
* @return CookieMetadataFactory
*/
private function getCookieMetadataFactory()
if (!$this->cookieMetadataFactory)
$this->cookieMetadataFactory = ObjectManager::getInstance()->get(CookieMetadataFactory::class);
return $this->cookieMetadataFactory;
/**
* Customer logout action
*
* @return MagentoFrameworkControllerResultRedirect
*/
public function execute()
$lastCustomerId = $this->session->getId();
$this->session->logout()->setBeforeAuthUrl($this->_redirect->getRefererUrl())
->setLastCustomerId($lastCustomerId);
if ($this->getCookieManager()->getCookie('mage-cache-sessid'))
$metadata = $this->getCookieMetadataFactory()->createCookieMetadata();
$metadata->setPath('/');
$this->getCookieManager()->deleteCookie('mage-cache-sessid', $metadata);
/** @var MagentoFrameworkControllerResultRedirect $resultRedirect */
$resultRedirect = $this->resultRedirectFactory->create();
$resultRedirect->setPath('*/*/logoutSuccess');
return $resultRedirect;
This is the magento core logout functionality, we can use as per our wish. Just try.
add a comment |
It will work. Pro-grammatically logout customer on observer.
<?php
/**
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace VendorModuleNameObserver;
use MagentoCustomerModelSession;
use MagentoFrameworkAppActionContext;
use MagentoFrameworkAppObjectManager;
use MagentoFrameworkStdlibCookieCookieMetadataFactory;
use MagentoFrameworkStdlibCookiePhpCookieManager;
use MagentoFrameworkEventObserverInterface;
class Logout implements ObserverInterface
/**
* @var Session
*/
protected $session;
/**
* @var CookieMetadataFactory
*/
private $cookieMetadataFactory;
/**
* @var PhpCookieManager
*/
private $cookieMetadataManager;
/**
* @param Context $context
* @param Session $customerSession
*/
public function __construct(
Context $context,
Session $customerSession,
CookieMetadataFactory $cookieMetadataManager
)
$this->session = $customerSession;
$this->cookieMetadataManager = $cookieMetadataManager;
parent::__construct($context);
/**
* Retrieve cookie manager
*
* @deprecated 100.1.0
* @return PhpCookieManager
*/
private function getCookieManager()
if (!$this->cookieMetadataManager)
$this->cookieMetadataManager = ObjectManager::getInstance()->get(PhpCookieManager::class);
return $this->cookieMetadataManager;
/**
* Retrieve cookie metadata factory
*
* @deprecated 100.1.0
* @return CookieMetadataFactory
*/
private function getCookieMetadataFactory()
if (!$this->cookieMetadataFactory)
$this->cookieMetadataFactory = ObjectManager::getInstance()->get(CookieMetadataFactory::class);
return $this->cookieMetadataFactory;
/**
* Customer logout action
*
* @return MagentoFrameworkControllerResultRedirect
*/
public function execute()
$lastCustomerId = $this->session->getId();
$this->session->logout()->setBeforeAuthUrl($this->_redirect->getRefererUrl())
->setLastCustomerId($lastCustomerId);
if ($this->getCookieManager()->getCookie('mage-cache-sessid'))
$metadata = $this->getCookieMetadataFactory()->createCookieMetadata();
$metadata->setPath('/');
$this->getCookieManager()->deleteCookie('mage-cache-sessid', $metadata);
/** @var MagentoFrameworkControllerResultRedirect $resultRedirect */
$resultRedirect = $this->resultRedirectFactory->create();
$resultRedirect->setPath('*/*/logoutSuccess');
return $resultRedirect;
This is the magento core logout functionality, we can use as per our wish. Just try.
It will work. Pro-grammatically logout customer on observer.
<?php
/**
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace VendorModuleNameObserver;
use MagentoCustomerModelSession;
use MagentoFrameworkAppActionContext;
use MagentoFrameworkAppObjectManager;
use MagentoFrameworkStdlibCookieCookieMetadataFactory;
use MagentoFrameworkStdlibCookiePhpCookieManager;
use MagentoFrameworkEventObserverInterface;
class Logout implements ObserverInterface
/**
* @var Session
*/
protected $session;
/**
* @var CookieMetadataFactory
*/
private $cookieMetadataFactory;
/**
* @var PhpCookieManager
*/
private $cookieMetadataManager;
/**
* @param Context $context
* @param Session $customerSession
*/
public function __construct(
Context $context,
Session $customerSession,
CookieMetadataFactory $cookieMetadataManager
)
$this->session = $customerSession;
$this->cookieMetadataManager = $cookieMetadataManager;
parent::__construct($context);
/**
* Retrieve cookie manager
*
* @deprecated 100.1.0
* @return PhpCookieManager
*/
private function getCookieManager()
if (!$this->cookieMetadataManager)
$this->cookieMetadataManager = ObjectManager::getInstance()->get(PhpCookieManager::class);
return $this->cookieMetadataManager;
/**
* Retrieve cookie metadata factory
*
* @deprecated 100.1.0
* @return CookieMetadataFactory
*/
private function getCookieMetadataFactory()
if (!$this->cookieMetadataFactory)
$this->cookieMetadataFactory = ObjectManager::getInstance()->get(CookieMetadataFactory::class);
return $this->cookieMetadataFactory;
/**
* Customer logout action
*
* @return MagentoFrameworkControllerResultRedirect
*/
public function execute()
$lastCustomerId = $this->session->getId();
$this->session->logout()->setBeforeAuthUrl($this->_redirect->getRefererUrl())
->setLastCustomerId($lastCustomerId);
if ($this->getCookieManager()->getCookie('mage-cache-sessid'))
$metadata = $this->getCookieMetadataFactory()->createCookieMetadata();
$metadata->setPath('/');
$this->getCookieManager()->deleteCookie('mage-cache-sessid', $metadata);
/** @var MagentoFrameworkControllerResultRedirect $resultRedirect */
$resultRedirect = $this->resultRedirectFactory->create();
$resultRedirect->setPath('*/*/logoutSuccess');
return $resultRedirect;
This is the magento core logout functionality, we can use as per our wish. Just try.
answered Oct 31 '18 at 1:39
ManiMaran AManiMaran A
3163 silver badges5 bronze badges
3163 silver badges5 bronze badges
add a comment |
add a comment |
Thanks for contributing an answer to Magento Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f192492%2fprogramatically-log-user-out-magento-2%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
you should get customer session in your observer, try this magento.stackexchange.com/questions/95558/…
– Kyrylo Romantsov
Sep 8 '17 at 7:56