cakePHP authentication problems - php

I am unable to wrap my head around how the Auth component works in cakePHP. I am using 2.1
My login works perfectly, and from my understanding I can set the default component in the appController, which I did as listed below.
// App controller:
public $components = array(
'Session',
'Auth' => array(
'loginAction' => array(
'controller' => 'users',
'action' => 'login',
),
'authError' => "Your username and password is incorrect, please try again.",
'authenticate' => array(
'Form' => array(
'scope' => array('User.user_status_id' => 1)
)
),
'redirect' => array("controller" => "users", "action" => "profile"),
'loginRedirect' => array("controller" => "users", "action" => "profile")
)
);
public function beforeFilter() {
$this->Auth->allow("home");
if($this->Auth->loggedIn() == true) {
$this->set("user_name",$this->Auth->user("first_name")." ".$this->Auth->user("last_name"));
$this->set("loggedIn",true);
if($this->Auth->user("user_type_id") == 5) {
$this->set("navigation","navigation_admin");
} else {
$this->set("navigation","navigation_loggedin");
}
} else {
$this->set("loggedIn",false);
$this->set("navigation","navigation_notloggedin");
}
}
home is located /app/view/home.ctp, however, I cannot access the page without being logged in. Next I have 2 different user levels, normal and administrator. I want to limit certain actions in controllers based if you're an admin or not.
In my UserController I have example:
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow("login");
if($this->Auth->user("user_type_id") != 5) {
$this->Auth->allow("login","profile");
}
}
But irrespective of the user type, everyone can view the actions.
In my pages controller I also have the following:
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow("*");
}
But I have to be logged in to view any pages.
I am convinced I am doing something wrong, but I cannot wrap my head around what, any help?

First, home is not an action on the controller, so $this->Auth->allow("home"); wouldn't have an effect. $this->Auth->allow("display"); would but would allow all pages to be seen (not sure if that's intended).
Secondly, you are using $this->Auth->allow("*"); after you call the parent's beforeFilter, which means that AppController::beforeFilter() would treat it as if the user wasn't logged in, since it doesn't know what you've allowed after the fact.

Related

cakePHP Routers/ loginRedirect not working after logout

OK, another one for the cakephp ninjas today..
Here it is :
I have a login/logout system implemented..
I am using $components attr in the AppController, and using the Auth config key to set up loginRedirect and logoutRedirect.. The code looks like this :
public $components = array(
'DebugKit.Toolbar',
'Session',
'Auth' => array(
'loginRedirect' => array(
'controller' => 'posts',
'action' => 'index'
),
'logoutRedirect' => array(
'controller' => 'users',
'action' => 'login'
),
'authorize' => array('Controller')
)
);
The logout action looks like this :
public function logout() {
$this->Session->setFlash(__('You are now logged out.'));
return $this->redirect($this->Auth->logout());
}
Here's the deal.. Whenever I logout through the above logoutRedirect, and then log in, the user is not redirected to posts/index somehow.. and since I ve got DebugKit setup I tried to check whats going on an realised that within the cake Request Params, the controller is set to 'pages' and the action is 'display'.. This lead me to try and logout by manually entering the logout action URL in the address bar.. and guess what?! it works, and the user is redirected to the posts/index page..
So anyone knows how i can fix this issue im having? Or can point me towards a good source from which i can understand what and why is this happening exactly! thanks
Try this
$this->Auth->logout();
$this->redirect(some url);

Does Cakephp Auth can be use even in other controller?

Recently, I've been studying cake, I've seen the auth library which said to be will take care of the access control over your app, but, it seems like, you can't initialize or even use this auth library when you're not in the 'UsersController', i did not want that, what if it has some admin part wherein i want the URI to be admin/login, or just simply /login, i've been scratching my head over this one, please help.
Another question, why it seems like the functionality of the '$this->redirect' is not effective when i'm putting this one at any method that contains nothing but redirection, or even in the __construct()?
thanks guys, hoping someone could clearly explain to me those things.
you can use the Auth component inside any controller in the application. If you want it will only effect with the admin section then you can add condition in the beforeFilter funciton in you application AppController on Auth initialization like.
// for component initialization.
public $components = array(
'Auth' => array(
'authenticate' => array(
'userModel' => 'Customer', // you can also specify the differnt model instead of user
'Form' => array(
'fields' => array('username' => 'email')
)
)
)
}
and you can bind this on the admin routing like
function beforeFilter(){
// only works with admin routing.
if(isset($this->request->params['prefix']) && ($this->request->params['prefix'] == 'admin')){
$this->Auth->loginRedirect = array('admin' => true, 'controller' => 'pages', 'action' => 'index');
$this->Auth->logoutRedirect = array('controller' => 'users', 'action' => 'login', 'admin' => true);
$this->Auth->loginAction = array('admin' => true, 'controller' => 'customers', 'action' => 'login');
}
}
If you're using cake 2.3.x or later then make sure you have specified the redirect action in correct format like.
return $this->redirect('action_name'); // you can also specify the array of parameters.

Authorizing administrators and regular users in a CakePHP application

