Fatal error on auth login - cakephp

Im getting the following error when trying to log in a user:
Call to a member function login() on a non-object
My login action uses an external model. The action is:
public function login() {
$this->loadModel('User');
if ($this->request->is('post')) {
$theUser = $this->User->find('first', array('conditions' => array('User.username' => $this->request->data['User']['username'])));
if($theUser['User']['activated'] == TRUE){
if ($this->Auth->login($this->request->data)){
$this->Session->setFlash('Logged in successfully');
$this->redirect(array('controller' => 'admin', 'action' => 'index'));
} else {
$this->Session->setFlash('Username or password is incorrect');
}
}else $this->Session->setFlash('User not yet activated. Please Contact administrator.');
}
}
The request data being passed to the $this->Auth->login is:
array(
'User' => array(
'password' => '*****',
'username' => 'admin'
)
)
$this->Auth->login($this->request->data) is the line causing the fatal error.
Can someone please explain what exactly the error means and what might be causing it?

You'll need to check that you've included the Auth component in the controller. For example:
class UsersController extends AppController {
public $components = array(
'Auth'
);
public function login() { ... }
}
As pointed out by #thaJeztah - check the docs for correct usage, as your code (which based on the usage of $this->request, implies you're using 2.x) is not correct and will not test if the user exists and can login - but instead directly log the user in whatever they put in the login form.

Related

Authorized public URL keeps redirecting for authentication and failing

In this scenario, OurCustomAuth is currently returning an expected value of false, is reaching the appropriate else, but the users/error path keeps redirecting even though it's been made public and not requiring any authentication.
I've setup the new action:
C:\wamp\myapp\app>Console\cake AclExtras.AclExtras aco_update
Welcome to CakePHP v2.4.9 Console
---------------------------------------------------------------
App : app
Path: C:\wamp\myapp\app\
---------------------------------------------------------------
Created Aco node: controllers/Users/error
Aco Update Complete
In the UsersController, I've added the action to be made public:
public function beforeFilter() {
parent::beforeFilter ();
$this->Auth->allow ('logout', 'error');
}
In AppController, the Auth config:
public $components = array(
'Acl',
'Cookie',
'DebugKit.Toolbar', 'Session',
'Auth' => array(
'authenticate' => array('OurCustomAuth'),
'loginAction' => array('controller' => 'users', 'action' => 'view'),
'authError' => 'Did you really think you are allowed to see that?',
'authorize' => array('Actions' => array('actionPath' => 'controllers'))
)
);
...
public function beforeFilter() {
...
//Auto logging users in if they are not logged in
if (!AuthComponent::user('id')) {
if ($this->Auth->login()) {
//stuff here
} else {
$this->Session->setFlash(__('We could not authenticate you ...'));
return $this->redirect(array('controller' => 'Users', 'action' => 'error'));
}
}
...
}
The error I get in Firefox:
The page isn’t redirecting properly
Firefox has detected that the server is redirecting the request for
this address in a way that will never complete.
Update #1
$this->Auth->login() essentially grabs request headers, that in this case are intentionally wrong, which seems to redirect to the appropriate link. However, /users/error shouldn't cause a redirect as it's excluded from Authentication.
The problem is that you run your login code on every request, ie in the app controllers beforeFilter() method. So when that code redirects you to /users/error because you're not logged in, the code will run again for that controller/action, and redirect you again, and again, and again...
If you need to run this code for every request, then you'll have to check the allowed actions manually, ie the actions allowed via $this->Auth->allow(), and run your code only in case the current action isn't allowed. Check the code of AuthComponent::_isAllowed(), you can easily use that with minimal modifications:
$action = strtolower($this->request->params['action']);
if (!in_array($action, array_map('strtolower', $this->Auth->allowedActions))) {
//Auto logging users in if they are not logged in
if (!AuthComponent::user('id')) {
// ...
}
}

cakephp 3.0 isAuthorized() not being called

