Cakephp User management plugin implementation - cakephp

I had downloaded the plugin from link
https://github.com/CakeDC/users
followed the steps given in the page. I have created the tables 'users' and 'details'. I have also registered the user and verfied the user, but while accessing the link www.mydomain/users/users/login this page is getting redirected to www.mydomain/users/login
which shows missing controller. I am new to cake and for me it is difficult to debug. I would be thank if some one help me.
Thank you for the response.
Yes, I have added the code given in the "cake\libs\controller\app_controller.php" file. In order to test this I have freshly downloaded the core files and setup the files in my local system. I have placed the plugins 'utils', 'search' and 'users' to my app/plugins folder and created the tables.
Now also I am able to register the user but not able to see the login page. ie. "while accessing the link www.mydomain/users/users/login this page is getting redirected to www.mydomain/users/login which shows missing controller".
Please let me know if I am missing anything or I am wrong.
Thank you.

This looks like a problem in the login redirection.
Did you add the beforeFilter() configuration to your app_controller?
if not you may need to add it.
Here is an example of how your app_controller should look like:
<?php
class AppController extends Controller {
var $components = array('RequestHandler', 'Session', 'Auth');
function beforeFilter(){
$this->Auth->fields = array('username' => 'email', 'password' => 'passwd');
$this->Auth->loginAction = array('plugin' => 'users', 'controller' => 'users', 'action' => 'login', 'admin' => false);
$this->Auth->loginRedirect = '/';
$this->Auth->logoutRedirect = '/';
$this->Auth->authError = __('Sorry, but you need to login to access this location.', true);
$this->Auth->loginError = __('Invalid e-mail / password combination. Please try again', true);
$this->Auth->autoRedirect = false;
$this->Auth->userModel = 'Users.User';
$this->Auth->userScope = array('User.active' => 1);
}
}
?>
Remember that the $this->Auth->loginAction MOST contain the 'plugin'=>'users', without it it will go to www.mydomain/users/login instead of www.mydomain/users/users/login

Related

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!

CakePHP Auth not re-logging in to the right path

I am having some issues with the CakePHP Auth login. For some reason, instead of the site going to the path i have laid out for it, it looks at the form and goes right to the login function.
To explain, here is my code,
Router File :
Router::connect('/clientlogin', array('controller' => 'pages', 'action' => 'UsersLogin'));
Router::connect('/login', array('controller' => 'users', 'action' => 'login'));
Pages Controller - UsersLogin Function :
public function UsersLogin() {
$this->render('/Pages/LoginForm');
} //End of UsersLogin function
Users Controller - login Function :
public function login() {
if ($this->Auth->login()) {
$this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash('Invalid Username Or Password, Please Try Again', 'default', array(), 'bad');
$this->redirect($this->Auth->redirect());
}
} //End of Login function
LoginForm.cpt Code :
echo $this->Session->flash('auth');
echo $this->Form->create('User', array('url'=>'/login', 'id' => 'LoginForm'));
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->submit('Login', array('class' => 'Button'));
echo $this->Form->end();
My main menu in my site has a 'login' button that points to '/clientlogin', which loads the form for my users to login with. However, when the session information expires, the areas of the site which require login to access them push me over to re-login.
But CakePHP is not going to /clientlogin its going to /login - which is not the form but the login controller. Also it dose not matter what I change it to but where ever I point my form is where Cake whats to go. For example, I changed the form to point to /mylogintest or /loginuser and Cake went to these paths instead.
So my main question is, when Cake needs to re auth the session information, how do I make sure it points to my clientform path and not the path laid out in my form.
If I have not been clear or, I have not posted something needed, then please ask me and I will try and fix it.
Many Thanks for any help given
Glenn.
You can change the default login action by passing extra keys into the components. See the code below :
// Pass settings in $components array
public $components = array(
'Auth' => array(
'loginAction' => array(
'controller' => 'pages',
'action' => 'UsersLogin'
)
)
);
I am not sure why you need to create separate action to contain the login form. Usually I'll have the form inside the login action and check the request using $this->request->is('post'). See the Cookbook for more information http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html