I'm trying to write some simple functionality to distinguish between administrators and regular users in the CakePHP application I'm writing. I've changed my users table to have a field called admin which is either 0 or 1.
In AppController.php I've got a $components array set up like this:
public $components = array(
'Session',
'Auth' => array(
'authenticate' => array(
'Blowfish' => array(
'fields' => array('username' => 'email')
)
),
'loginRedirect' => array('controller' => 'pages', 'action' => 'home'),
'logoutRedirect' => array('controller' => 'pages', 'action' => 'home'),
'authorize' => array('Controller')
)
);
And also this method:
public function isAuthorized($user) {
// Check if admin
if(isset($this->params['admin']) && $this->Auth->user('admin') == 1) {
echo "admin";
return true;
}
// Default deny
return false;
}
When I load pages I get this error: (net::ERR_TOO_MANY_REDIRECTS): There were too many redirects.. For some reason the code above is causing infinite redirects and I can't work out why.
Also, I've set up a routing prefix for admin so administrators can access URLs like /admin/users/edit. When I go to that page, I don't get infinite redirects and admin is echo'd out like it should be.
I've read up on tutorials online and read the Cake docs but they all seem to end with the infinite redirects, how can I set this up so that I can distinguish administrators from regular users, and deny/allow access to certain actions for each role?
Sixthpoint has already pointed this out.
In absence of the Auth object, the Auth component is redirecting to the Pages Controller and I think you are missing
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow("*"); // * or array("actions", "that", "are", "allowed")
}
So, this is essentially creating an infinite loop, First Auth object is missing, it gets directed to PagesController. The Auth component has been configured to authorize all Controllers, incl PagesController. And the loop reiterates redirecting again to PagesController.
Have you tried looking into ACL ? You can accomplish the same by use of Roles coupled with ACL.

CakePHP Auth loginRedirect error/always redirect to 'users/login' whereas i put different controller

CakePHP Auth loginRedirect error/always redirect to 'users/login' whereas i put different controller.
I mean, when i open the forbidden page(not allowed/require login)
$this->Auth->allow('index', 'profile', 'view', 'register');
it must redirect to "players/index". I put the loginRedirect to "players",
'loginRedirect' => array('controller' => 'Players', 'action' => 'index'),
but it doesn't work. It always redirect to "users/login" not "players/index" whereas i write "'loginRedirect' => array('controller' => 'Players', 'action' => 'index')".
this is my code:
class AppController extends Controller {
public $components = array(
'Session',
'Auth'=>array(
'loginRedirect' => array('controller' => 'Players', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'Players', 'action' => 'index'),
'authError'=>"Anda tidak dapat mengakses halaman.",
'authorize'=>array('Controller')
)
);
public function isAuthorized($user) {
return true;
}
public function beforeFilter() {
$this->Auth->allow('index', 'profile', 'view', 'register');
$this->set('logged_in', $this->Auth->loggedIn());
$this->set('current_user', $this->Auth->user());
}}
My table's name : players
why the result's always redirect to "users/login" not "players/" or "players/index"?
please tell me why this happens and how i can solve it. Thank you!
I was stuck with the same issue for hours. Set the login action in the beforeFilter of your AppController as following:
$this->Auth->loginAction = array('controller'=>'yourcontollername', 'action'=>'login');
I followed the video youtube.com/watch?v=zvwQGZ1BxdM, see the first reply.
Have you tried to lowercase controller name ? Players => players
'loginRedirect' => array('controller' => 'players', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'players', 'action' => 'index'),
very interesting, i come across a similar problem - after login redirect to the default home page.
I have tried all above methods, but none of them could solve the issue.
finally, i found out that login form did not build properly which action and controller were not set. therefore the html form pointed to '/', when posted.
However, the system still managed to login to right accounts, but none of redirect function worked in this situation.
It might be something you need to look into.
good luck.
The answer lies in the beforeFilter function in AppController.php. You must set allowances for the Auth object.
public function beforeFilter() {
// put in the functions that point to the views you want to be able to see
// without logging in. This works for all controllers so be careful for naming
// functions the same thing. (all index pages are viewable in this example)
$this->Auth->allow('index', 'thePageIWantToSee', 'userAdd', 'landingPage');
}
Simply use the login() function in your Users/Players Controller. With the if cause you can redirect to an diffrent page.
public function login()
{
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
return $this->redirect('/account'); //$this->redirect($this->Auth->redirectUrl());
}
return $this->redirect( ['controller' =>'pages', 'action' => 'login-fail']);
}
}
Example used in CakePHP 3.2

Authenticating with email address in CakePHP v2.0

Okies this question is similar to one I have asked recently on Stack Overflow, but I'm basically just using the code from the CakePHP Book rather than my own code to try and understand why something is not working.
Basically the idea is to allow a user to login using their email address as well as their username in version 2.0 of Cake. However it always returns that the details are incorrect but I can STILL login with the username, so basically the override in the AppController does not change anything... More so I'm trying to figure out how to allow both fields for logging in.
As discussed in the original post here: Login with email address or username in CakePHP v2.0 #nIcO has put together something that could pontentially work for both fields BUT the issue explained here causes it not to work.
Any ideas? Anyone got email login working with version 2.0.
// AppController
public $components = array(
'Auth' => array(
'loginAction' => array(
'controller' => 'users',
'action' => 'login'
),
'authenticate' => array(
'Form' => array(
'fields' => array('username' => 'email')
)
)
)
);
// UsersController
public function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash(__('Username or password is incorrect'), 'default', array(), 'auth');
}
}
}
Though id added it in UsersController (not in AppController), but this worked for me for email as username:
public $components = array('Auth');
//beforeFilter in UsersController
function beforeFilter() {
parent::beforeFilter();
$this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');
$this->Auth->authenticate = array(
'Form' => array(
'fields' => array('username' => 'email')
)
);
}
Hope it helps in some way
This is the best implementation I found: http://bin.cakephp.org/view/1831131032
I like how some of the logic has been moved into the Model and clears up the Controller logic and makes it more MVC. Hopefully this will help others.

Categories