I've followed the tutorial and all the CakePHP Authorization guide and I can't get my isAuthorized() method to be called. My understanding (correct me if I am wrong, which is incredibly likely) is by delegating authorize to the specific controllers by doing 'authorize'->['Controller'] in AppController.php, when a method in UsersController is called, in this case 'add', UsersController would run the isAuthorized() method I defined. I was testing to see if this method ran at all outputting a flash->error message right when isAuthorized() is called but nothing happens. If I explicitly call isAuthorized($hardcodeduser) in my beforeFilter()method it will work but only if I hard code a user.
The way the method is supposed to work is: If a registered user requests to add/create a new user, the system checks to see if the user has admin/staff level permissions (which is just a 0 or 1 value in the database) and if the user does not have permission then it redirects to the home screen with an error message that says "You are not authorized to access that function".
Any help or suggestions or other links to follow would be much appreciated!
class AppController extends Controller {
public $components = ['Flash', 'Auth', 'Session'];
public function initialize() {
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'authorize' => ['Controller'],
'loginRedirect' => [
'controller' => 'Articles',
'action' => 'index'
],
'logoutRedirect' => [
'controller' => 'Pages',
'action' => 'display',
'home'
]
]);
}
public function beforeFilter(Event $event) {
$this->Auth->authorize = 'Controller';
}
public function isAuthorized($user) {
if(isset($user['is_staff']))
return true;
return false;
}
}
class UsersController extends AppController {
public function beforeFilter(Event $event) {
parent::beforeFilter($event);
$this->Auth->allow(['logout']);
}
public function isAuthorized($user) {
$this->Flash->error(__('Test Message PLEASE WORK'));
if($this->request->action === 'add') {
$isStaff = $user['is_staff'];
if($isStaff == 0) {
$this->redirect($this->Auth->redirectUrl());
$this->Flash->error(__('Not authorized to access this function'));
return false;
}
}
return parent ::isAuthorized($user);
}
}
Generally your assumption is correct, Controller::isAuthorized() is going to be invoked automatically when using the controller authorization handler.
The problem with your code is that in your UsersController::beforeFilter() method you are explicitly allowing the add method to be accessed by everyone (it won't even require authentication):
$this->Auth->allow(['logout', 'add']);
You have to understand that once a method is allowed, there will be no further checks made by the auth component, see AuthComponent::startup().
Also note that you don't need to redirect and set a flash message manually, the component will do that for you, you just need to configure it appropriately using the authError and unauthorizedRedirect options, see Cookbook > Components > Authentication > Configuration options
As we following the Cake blog tutorial,
they made a little mistake, that function "isAuthorized" never be called.
And I did take a time to research it.
Solution is
Adding this line when load component "Auth":
'authorize' => array('Controller'),
so the code should looks something like this:
$this->loadComponent('Auth', [
'loginRedirect' => [
'controller' => 'Articles',
'action' => 'index'
],
'logoutRedirect' => [
'controller' => 'Pages',
'action' => 'display',
'home'
],
'authorize' => array('Controller'),
]);
Hope it help some one saving time :)
From cakephp 3.x documentation: you can configure authorization handlers in your controller’s beforeFilter() or initialize() methods using an array:
// Basic setup
$this->Auth->config('authorize', ['Controller']);
// Pass settings in
$this->Auth->config('authorize', [
'Actions' => ['actionPath' => 'controllers/'],
'Controller'
]);

CakePHP Auth Login Stopped Working