Cakephp Auth Component - Home page redirect loop

I want to have a login form in my home page, the registered users should be redirected to users/index
with the below code, my home page is going to redirect loop
can anyone tell me where is the issue ??
Note:- infact it is perfectly working if i change the line to
$this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');
App Controller
public function beforeFilter(){
$this->Auth->autoRedirect = false;
$this->Auth->loginAction = array('controller' => './', 'action' => 'index');
$this->Auth->loginRedirect = array('controller' => 'users', 'action' => 'index');
$this->Auth->logoutRedirect = array('controller' => './', 'action' => './');
$this->Auth->authorize = 'controller';
$this->Auth->authError= 'You need permissions to access this page';
$this->Auth->allow('index');
$this->set('Auth',$this->Auth);
}
UsersController
public function login(){
$id = $this->Auth->user('id');
if(empty($id)){
if($this->request->is('post')){
if($this->Auth->login()){
$this->redirect($this->Auth->redirect());
}else{
$this->Session->setFlash('Invalid Username or password');
}
}
}else{
$this->redirect(array('action'=>'index'));
}
}
Thanks for the help...
You pretty much answered your own question here:
Note:- infact it is perfectly working if i change the line to
$this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');
Indeed that would work and that is what it should look like. Right now, you're telling the auth component your loginAction (the action which holds your login logic) is the index action of the ./ controller (which doesn't even exist). I'm assuming you're confusing it with the loginRedirect variable, which is for setting the page to go to after successful authentication.
If you only want Registered Users to Access Your Site you could have something like this... at least, this is how I implement something similar in my site...
In your app_controller file add the following to the beginning of your beforeFilter() function
function beforeFilter(){
//Check if user was able to log in thru Auth using your form in the homepage
if($this->isLoggedIn() == TRUE){
$this->layout = 'default'
}else{
// You can created this layout with a login form and
// whatever else you need except <?php echo $content_for_layout; ?>
// Any registered user will be allowed to login using the form
// and continue on to your site using the default layout
// But it guarantees no one else can see your default site
$this->layout = "unregistered_user"
}
}
On your App_controller.php you can create this function
function isLoggedIn(){
// You can also use $this->Auth->user directly in your App's beforeFilter()
// But I just like to have functions so I can reuse
if($this->Auth->user()){
$loggedin= TRUE;
}else{
$loggedin= FALSE;
}
return $loggedin;
}
I have something similar of my site but is only used when in maintenance mode. I am still developing my site. The only problem I've seen with this way, which I have not yet have time/need to look at, is that my errors are not sent to the layout I want. Supposed a user types in http://www.mydomain.com/inexistentpage then cake transfers them to my default layout. It might be easy to fix, but I havent got time to do that yet.
NOTE: I quickly did this off the top of my head and because of it, this code is untested. However, if you have any issues please let me know and I will test it and post back.
using $this->requestAction(anotherController/action); in the view might call to another controller->action. you must ensure that the another controller->action has the right permissions. or you'll get redirect loop.
solve it by adding $this->auth->allow('action name'); to the another controller page in the beforeFilter() callback.

cakePHP auth component not working

