cakephp - auth logout redirect - redirect

In cakephp2.0, I have domain.com but when I logout (url is domain.com/logout), it is redirected to domain.com/app/login. I dont want it to redirect to domain.com/app/login but instead redirect to domain.com/logout. These are the codes I have in my UsersController & my AppController
class AppController extends Controller {
public $helpers = array ('Html', 'Form', 'Js' => array('Jquery'), 'Session');
public $components = array(
'Session',
'Auth' => array(
'loginRedirect' => array('controller' => 'posts', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'users', 'action' => 'login'),
'authorize' => array('Controller') // Added this line
)
);
}
Userscontroller
class UsersController extends AppController {
public $components = array(
'Auth' => array(
'loginRedirect' => array('controller' => 'posts', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'users', 'action' => 'login'),
'authorize' => array('Controller') // Added this line
)
);
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('add', 'logout', 'login');
$this->Auth->deny('view');
}
public function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
$this->redirect('http://domain.com/thankyou');
} else {
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}
}
public function logout() {
$this->redirect($this->Auth->logout());
}
}
Any help would be great. Thanks.

I ended up using this in my logout() function
$this->Auth->logout();
$this->redirect(some url);

Do you have a view for the logout page? Something that you are trying to display after they are logged out? What might be happening is that the user is logged out, but Cake is unable to display the logout page because it is secure, so Cake redirects to the login page.
If you have security enabled and a page you want to be displayed to a user that is not logged in, you will need to include something like this in its controller:
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('login','logout');
}