My auth component has been working fine for the past year. I was logged into my site about two hours ago and made a single minor change. I got off for those two hours and since I've returned about a half hour ago, I have been unable to log into my site. The error message says the username/password combination is incorrect. I thought somehow the values got changed in my database or that my browser had autosaved an old password so just to be sure I updated the password in my database with it's appropriate md5 hashed value and I tried it again in my browser. It still did not work.
I emptied my cache (which is something I do quite often any way) because I was suggested to do so from this post but this too did not work (nor did it help the poster of that question). That person's solution of having added something to the view file that broke the database connection does not apply to me because I did not change any of the view files. Nor have I changed the user model or app controller. The ONLY thing I changed during the time I was on earlier was that I edited the UsersController online() action. I have since changed it back. In fact, I went into my site backup utility and restored all controller and model files to their latest backup which was 2 days ago when everything was working. Still no affect.
I cannot log into any of the accounts I have registered. I even unhashed one of the passwords in the database and tried logging in with that account but that didn't work either.
AppController
//I HAVE NOT CHANGED THIS IN SEVERAL MONTHS
public $helpers = array('Form', 'Html', 'Custom', 'Time', 'Js', 'Cache');
public $components = array('CustomPage', 'Session', 'CustomUser',
'Auth' => array(
'autoRedirect' => false,
'loginAction' => array('controller' => 'users', 'action' => 'login', 'prefix' => false, 'admin' => false, 'moderate' => false),
'loginRedirect' => array('prefix' => false, 'admin' => false, 'moderate' => false, 'controller' => 'account', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'index', 'prefix' => false, 'admin' => false, 'moderate' => false),
'authError' => "You can't access that page",
'authorize' => array('Controller')
)
); // components
public function isAuthorized($user) {
return true;
}
UsersController
// DID NOT CHANGE FOLLOWING ACTION
public function login() {
if ($this->Session->read('Auth.User')) {
$this->Session->setFlash('You are already logged in');
$this->redirect(array('controller' => 'account', 'action' => 'index'));
}
$this->layout = "simple";
$this->set('title_for_layout', 'Login');
if ($this->request->is('post')) {
$this->User->UsersOnline->deleteAll(array('UsersOnline.session' => $this->viewVars['session_session']), false);
if ($this->Auth->login()) { // check user is logged in
$this->User->id = $this->Auth->user('id');
$this->User->saveField('last_login', date(Configure::read('Site.date_format'))); // save login time
$this->redirect($this->Auth->redirect()); // redirect to default place
} else {
$this->Session->setFlash('Your username/password combination was incorrect');
}
}
} // end login
// THE FOLLOWING ACTION WAS THE ONLY THING
// THAT WAS CHANGED BUT IT IS NOW BACK TO ORIGINAL VERSION
public function online() {
$page_id = $this->viewVars['page_id'];
$link = $this->viewVars['link'];
// CONTAIN
$this->User->UsersOnline->contain(array(
'User' => array(
'fields' => array(
'User.username', 'User.online'
),
'Avatar' => array(
'fields' => array(
'Avatar.file'
)
)
)
));
if($page_id){
$this->set('users', $this->paginate($this->User->UsersOnline, array('UsersOnline.page_id' => $page_id)));
$this->set('title_for_layout', 'Fans Online');
}
else{
$this->set('title_for_layout', 'Users Online');
$this->set('users', $this->paginate($this->User->UsersOnline));
$this->layout = "default";
}
} // end online action
My user model uses the standard "username" and "password" columns to authenticate a user.
I've added the following code to my UserController login() action and the correct result is printed...
$password = md5($this->request->data['User']['password']);
print_r(
$this->User->find('first',
array(
'User.username' => $this->request->data['User']['username'],
'User.password' => $password
)
)
);
Again, I have restored ALL controller and model files to their state from 2 days ago so I really have no idea what could be causing this.
Edit 1: And now just to be safe, I reverted all my view files back to their latest backup versions from this weekend. This did not fix the issue.
Edit 2: If I debug $this->Auth->login, the result is empty. Why would this be empty all of a sudden if nothing has changed?
Edit 3: My UsersController register() action properly creates a new user and automatically logs that user in.
UsersController
public function register() {
if($this->Session->read('Auth.User')) {
$this->Session->setFlash('You are already registered');
$this->redirect(array('controller' => 'account', 'action' => 'index'));
}
$this->layout = "simple";
$this->set('title_for_layout', 'Register');
if ($this->request->is('post')) {
$this->User->create();
if ($this->User->save($this->request->data)) {
$id = $this->User->id;
$this->request->data['User'] = array_merge($this->request->data['User'], array('id' => $id));
if($this->Auth->login($this->request->data['User'])){
$this->Session->setFlash(__('Your account has successfully been created and you have logged in'));
$this->redirect(array('controller' => 'account', 'action' => 'index'));
} // end if account created and successful log in
else{
$this->Session->setFlash(__('Your account has successfully been created but you cannot log in'));
} // end else if account created but not logged in
} else {
$this->Session->setFlash(__('Your account could not be created. Please, try again.'));
} // end else if account cannot be created
} // end if method is post
} // end register
Well, I never figured out what the INITIAL issue was but now I found out that reverting all of my changed controller, model, AND view files seem to solve the issue. It still bothers me that I don't know what the initial issue was.
However, I DID discover that after I updated all my passwords in my database to their corresponding md5 hash, that was giving me the ongoing issue. I guess Cake doesn't use md5 which I thought so the passwords weren't being matched properly. So even after reverting all my changed files, the passwords all became incorrect.
If I ever figure out what the original issue was I will update.
It may help to remove all files from tmp/cache and tmp/models
I had the same problem.It was working fine but suddenly after some changes in code that was nothing to do with the login part the login function was not working and deleting the changes I made didnt help and when I searched and find out that you have the same problem and you didnt find what the problem is I figured out that it must be some thing very simple as it didnt give me any error and I suddenly found that when I was editing the user controller file I accidently wrote the ' char in the begining of the file and I removed it and the problem is solved!