I have an issue with cake's auth that I simply can't seem to get past (i've been debugging and trying different tutorials for the last two days). As far as I can see it should be very simple, the problem is whenever i try to login, it just refreshes the login page. I cannot for the life of me figure out why! My only conclusion is that there must be something (basic) which tutorials take for granted that I have missed.
Here are a couple of snippets:
users_controller.php
class UsersController extends AppController {
var $name = 'Users';
function beforeFiler() {
parent::beforeFilter();
}
function login() {
}
function logout() {
$this->Session->setFlash('You have successfully logged out.');
$this->redirect($this->Auth->logout());
}
}
app_controller.php
class AppController extends Controller {
var $helpers = array('Html','Form','Javascript');
var $components = array('Auth');
function beforeFilter() {
$this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');
$this->Auth->loginRedirect = array('controller' => 'contents', 'action' => 'index');
$this->Auth->logoutRedirect = array('controller' => 'contents', 'action' => 'view');
$this->Auth->loginError = 'Something went wrong';
$this->Auth->allow('register', 'view');
$this->Auth->authorize = 'controller';
$this->set('loggedIn', $this->Auth->user('id'));
}
function isAuthorized() {
return true;
}
}
login.ctp
<div class="midCol short">
<h3>Login</h3>
<div class="loginBox">
<?php e($form->create('User', array('controller'=>'users','action'=>'login')));?>
<?php
echo $this->Form->input('username');
echo $this->Form->input('password');
e($this->Form->end(array('label'=>'Login', 'class'=>'loginButton button png')));?>
</div>
</div>
Any help would be greatly appreciated, this has me tearing my hair out!
Just for documentation as I had difficulties finding an answer for CakePHP 2.x on the web. This stuff needs to be "correct" in order to use Form authentication:
The config needs to be right, e.g. in your UsersController (the fields config is really only required when names differ in the DB):
public $components = array(
'Auth' => array(
'authenticate' => array(
'Form' => array(
'fields' => array(
'username' => 'username',
'password' => 'password'
),
)
)
)
);
You have to use the Form Helper: Form->create adds a hidden input field ("post"), and the names of the input fields generated by Form->input() follow a convention that the Auth component expects.
User->login must not pass custom data to Auth->login(). The Auth component will take the auth data from the form (= request).
Thanks for the advice, but I ended up scrapping it and building again from scratch. Not exactly sure why it was originally breaking, probably not calling inbuilt functions with American English!
The Auth component will redirect to the page before you logged in. If that page was the login page that's where it'll redirect to.
When you're testing, it's likely that you're refreshing the login page, so on successful login that's where you're redirected to. You can check this by trying to perform an Auth protected action after logging in.
This gives me a lot of headaches as well - I think the current functionality of the component is a little clumsy in that respect.
I had the exact same problem and found that I had to restart mySQL service. Once it was restarted I stopped getting the login page being redirected. Hope that helps.
Gonna throw something in here. I was having an almost unresolveable problem with cakephp authentication. Ended up doing some debugging around it and found that during my database prep I had created a field for the password which was perfectly able to store normal size passwords... but.... when you start applying password hashing you need a lot more. My code was fine, but I had to add a bunch more space into the VARCHAR field for the password before I could log in. If you're having a problem with authentication - make sure your password field is adequately sized and not getting truncated like mine was. Took me a whole day to find that. DOH!
Correct me if i am wrong but must there not be code for redirection or something inside the function of login
function login() {
}
should it not be something like
public function login()
{
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
return $this->redirect($this->Auth->redirectUrl());
}
$this->Flash->error(__('Invalid username or password, try again'));
}
}

CakePHP - how to give public authorization on the main page

I set up the basic Authentication/Authorization set up, but a problem now is that every time I try to access the http://localhost:1234/, it requires user to login.
How/Where do I make the Auth->authorize("index") on the main page?
In the beforeFilter() of your controller
add the following piece of code
> $this->Auth->allow('actionname');
for suppose if I want to allow adding/registering of user without logging in then I would do like this in the beforeFilter() function of the users_controller.php file.
> $this->Auth->allow('add');
Inside app_controller.php's beforeFilter():
$this->Auth->authorize("display");
fixed the problem.
for cakephp 1.3 you have to do it now like this:
var $components = array(
'Auth' => array(
'authorize' => 'controller',
'allowedActions' => array('index','**display**');
)
);
And remember that you also can config a router:
Router::connect('/facebook', array('controller' => 'pages', 'action' => '**display**', 'facebook'));

Resources