zf2 navigation, how to hide some items based on session - zend-framework

My zendframwork 2 application contains a navigation in my application/module.php , this navigation contains many items from which some of them are ( login - logout - register )
I don't need to show the three all the time In the navigation menu.. when the user is n't logged in I must show him : login- register , after he logs-in, I must show him only logout link
How can I do that?

Removing pages
Module.php
public function onBootstrap(MvcEvent $e)
{
$application = $e->getApplication();
$serviceManager = $application->getServiceManager();
if (user not login) {
$container = $serviceManager ->get('navigation');
$logoutPage = $container->findBy('route' , 'logout');
$container->removePage($logoutPage);
}
}

<?php if (isset($_SESSION["login"]) { ?>
Logout
<?php } else { ?>
Login
Register
<?php } ?>
or something similar to this might work. Replace the "login" key with whatever yours is.

Related

Unable to destroy session after clicking logout link in codeigniter(facebook integration)

Session is not destroying after clicking the logout link on home page. Here is my code
public function login()
{
$config['appId'] = '405802852809513';
$appid=$config['appId'];
$config['secret'] = 'b873cf1c00e9e1554cb0eede34d252d5';
$secret=$config['secret'];
$this->load->library('facebook', $config);
$user = $this->facebook->getUser();
if ($user) {
try {
$user_profile = $this->facebook->api('/me'); print_r($user_profile);
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
if ($user) {
echo"<br>";
echo $data['logoutUrl']=$this->facebook->getLogouturl(array("next"=>site_url('/user/logout')));
} else {
$scope = array(
'scope' => 'email,offline_access,publish_stream,user_birthday,user_location,user_work_history,user_about_me,user_hometown'
);
$data['loginUrl'] = $this->facebook->getLoginUrl($scope);
}
if ($user) {
$logoutUrl=$data['logoutUrl'] ;
$user_info = array(
'name' => $user_profile["name"],
'app_id'=>$appid,
'secret'=>$secret,
'id' =>$user_profile["id"],
'logoutUrl'=> $logoutUrl,
);
$this->load->library('session');
$this->session->set_userdata($user_info);
redirect('user/home') ;
} else {
$this->load->view('frm_login',$data);
}
}
After filling email and passoward user will be redirect to home page and home method will be called
public function home(){
$this->load->library('session');
$user_info=$this->session->all_userdata();
if(isset($user_info['name'])){
$data['name']=$user_info['name'];
if(isset($user_info['logoutUrl']))$data['logoutUrl']=$user_info['logoutUrl'];
$this->load->view("home",$data);
}
else{
redirect("user/login");
}
}
And here is the view for my home page
<html>
<body>
Welcome <?php echo $name;?>
<?php
if(isset($logoutUrl))
{?>
Fb_Logout
<?php }
else
{?>
Logout
<?php
}
?>
</body>
</html>
And here is my logout for destroying the session but the prob is that session is not destroying. I tried everything to destroythe session but still it exists.
And if I call user/loggin in the url then it show my directly the home page with my facebook name displayed on it.If the session is successfully destroyed then it must show the login screen of facebook, but it is not showing that. Please help me out got stucked in this for almost 2 days. Your replies are totally welcome.
public function logout(){
$this->load->library('session');
$this->load->library('facebook', $config);
$this->session->unset_userdata($user_info);
$this->facebook->destroysession();
$this->session->sess_destroy();
redirect("user/login");
}
I do not know in which class do you have your logout method. It is a class right? (otherwise it would be strange to see the usage of $this inside). Do you have a session object in that class? What class does your session object have in your class? Is the class of your session object having a sess_destroy method? If so, is it public? If so, what does it contain? Also, where do you call your logout() method? Is it even executed?
These should have been the questions you should have asked yourself.
This is a reference about how to destroy the session in php.

How to handle a failed login with ZfcUser's LoginWidget?

In my Zend Framework 2 application I am using the zfcUserLoginWidget, a View Helper provided by ZfcUser. This View Helper is meant to embed the login form on another page.
<?php echo $this->zfcUserLoginWidget(); ?>
I use this View Helper in my index.phtml which is controlled by my IndexController. Pressing the "Login" button calls the loginAction function of the UserController. If the entered login data are invalid, the UserController redirects by default to the login page:
class UserController extends AbstractActionController
{
const ROUTE_LOGIN = 'zfcuser/login'; // Leads to 'user/login'
public function loginAction()
{
// ...
if (!$form->isValid()) {
$this->flashMessenger()->setNamespace('zfcuser-login-form')->addMessage($this->failedLoginMessage);
return $this->redirect()->toUrl($this->url()->fromRoute(static::ROUTE_LOGIN).($redirect ? '?redirect='. rawurlencode($redirect) : ''));
}
// ...
}
}
The login.phtml displays by default an error message if the entered login data has been invalid:
<?php echo $this->formElementErrors($form->get('identity')) ?>
In my application I have changed the redirection route back to the index.phtml (to the LoginWidget) controlled by the IndexController instead of the login.phtml controlled by the UserController:
const ROUTE_LOGIN = 'home'; // Leads to 'index/index'
Changing this redirection route causes the loss of error messages: The previously mentioned formElementErrors function is still called, but there are no messages available anymore.
Question:
How can I inform the LoginWidget about the fact that there has been entered invalid login data and that the page has not only been simply reloaded?
I'd like to colorize the input fields red if that is the case...
having the same problem i solved it using use Zend\Session\Container, generating my own message.
Modified:
ZendSkeletonApplication\vendor\zf-commons\zfc-user\src\ZfcUser\Controller\UserController.php
Add
use Zend\Session\Container;
const ROUTE_LOGIN = 'home';
in loginAction of UserController.php added/changed
//open session
$session = new Container('loginmsg');
if (!$form->isValid()) {
//$this->flashMessenger()->setNamespace('zfcuser-login-form')->addMessage($this->failedLoginMessage);
//$this->flashMessenger()->addMessage('not working');
//return $this->redirect()->toUrl($this->url()->fromRoute(static::ROUTE_LOGIN).($redirect ? '?redirect='.$redirect : ''));
$session->loginmsg = 'Username and password do not match.'; //store loginmsg
return $this->redirect()->toRoute('home');
} else {
$session->loginmsg = "";
}
Also modify the authenticateAction
if (!$auth->isValid()) {
$this->flashMessenger()->setNamespace('zfcuser-login-form')->addMessage($this->failedLoginMessage);
$adapter->resetAdapters();
//open session
$session = new Container('loginmsg');
$session->loginmsg = 'Username and password do not match.'; //store loginmsg
return $this->redirect()->toUrl($this->url()->fromRoute(static::ROUTE_LOGIN)
. ($redirect ? '?redirect='.$redirect : ''));
}
In the home Route (indexAction):
$session = new Container('loginmsg');
$loginmsg = strip_tags($session->loginmsg);
$session->getManager()->getStorage()->clear('loginmsg');
$this->layout('layout/index');
return new ViewModel(array(
'loginmsg' => $loginmsg,
));
In the View of the Index
<?php if(!(empty($loginmsg))):?>
<div class="alert alert-danger" role="alert"><?php echo $loginmsg;?></div>
<?php endif; ?>
Worked for me (at first), msg me for further information.
Kind regards,
David

Form action showing two controller actions in cakephp form

I am new to cakephp and currently building a login authentication page. My users_controller.php is:
<?php
class UsersController extends AppController {
var $name = 'Users';
var $components = array('Auth');
function index() {
}
function login() {
}
function logout() {
$this->redirect($this->Auth->logout);
}
}
And login.ctp is
<?php
echo $this->Session->flash('auth');
echo $this->Form->create('Users');
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->end('Login');
?>
But when I checked the page source, the action of the form is <form action="/student/app/webroot/index.php/users/users/login" id="UsersLoginForm" method="post" accept-charset="utf-8">. As you can see there are two users controller in the action . Why this additional user is coming ?
NB: Cakephp version 1.3. All our projects were done in this version and not yest upgraded !

cakephp multiple forms with same action

I've got on my page several News, to every News we can add comment via form.
So actually I've got 3 News on my index.ctp, and under every News is a Form to comment this particular News. Problem is, when i add comment, data is taken from the last Form on the page.
I don;t really know how to diverse them.
i've red multirecord forms and Multiple Forms per page ( last one is connected to different actions), and i don't figure it out how to manage it.
Second problem is, i can't send $id variable through the form to controller ( $id has true value, i displayed it on index.ctp just to see )
This is my Form
<?php $id = $info['Info']['id']; echo $this->Form->create('Com', array('action'=>'add',$id)); ?>
<?php echo $this->Form->input(__('Com.mail',true),array('class'=>'form-control','field'=>'mail')); ?>
<?php echo $this->Form->input(__('Com.body',true),array('class'=>'form-control')); ?>
<?php echo $this->Form->submit(__('Dodaj komentarz',true),array('class'=>'btn btn-info')); ?>
<?php $this->Form->end(); ?>
and there is my controller ComsController.php
class ComsController extends AppController
{
public $helpers = array('Html','Form','Session');
public $components = array('Session');
public function index()
{
$this->set('com', $this->Com->find('all'));
}
public function add($idd = NULL)
{
if($this->request->is('post'))
{
$this->Com->create();
$this->request->data['Com']['ip'] = $this->request->clientIp();
$this->request->data['Com']['info_id'] = $idd;
if($this->Com->save($this->request->data))
{
$this->Session->setFlash(__('Comment added with success',true),array('class'=>'alert alert-info'));
return $this->redirect(array('controller'=>'Infos','action'=>'index'));
}
$this->Session->setFlash(__('Unable to addd comment',true),array('class'=>'alert alert-info'));
return false;
}
return true;
}
}
you are not closing your forms
<?php echo $this->Form->end(); ?>
instead of
<?php $this->Form->end(); ?>
for the id problem you should write
echo $this->Form->create(
'Com',
array('action'=>'add/'.$id
)
);
or
echo $this->Form->create(
'Com',
array(
'url' => array('action'=>'add', $id)
)
);

ZF strange layout behavior

I have a strange behavior with ZF that I can't resolve. I have a layout.phtml and a login.phtml. So when the user is logged in the layout.phtml should be displayed else the login.phtml. This also works, but before displaying the login.phtml, ZF go through layout.phtml and I can confirm this due to errors in the error.log file.
Here what I have in the bootstrap:
public static function _initAcl()
{
$auth = Zend_Auth::getInstance();
$acl = new BM_Acl($auth);
$front = Zend_Controller_Front::getInstance();
$front->registerPlugin(
new BM_Controller_Plugin_Acl($auth, $acl)
);
}
Here what I have in the auth controller:
public function indexAction() {
$form = new BM_Form_Login();
$request = $this->getRequest();
if ($request->isPost()) {
if ($form->isValid($request->getPost())) {
if ($this->_process($form->getValues())) {
// We're authenticated! Redirect to the home page
//json validation on login page
$var = json_encode(array('valid' => true, 'redirect' => 'index'));
echo $var;
exit();
} else {
$var = json_encode(array('valid' => FALSE, 'error' => 'Authentication failed!', 'redirect' => 'auth'));
echo $var;
exit();
}
}
}// end if is POST
$this->_helper->layout()->setLayout('login'); // special login page
$this->view->form = $form;
}
Any help will be appreciated...
Regards
Andrea
P.S. This only happens when I start the application from a new browser window. If I refersh the login page, the layout is not called anymore...
Views are for single pages. If you have a singular page you wish to display with a template like layout.phtml, you would edit the index.phtml inside the index action's views directory. If you want to disable the main layout
$this->_helper->layout()->disableLayout();
Or use a blank layout
$this->_helper->layout()->setLayout('blank');
Any code specific to a singular page should be done with a view.
Iam not sure, but the i think the layout is redered before the view scripts. You could try to put you logic inside the preDispatch Hook in your Controller.
public function preDispatch() {
$form = new BM_Form_Login();
$request = $this->getRequest();
if ($request->isPost()) {
if ($form->isValid($request->getPost())) {
if ($this->_process($form->getValues())) {
// We're authenticated! Redirect to the home page
//json validation on login page
$var = json_encode(array('valid' => true, 'redirect' => 'index'));
echo $var;
exit();
} else {
$var = json_encode(array('valid' => FALSE, 'error' => 'Authentication failed!', 'redirect' => 'auth'));
echo $var;
exit();
}
}
}// end if is POST
$this->_helper->layout()->setLayout('login'); // special login page
$this->view->form = $form;
}
Or use an ControllerPlugin:
Zend Controller Plugin - Doc
When I understand right, you have a layout that you use on all pages, except for login. Instead of using the view for login as a layout, you should disable layout for this action and just render the login.phtml normally. You can do this by calling the following in your controller's loginAction, instead of setLayout('login'):
$this->_helper->layout()->disableLayout();
This will just disable the layout, but the view is rendered normally.
If you want to do it your way, you have to place the login.phtml into the layout-path, not in the view-path (if you want a more detailed explanation, just ask in a comment).