cant understand how this function works $this->Auth->login() in cakephp 2.x

i am new in cakephp. i am making a logging system in cakephp 2.x .. i am stuck here
UsersController.php extending AppController
public function login()
{
if ($this->request->is('post')) {
if ($this->Auth->login()) {
$this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash('Your email/password combination was incorrect');
}
}
}
the problem is that it is not checking that whether the email and password typed by the user is correct or not..and is logging the user in without checking .. i have never used the auth component before ... so i am feeling hard to grasp that how this function is checking the email and password from the database as on the internet and the cakephp website they are using this function to check whether the user has logged in successfully or not./i always used sql queries but i dont know how this component is working .. please correct this function and explain me where it is checking the email and password from the database
here is my
AppController
class AppController extends Controller {
public $components = array(
'Session',
'Auth'=>array(
'loginRedirect'=>array('controller'=>'users', 'action'=>'admin'),
'logoutRedirect'=>array('controller'=>'users', 'action'=>'admin'),
'authError'=>"You can't access that page",
'authorize'=>array('Controller')
)
);
public function isAuthorized($user) {
}
public function beforeFilter() {
$this->Auth->allow('index');
}
}
class AppController extends Controller {
// added the debug toolkit
// sessions support
// authorization for login and logut redirect
public $components = array(
'Session',
'Cookie',
'Auth' => array(
'authenticate' => array('Form' => array('fields' => array('username' => 'email', 'password' => 'password'),)),
'authorize' => array('Controller'))
);
public function isAuthorized($user) {
return true;
}
}
please replace the co in app controller.

Cakephp Simple Authentication tutorial page not redirecting to current page

I am start going through the cakephp tutorials, I copy the source code exactly as shown in the tutorial.
I have done the Blog tutorial and all seems good, now I am onto the "Simple Authentication and Authorization Application" (http://book.cakephp.org/2.0/en/tutorials-and-examples/blog-auth-example/auth.html) tutorial, but are running into this issue.
The add page loads fine:
".../app/webroot/index.php/Users/add"
After hitting submit, it redirects me to this url (with the additional "Users" string) and with an error message.
".../app/webroot/index.php/Users/Users/add"
Missing Method in UsersController
Error: The action Users is not defined in controller UsersController
Error: Create UsersController::Users() in file: app/Controller/UsersController.php.
class UsersController extends AppController {
public function Users() {
}
}
Let me know where I should start checking, Thanks.
AppController
class AppController extends Controller {
public $components = array(
'Session',
'Auth' => array(
'loginRedirect' => array('controller' => 'posts', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'pages', 'action' => 'display', 'home'),
'authorize' => array('Controller') // Added this line
)
);
public function beforeFilter() {
$this->Auth->allow('index', 'view');
}
public function isAuthorized($user) {
// Admin can access every action
if (isset($user['role']) && $user['role'] === 'admin') {
return true;
}
// Default deny
return false;
}
}
Because I still can't comment, I'll tell you here and edit this answer if I know it.
Show me your AuthComponent configuration in AppController.php.
EDIT:
Answer is in the comments below. :)

Resources