When you redirect a customer who is logged in to the login form, Magento automatically redirects the customer to their dashboard.
In your code, you need to log the customer out first; then you can redirect them to the login form.
EDIT
Sorry, I can't read sometimes.
I think you're running into a caching problem. You don't write where you execute the code, but most likely the FPC or something else leads to the fact that code#2 is executed; this redirects to the login form, and because the customer is already logged in, to the dashboard.
There are several ways to solve this.
Easiest would be to insert a layout xml update only for that page which contains a block that's cacheable=false
. This means that the FPC won't cache that page. The performance impact, of course, is huge.
Another way would be: when a logged-out customer accesses the page, show the login form on that page instead of the content. If you show the login form shouldn't be determined using PHP (again: FPC at work). You should use knockout.js for this. See here for more info: https://devdocs.magento.com/guides/v2.4/extension-dev-guide/cache/page-caching/private-content.html
A third way would be to add a layout handle programmatically that is only added if the customer is logged in. I've done that in the past and it works fine.
Here's some code to get you started, this is for product pages:
<!-- add a special layout handle for products with hidden price -->
<type name="Magento\Catalog\Helper\Product\View">
<plugin name="vendor_module_before_init_product_layout" type="Vendor\Module\Plugin\Catalog\Helper\Product\ViewPlugin" sortOrder="1" />
</type>
code extract from the class PHP class:
public function beforeInitProductLayout(\Magento\Catalog\Helper\Product\View $view, \Magento\Framework\View\Result\Page $resultPage, $product, $params = null) {
if(!$this->customerIsLoggedIn()) {
if (! $params) {
$params = new \Magento\Framework\DataObject();
}
$afterHandles = $params->getAfterHandles();
if (! $afterHandles) {
$afterHandles = array();
}
$afterHandles[] = 'catalog_product_view_customer_logged_out';
$params->setAfterHandles($afterHandles);
}
return [
$resultPage,
$product,
$params
];
}
/**
*
* @return boolean
*/
public function isCustomerLoggedIn()
{
return boolval($this->_httpContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH));
}
After that, create a file catalog_product_view_customer_logged_out.xml
and do something there (remove page content, add login form or else).
If you really want to redirect, your mistake at the moment is most likely that you execute your code too late. Use the controller predispatch event or something else that's very early.
You can also find some inspiration when you check where & how the customer/login
page checks if the customer is logged in.