Auth not working in view - php

I'm trying to make certain buttons appear only to certain user types, I was adding this code around buttons in my view:
<li><?php
if($this->Auth->user('role_id')==8){
echo $this->Html->link(__('New Consumer Product'), array('action' => 'add'));
}
?>
</li>
But that just gave me the error Error: AuthHelper could not be found. so I added the following in my AppController:
public $helpers = array('Auth');
However this just gave me the following error:
Helper class AuthHelper could not be found.
Error: An Internal Error Has Occurred.
What's happening here? Shouldn't it have worked when I added the Auth helper into my AppController?
I'd previously been using Auth in my UsersController with no problems at all.

You can't use Auth in the view. That's only for controllers.
There are actually a few options such as setting/passing a variable for it, but this is the correct way as per the manual
if((AuthComponent::user('role_id') == 8) {
...
}

In your AppControllers beforeRender() or beforeFilter() just set the active user to the view:
public function beforeRender() {
$this->set('userData', $this->Auth->user());
}
And work with that variable in the view. I prefer to not use the static method calls on the component inside a view, it's the wrong place for a component and also static calls aren't something you want to introduce a lot because of tight coupling.
My BzUtils plugin comes with a helper that can deal with this variable or can be configured to read the user data from session and offers some convenience methods.

in cake 3.x I found the only thing that worked is to set the variable in AppController.php as so:
public function beforeRender(\Cake\Event\Event $event) {
$this->set(['userData'=> $this->Auth->user(),
]);
}
the key difference being you have to pass in $event...

Auth is a component not a helper. There is no Auth helper.
You can read the Authenticated user from the following command
$user = $this->Session->read("Auth.User");

Related

How to call a function of a controller from a view?

There is a controller :
use Phalcon\Mvc\Controller;
class ReferentielClientController extends Controller
{
public function indexAction(){
// moteur de template pour une View
$this->view->act_form = 'ReferentielClient/ajouterClient';
return $this->view->pick("client/listerClient");
}
public function ajouterClientAction(){
$this->view->action_form = 'ajouterClientExec';
return $this->view->pick("client/ajouterClient");
}
...
}
From a view I want to call the indexAction method of the controller ReferentielClientController. How to do that ?
Short answer: You can't.
You can't since indexAction is not a normal method, it's an action. Actions aren't called by anyone in the usual way that methods are, they are called with routes an url. Let me explain this a little bit further:
Using MVC, we have the following route using :
http://www.example.org/a/b/c
a is which we call module.
b is which we call controller.
And c is which we call action.
Index actions and default modules will not appear in the URL.
So, how to call functions from view? Better not to. Best way to proceed is to do everything in your controller and pass that info to the view. I.e.:
public function indexAction(){
$this->view->myInfo = $allMyInformationInOneObject;
}
And then, in the view (index.phtml):
<p>
<?php echo $this->myInfo ?>
</p>
Summary:
You don't need to call any controller function from the view, just give it that info from the controller.
Added info about redirection
OK, answering to your commentary. What you want is not to call that function but to redirect the browser to that action.
So, I'll suppose you have your route created in your router, if not, please, go to the Zend documentation about routing. It's highly recommended to create routes instead of using the URL itself.
I guess that you will not be able to use the normal redirecting using href on a button or such, so you will need to use the redirector helper. Since you are not in a controller, you are not able to use the helper by using:
$this->_helper->redirector->gotoUrl($url);
So you will need to instance the redirector like this:
$redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
$redirector->gotoUrl($url);
Being this $url, the URL given by your router, as you can read in the link above.
This can be done but I strongly recommend not to redirect from the view but from the controller. It would be good that all the logic remains in the controller.
I hope this helps!
Ok I found it : I set the href to point to the controller : Annuler

How to route cutom URL with to custom controller in CodeIgniter?

I have a PHP CodeIgniter Controller with name User and have a method that get details of user user_detail($username)
Now when i need to show user data for example for userName mike
I call this URL
http://www.example.com/user/user_detail/mike
My target
How to make user data accessible by next URLs
http://www.example.com/user/mike
or / and
http://www.example.com/mike
You have to read the this page from the official documentation of codeigniter. It covers all related things to Routing URLs easily. All routes must be configured via the file:
application/config/routes.php
It could be something like this :
$route['user/(:any)'] = "user/user_detail/$1";
This can be achieved by overriding CI_Controller class BUT dont change the original core files, like I said override the controller and put your logic in it.
Help: https://ellislab.com/codeigniter/user-guide/general/core_classes.html
how to create Codeigniter route that doesn't override the other controller routes?
Perhaps an easier solution would be to route it with the help of apache mod_rewrite in .htaccess
Here is an detailed explanation on how to achieve it: http://www.web-and-development.com/codeigniter-remove-index-php-minimize-url/
Hatem's answer (using the route config) is easier and cleaner, but pointing the usage of the _remap() function maybe helpful in some cases:
inside the CI_Controller, the _remap() function will be executed on each call to the controller to decide which method to use. and there you can check if the method exist, or use some defined method. in your case:
application/controllers/User.php
class User extends CI_Controller {
public function _remap($method, $params = array())
{
if (method_exists(__CLASS__, $method)) {
$this->$method($params);
} else {
array_unshift($params, $method);
$this->user_detail($params);
}
}
public function user_detail($params) {
$username = $params[0];
echo 'username: ' . $username;
}
public function another_func() {
echo "another function body!";
}
}
this will result:
http://www.example.com/user/user_detail/john => 'username: john'
http://www.example.com/user/mike ........... => 'username: mike'
http://www.example.com/user/another_func ... => 'another function body!'
but it's not going to work with: http://www.example.com/mike , since the controller -even if it's the default controller- is not called at all, in this case, CI default behaviour is to look for a controller called mike and if it's not found it will throws 404 error.
for more:
Codeigniter userguide 3: Controllers: Remapping Method Calls
Redirect to default method if CodeIgniter method doesn't exists.

How to read and write session in helper--Cakephp

I have to use the session in cakephp helper.
To read the session is possible in helper but write session is not.
I don't know how to do it.
Can anyone tell me?
Basic problem is that:
I have created one custom helper which call several times in view for single request.
Suppose helper has called for 5 times.
In helper for textarea some random id has going to be assign.
I need to collect those ids in some variable and then use it for the js function.
If you have new idea related to this problem then please share.
I have added the "session helper" in my custom helper.
Thanks!!!
You can extend SessionHelper , for that place a create a ExtendSessionHelper.php in View/Helper
and add following code in it.
App::uses('SessionHelper', 'View/Helper');
class ExtendSessionHelper extends SessionHelper {
public function write($name, $value = null) {
return CakeSession::write($name, $value);
}
}
Use following code in helpers array of controller to use this helper
var $helpers = array( 'Session' => array('className' => 'ExtendSession'));

CakePHP - creating an API for my cakephp app

I have created a fully functional CakePHP web application. Now, i wanna get it to the next level and make my app more "opened". Thus i want to create an RESTful API. In the CakePHP docs,i found this link (http://book.cakephp.org/2.0/en/development/rest.html) which describes the way to make your app RESTful. I added in the routes.php the the two lines needed,as noted at the top of the link,and now i want to test it.
I have an UsersController.php controller,where there is a function add(),which adds new users to databases. But when i try to browse under mydomain.com/users.json (even with HTTP POST),this returns me the webpage,and not a json formatted page,as i was expecting .
Now i think that i have done something wrong or i have not understood something correctly. What's actually happening,can you help me a bit around here?
Thank you in advace!
You need to parse JSON extensions. So in your routes.php file add:
Router::parseExtensions('json');
So a URL like http://example.com/news/index you can now access like http://example.com/news/index.json.
To actually return JSON though, you need to amend your controller methods. You need to set a _serialize key in your action, so your news controller could look like this:
<?php
class NewsController extends AppController {
public function index() {
$news = $this->paginate('News');
$this->set('news', $news);
$this->set('_serialize', array('news'));
}
}
That’s the basics. For POST requests, you’ll want to use the RequestHandler component. Add it to your controller:
<?php
class NewsController extends AppController {
public $components = array(
'RequestHandler',
...
);
And then you can check if an incoming request used the .json file extension:
public function add() {
if ($this->RequestHandler->extension == 'json') {
// JSON request
} else {
// do things as normal
}
}

Zend Framework MVC redirecting to different controller and action

i'm trying to work out how i can stop zend or redirect zend to go to a different zend controller and action if a check within the boot strap fails.
for example a get variable does not exist or more likely a session does not exist meaning the user must log in.
so the user had originally requested index/someaction
but i want them to go to login/index
within my boot strap i would place the condition and then change the controller action to view.
if i'm doing this in a way that is not standard can anyone direct me to documentation on the best practice ?
zend novice
From Zend documentation (Dispatcher)
// forward to an action in another controller:
// FooController::bazAction(),
// in the current module:
$this->_forward('baz', 'foo', null, array('baz' => 'bogus'));
I'd sugest you to do with plugins for access check on each page and for login create an authentication controller.
Here you'll find out how to do this http://alex-tech-adventures.com/development/zend-framework/61-zendauth-and-zendform.html
An example:
class Plugin_AccessCheck extends Zend_Controller_Plugin_Abstract
{
public function preDispatch(Zend_Controller_Request_Abstract $request)
{
// ...
if(!$auth->hasIdentity())
{
$request->setControllerName('authentication')
->setActionName('login');
}
}
}
I don't usually put authentication in the bootstrap, that should have it's own controller.
Create an AuthController() to set up your auth adapter and and set up your instance.
Then in a common view (for secure pages), just check your instance with something like:
$auth = Zend_Auth::getInstance();
if(!$auth->hasIdentity())
{
#re-direct to login page
}

Categories