Did you check that ?
'Auth' => array(
'loginRedirect' => array('controller' => 'posts', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'users', 'action' => 'login'),
)
And
public function logout() {
//$this->redirect($this->Auth->logout());
//Change for :
//I suppose that you have a logout.ctp view in your View/Pages
$this->redirect(array('controller' => 'pages', 'action' => 'display', 'logout')
}
Then in your rootes
Router::connect('/logout', array('controller' => 'pages', 'action' => 'display', 'logout'));
of course don't forget
$this->Auth->allow('display'

Related

Magento 1.9 sending custom form - form data not found in controller

I am having trouble with a simple form. I am quite sure that I miss some critical info about this topic...
I created a custom module, I created a custom form
<?php
class modulename_History_Block_Adminhtml_History_Edit_Form extends Mage_Adminhtml_Block_Widget_Form {
protected function _prepareForm()
{
$form = new Varien_Data_Form(array(
'id' => 'edit_form',
'name' => 'edit_form',
'action' => $this->getUrl('*/*/history', array('id' => 'orders_export')),
'method' => 'post',
'enctype' => 'multipart/form-data',
'data' =>'somethingsomethingdarkaside'
));
$this->setForm($form);
$fieldset = $form->addFieldset('Filtrování objednávek', array('legend'=> 'Nastavte filtr pro report objednávek'));
$dateTimeFormatIso = Mage::app()->getLocale()->getDateTimeFormat(Mage_Core_Model_Locale::FORMAT_TYPE_SHORT);
$fieldset->addField('date_from', 'date', array(
'label' => 'Změna statusu objednávek od:',
'title' => 'Změna statusu objednávek od:',
'time' => true,
'name' => 'filter_date_from',
'image' => $this->getSkinUrl('images/grid-cal.gif'),
'format' => $dateTimeFormatIso,
'required' => true,
));
$fieldset->addField('export_history_order_status_changed', 'button', array(
'label' => 'Exportovat do souboru:',
'value' => 'Export',
'name' => 'export_history_order_status_changed',
'class' => 'form-button',
'onclick' => "setLocation('{$this->getUrl('*/*/export')}')",
));
$form->setUseContainer(true);
return parent::_prepareForm();
}
And then there is a controller. When the button is pressed, it goes to the correct controller to a correct action. However no data in post received:
<?php
class modulename_History_Adminhtml_History_HistoryController extends Mage_Adminhtml_Controller_Action {
protected function _initAction()
{
return $this;
}
/**
* A page with the form, creating the block with it.
*
*/
public function editAction()
{
$this->_title('Historie objednavky')
->loadLayout()
->_setActiveMenu('modulename/historymenu');
$this->_addContent($this->getLayout()->createBlock('modulename_history/adminhtml_history_edit'));
$this->renderLayout();
}
/**
* A main entrance - when the filter is set and the "export" button pressed then this is the function which starts.
*
* #return bool|Mage_Core_Controller_Varien_Action - either we return a downloadable file or we return false.
*/
public function exportAction()
{
if ($this->_setParameters())
{
if ($this->_setOrdersIds())
{
return $this->_getDownloadFile();
}
}
return false;
}
/**
* Try to get parameters from the admin form. If all correct then we return true. If there is something not set
* then we are unable to continue and we return false.
*
* #return bool - either we were successful with getting the parameters or not.
*/
protected function _setParameters()
{
$parameters = $this->getRequest()->getParams();
$pokus = $this->getRequest()->getPost();
$necf = $this->getRequest()->getPost('edit_form');
$neco = Mage::app()->getRequest()->getParam('edit_form');
}
}
Hellou,
so a competent colleque find an answer within minutes. I mean it was as silly as expected, just remove on click action on button and set the heading from the button to the form. And changed the button to submit. I quess the guy I copied the code from used some other spells of high magic so it worked for him. I hope this will help. Correct form below:
<?php
class modulename_History_Block_Adminhtml_History_Edit_Form extends
Mage_Adminhtml_Block_Widget_Form {
protected function _prepareForm()
{
$form = new Varien_Data_Form(array(
'id' => 'edit_form',
'name' => 'edit_form',
//'action' => $this->getUrl('*/*/history', array('id' => 'orders_export')),
'action' => $this->getUrl('*/*/export', array('id' => 'orders_export')),
'method' => 'post',
'enctype' => 'multipart/form-data',
'data' =>'somethingsomethingdarkaside'
));
$this->setForm($form);
$fieldset = $form->addFieldset('Filtrování objednávek', array('legend'=> 'Nastavte filtr pro report objednávek'));
$dateTimeFormatIso = Mage::app()->getLocale()->getDateTimeFormat(Mage_Core_Model_Locale::FORMAT_TYPE_SHORT);
$fieldset->addField('date_from', 'date', array(
'label' => 'Změna statusu objednávek od:',
'title' => 'Změna statusu objednávek od:',
'time' => true,
'name' => 'filter_date_from',
'image' => $this->getSkinUrl('images/grid-cal.gif'),
'format' => $dateTimeFormatIso,
'required' => true,
));
$fieldset->addField('export_history_order_status_changed', 'submit', array(
'label' => 'Exportovat do souboru:',
'value' => 'Export',
'name' => 'export_history_order_status_changed',
'class' => 'form-button',
//'onclick' => "setLocation('{$this->getUrl('*/*/export')}')",
));
$form->setUseContainer(true);
return parent::_prepareForm();
}

How to create multiple form submit buttons with alternate routes in ZF2

In ZF2, how do you create multiple submit buttons that each lead to different routes? In the Forms and actions chaper of the ZF2 tutorial, a form is created with a single submit button with the label “Go” that processes the input data and returns to the index page (route). Where do we put the pertinent scripts if we wanted four buttons:
Save action: saves user input, route: return to current page
Save and Close action: saves user input, route: return to index (Album)
Clear action: no action, route: return to current page
Close action: no action, route: return to index (Album)
I assume the buttons are created like this:
namespace Album\Form;
class AlbumForm extends Form
{
public function __construct($name = null)
{
// ... //
$this->add(array(
'name' => 'savebutton',
'attributes' => array(
'type' => 'submit',
'value' => 'Save',
'id' => 'savebutton',
),
));
$this->add(array(
'name' => 'save_closebutton',
'attributes' => array(
'type' => 'submit',
'value' => 'Save & Close',
'id' => 'save_closebutton',
),
));
$this->add(array(
'name' => 'clearbutton',
'attributes' => array(
'type' => 'submit',
'value' => 'Clear',
'id' => 'clearbutton',
),
));
$this->add(array(
'name' => 'closebutton',
'attributes' => array(
'type' => 'submit',
'value' => 'Close',
'id' => 'closebutton',
),
));
}
}
This is what the edit action looks like with only one submit button:
// module/Album/src/Album/Controller/AlbumController.php:
//...
// Add content to this method:
public function editAction()
{
$id = (int) $this->params()->fromRoute('id', 0);
if (!$id) {
return $this->redirect()->toRoute('album', array(
'action' => 'add'
));
}
$album = $this->getAlbumTable()->getAlbum($id);
$form = new AlbumForm();
$form->bind($album);
$form->get('submit')->setAttribute('value', 'Edit');
$request = $this->getRequest();
if ($request->isPost()) {
$form->setInputFilter($album->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$this->getAlbumTable()->saveAlbum($form->getData());
// Redirect to list of albums
return $this->redirect()->toRoute('album');
}
}
return array(
'id' => $id,
'form' => $form,
);
}
//...
Since pairs of buttons have the same form action and pairs of buttons have the same route, I image we want to add two if statements somewhere here, unless a switch statement is better.
Quick 'n dirty way to do what you need:
public function editAction()
{
$id = (int) $this->params()->fromRoute('id', 0);
if (!$id) {
return $this->redirect()->toRoute('album', array(
'action' => 'add'
));
}
$album = $this->getAlbumTable()->getAlbum($id);
$form = new AlbumForm();
$form->bind($album);
$form->get('submit')->setAttribute('value', 'Edit');
$request = $this->getRequest();
if ($request->isPost()) {
$form->setInputFilter($album->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$input = $form->getData();
if (!empty($input['save_closebutton'])) {
return $this->redirect()->toRoute('album', array(
'controller' => 'AlbumController',
'action' => 'index',
));
}
}
}
return array(
'id' => $id,
'form' => $form,
);
}

Zend Framework 2 Redirect not working

i have a problem with ZF2 not redirecting from my controller. When i call the url xyz.dev/event it redirects to my home ("/") as defined in routes. When i call xyz.dev/event/1 (where id is now set) it shall also redirect to home, which is not happening. I get the error
Url plugin requires that controller event compose a router; none found
My code is here:
namespace Event\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\Mvc\Router\SimpleRouteStack;
use Event\Model\EventTable;
use Zend\Mvc\Router\Http\Segment;
use Zend\Mvc\MvcEvent;
class IndexController extends AbstractActionController {
protected $eventsTable;
public $event;
public $_event;
public function indexAction() {
$id = (int) $this->params()->fromRoute('id', 0);
if (!$id) {
return $this->redirect()->toRoute("home");
}
$this->event = $this->getEventsTable()->getEvent($id);
// if ($this->event->end < date("Y-m-d")) {
return $this->redirect()->toRoute('home');
// }
return new ViewModel(array("event" => $this->event));
}
public function getEventsTable() {
if (!$this->eventsTable) {
$sm = $this->getServiceLocator();
$this->eventsTable = $sm->get("Event\Model\EventTable");
}
return $this->eventsTable;
}
}
The first redirect
if (!$id) {
return $this->redirect()->toRoute("home");
}
is working fine, the second is not... Any ideas?
Thank you,
Alex
Check your module.config file routing section and check which has proper routing condition as like below:
'home' => array(
'type' => 'segment',
'options' => array(
'route' => '/home[/:action][/:id][/]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]*',
),
'defaults' => array(
'controller' => 'Home\Controller\Home',
'action' => 'index',
),
),
),
You may forgot to mention the optional parameters(id) in your routing arguments.
I hope this works...

Zend Framework: My form wont render

So I have created a form below with Zend Framework which I'm then going to customise. My first issue is that with the csrf hash security I get an application error. However, when I remove them lines all I get is a blanks screen which is only resolved when I remove the CPATCHA protection. Can anyone explain to me why?
My Form:
class Application_Form_Clips extends Zend_Form
{
public function init()
{
// Set the method for the display form to POST
$this->setMethod('post');
// Add an email element
$this->addElement('text', 'email', array(
'label' => 'Your email address:',
'required' => true,
'filters' => array('StringTrim'),
'validators' => array(
'EmailAddress',
)
));
// Add the comment element
$this->addElement('textarea', 'comment', array(
'label' => 'Please Comment:',
'required' => true,
'validators' => array(
array('validator' => 'StringLength', 'options' => array(0, 20))
)
));
// Add a captcha
$this->addElement('captcha', 'captcha', array(
'label' => 'Please enter the 5 letters displayed below:',
'required' => true,
'captcha' => array(
'captcha' => 'Figlet',
'wordLen' => 5,
'timeout' => 300
)
));
// Add the submit button
$this->addElement('submit', 'submit', array(
'ignore' => true,
'label' => 'Sign Guestbook',
));
// And finally add some CSRF protection
$this->addElement('hash', 'csrf', array(
'ignore' => true,
));
}
}
My Controller:
class AdminController extends Zend_Controller_Action
{
public function init()
{
// get doctrine and the entity manager
$this->doctrine = Zend_Registry::get('doctrine');
$this->entityManager = $this->doctrine->getEntityManager();
// get the users repository
$this->indexVideos = $this->entityManager->getRepository('\ZC\Entity\Videos');
$this->indexClips = $this->entityManager->getRepository('\ZC\Entity\Clips');
}
public function indexAction()
{
// action body
}
public function clipsAction()
{
// get a form
$form = new Application_Form_Clips();
$this->view->form = $form;
}
public function videosAction()
{
// action body
}
}
My View:
<?php echo $this->form; ?>
Basic error, I hadn't uncommented session.pat in my php.ini

Zend_Auth now only works partial

Okay,
This is completely a weird situation.
When a user logs in, I store some stuff using the following code:
$auth->getStorage()->write($authAdapter->getResultRowObject(array(
'username',
'avatar',
'status',
'role',
'id',
'email'
)));
Then I use the following code in my bootstrap to get access to the variables:
<?php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
protected function preDispatch()
{
$this->frontController = Zend_Controller_Front::getInstance();
}
protected function _initBuildBase()
{
$this->bootstrap('layout');
$layout = $this->getResource('layout');
$this->view = $layout->getView();
// Set doctype
$this->view->doctype("XHTML1_TRANSITIONAL");
$this->view->headMeta()->appendHttpEquiv('Content-Type', 'text/html;charset=utf-8');
}
protected function _initLoader()
{
$adminLoader = new Zend_Application_Module_Autoloader(array(
'namespace' => 'Admin',
'basePath' => APPLICATION_PATH));
$autoLoader = Zend_Loader_Autoloader::getInstance();
$autoLoader->registerNamespace('MyApp_');
$resourceLoader = new Zend_Loader_Autoloader_Resource(array(
'basePath' => APPLICATION_PATH,
'namespace' => '',
'resourceTypes' => array(
'model' => array(
'path' => 'models/',
'namespace' => 'Models_'
),
'service' => array(
'path' => 'services/',
'namespace' => 'Services_'
),
'form' => array(
'path' => 'forms/',
'namespace' => 'Forms_'
),
),
));
return $autoLoader;
return $adminLoader;
}
protected function _initControllerPlugins()
{
$this->frontController->registerPlugin(new MyApp_Controller_Plugin_ApplicationSettings);
$this->frontController->registerPlugin(new MyApp_Controller_Plugin_LayoutLoader);
$this->frontController->registerPlugin(new MyApp_Controller_Plugin_LanguageSelector);
$this->frontController->registerPlugin(new MyApp_Controller_Plugin_Acl);
$this->frontController->registerPlugin(new MyApp_Controller_Plugin_Uploadify);
}
protected function _initActionHelpers()
{
Zend_Controller_Action_HelperBroker::addPath(APPLICATION_PATH .'/views/helpers');
}
protected function _initRoutes()
{
$router = $this->frontController->getRouter();
$router->addRoute(
'crud',
new Zend_Controller_Router_Route('/:module/:controller/:action/:id', array('module' => 'admin', 'controller' => ':controller', 'action' => ':action', 'id' => ':id'))
);
$router->addRoute(
'pagination',
new Zend_Controller_Router_Route('/:module/:controller/index/:page', array('module' => 'admin', 'controller' => ':controller', 'action' => 'index', 'page' => ':page'))
);
$router->addRoute(
'pageUrl',
new Zend_Controller_Router_Route('/:page/:subpage', array('module' => 'default', 'controller' => 'index', 'action' => 'index', 'page' => ':page', 'subpage' => ':subpage'))
);
}
protected function _initLogin()
{
$this->auth = Zend_Auth::getInstance();
$this->view->user = $this->auth->getIdentity();
}
}
Okay, and now for the weird part:
When I use
if($this->user->role == 'Administrator')
{
In my layout.phtml it works great. But when I use the same code in a index.phtml file which is loaded according to the controller it doesn't work?!
The stranger part is that it used to work perfectly and use it t show different options depending of the user's role.
Where could I look for mistakes in my code? Really lost on places to check on. Probably changed something somewhere, but everything else seems to work fine.
Any tips or directions would be awesome!
The layout and view resource both do use the Zend_Controller_Action_Helper_ViewRenderer(). The layout resource accesses the helper to get the view (readonly). But the view resource accesses the helper and overwrites the view object of the helper.
So in your case the layout got bootstrapted, you did set the variables. Afterwards the view resource is bootstrapted which overwrites the view in the helper.
You always should bootstrap the view before the layout to ensure they both use the same view object.