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
Related
I am facing this weird problem. I am trying to change the default loginRedirect of the admin role from that of normal user.
U have the auth key in the AppController's component variable set up as follows :
'Auth' => array(
'loginRedirect' => array(
'controller' => 'donors',
'action' => 'index'
)
)
Now in the beforeFilter callback I have this set up:
if($this->Auth->user('role') == 'admin'){
$this->Auth->loginRedirect = array(
'controller'=>'users',
'action'=>'admin_index',
'prefix'=>'admin',
'admin'=>true
);
}
However, this does not work and the if condition is never met. I am expecting this to run when the user logs in. If I add an else condition and repeat the same code shown above, it works and the admin is redirect to the desired page.
Can anyone instruct how I am able to do this correctly ? Thanks in advance
If the user is not logged in, $this->Auth->user() will return null. beforeFilter() will run before any action is run, so your login() action has still not been called.
Do the redirecting after $this->Auth->login() has been called and is successful. E.g. in your UsersController::login() action (or whichever action you use to login):
if ($this->Auth->login()) {
if($this->Auth->user('role') == 'admin') {
$this->redirect(array(
'controller'=>'users',
'action'=>'admin_index',
'prefix'=>'admin',
'admin'=>true
);
}
}
Instead of $this->Auth->loginRedirect use $this->redirect(
array('controller' => 'users', 'action' => 'admin_index');
Its less complicated
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.
After migrating a fully functional Cake 1.3 application to the recently released 2.0 version Authentication has ceased to work.
I've changed the calling of the AuthComponent and the structure of the login action according to the updated 2.0 manual, to no avail. The strange thing is the user is actually validated by $this->Auth->login() as it reaches the part of the login function where the user is redirect to the url set by $this->Auth->redirect(). After that redirect however, $this->Auth->user() returns empty (as well as AuthComponent::user()) and the user isn't logged in by the Auth component.
Cake doesn't throw any error during the process, the flash messages for 'auth' remain empty.
Users are stored in a simple database table containing id, username, email, password and timestamp columns. The passwords are hashed and I've added some users using the new Cake 2.0 methods.
This is the code of AppController.php:
<?php
class AppController extends Controller {
public $helpers = array('Session', 'Html', 'Time', 'Form', 'Text');
public $components = array('Session', 'RequestHandler', 'Auth');
public function beforeFilter() {
$this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');
$this->Auth->loginRedirect = array('controller' => 'maps', 'action' => 'index');
$this->Auth->logoutRedirect = array('controller' => 'maps', 'action' => 'index');
}
}
?>
UserController.php:
<?php
class UsersController extends AppController {
public $name = 'Users';
function beforeFilter() {
parent::beforeFilter();
}
function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirect());
}
}
}
function logout() {
$this->redirect($this->Auth->logout());
}
}
?>
User.php model. I've disabled form validation for the time being after I solve this problem:
<?php
class User extends AppModel {
public $name = 'User';
}
?>
The login view:
<?php
echo $this->Form->create('User');
echo $this->Form->input('username', array('label' => 'Username', 'before' => '<p class="input" id="username">', 'after' => '</p>', 'between' => '<br />', 'div' => false));
echo $this->Form->input('password', array('label' => 'Password', 'before' => '<p class="input" id="password">', 'after' => '</p>', 'between' => '<br />', 'div' => false));
echo $this->Form->end('Login');
?>
I also tried to setting some of the Auth features in the $components variable in the AppController, which didn't work as well:
public $components = array(
'Auth'=> array(
'loginAction' => array(
'controller' => 'users',
'action' => 'login',
),
'loginRedirect' => array(
'controller' => 'maps',
'action' => 'index',
),
'authenticate' => array(
'Form' => array(
'fields' => array('username', 'password')
)
)
)
);
What's causing the problem here? Routing maybe? I've commented out all routes except:
require CAKE . 'Config' . DS . 'routes.php';
UPDATE:
After adding some debug statements in the login method in the UsersController I now know $this->Auth->user() is actually populated with the correct user after the call to $this->Auth->login(). After the redirect to another controller the login session is lost completely, however. So I still don't know what's going wrong here.
UPDATE 2
I've restarted the process of migrating by taking my working 1.3 application and running the migration console script on it like I did the last time.
This time I noticed the script stopped because of two errors relating to custom components. Component classes should extend Component now, instead of the 1.3 default: Object.
After fixing these component errors I ran the migration script again (something I neglected to do during the first migration attempt) and implemented the new AuthCompenent call. So far everything seems to be working correctly. Not sure what's different now and what went wrong the first time, as Cake didn't output any error messages.
UPDATE 3
It's getting weirder. I thought I solved it, but after transferring my code to another development machine Auth suddenly stops working. It's working on my main setup, but while testing on another it fails again following the same scenario. I've cleared the cache to be sure, but it still isn't working. Cake doesn't generate any error output.
UPDATE 4
It appears to be a Session problem on my machine. I've just set the Session to be stored in a cookie and suddenly Auth starts working again. Not sure why the default Session isn't working and I don't know where to start debugging in that case.
Only cookie sessions appear to work, defining a database session has the same result as a regular session; Auth stops working.
Try it with use_trans_sid enabled in /Config/core.php:
Configure::write('Session', array(
//'defaults' => 'php'
'defaults' => 'cake',
'cookie' => 'CAKEPHP2',
'ini' => array('session.use_trans_sid' => true)
));
Did you try also to configure the Authentication handler ?
public $components = array(
'Auth'=> array(
'authenticate' => array('Form')
)
);
How would I create a login link on a CakePHP page that contains a query string with the current page so for example: domain.com/login/?back=/posts/This_is_a_post
and then how would I use this in the login method to send the user BACK to this url?
I have tried this: <?php echo $this->Html->link('Log in', array('controller'=>'users','action'=>'login','admin'=>false, '?'=> array('back'=>$this->here)), array('escape'=>false)); ?>
but it does this on the url /login?back=%2Fportfolio%2Fgt%2FCreatHive
how do I get it to NOT change the / in the URL
Cheers
The best way to do this is to store the last page visited in a session at some point, probably when the page is loaded in the login action or something. Why you ask? As an attacked could make a link to your site eg: yoursite.com/login?back=mysite.com/login, so that when the user logs in, you send them to my site which is an exact duplicate of your login form and get them to login again. Voila, an attacker could now easily phish your users info.
With sessions there'd be no url encoding problems either. Just something like this in your login action:
$this->Session->set('back_to', $this->referer());
// Then if they have logged in:
$backTo = $this->Session->read('back_to');
if($backTo) {
$this->redirect($back_to);
} else {
$this->redirect($this->Auth->redirect());
}
Update - Try using named parameters instead:
For your link:
echo $this->Html->link('My Link', array('controller' => 'users', 'action' => 'login', 'url' => $url));
In your users login:
function login(){
if($this->Session->read('Auth.User')){
$url = $this->params['named']['url']
// encode/decode url
$this->redirect("$url");
}
}
You can always use urlencode() and urldecode() for the $url variable.
You also need to make sure your form also sends the URL back to the login function:
echo $this->Form->create('User', array('controller' => 'users', 'action' => 'login', 'url' => $url));
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'));
}
}