Authenticating with email address in CakePHP v2.0 - php

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.

Related

cakephp upgrade from 1.3 to 2 authentication failure

I've actually figured this out but I couldn't find anything about this until brainstorming with another developer - tracing through the core code to figure out what was going on.
The problem is quite simple - after upgrading from CakePHP v1.3 to v2.5.9 the login (authentication) doesn't work. But there is no error message to tell you why it's not working.
As is noted in the 2.0 Migration Guide:
The AuthComponent was entirely re-factored for 2.0, this was done to help reduce developer confusion and frustration. In addition, AuthComponent was made more flexible and extensible. You can find out more in the Authentication guide.
The Authentication guide mentioned explains all well and good how you should get it to work for a new installation but nothing about what you need to do to migrate.
The further problem is that there is no error to tell you what is going on.
I copied the code for the UsersController.php -> login method from the Authentication guide section on Identifying users:
public function login() {
if ($this->request->is('post')) {
// Important: Use login() without arguments! See warning below.
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirectUrl());
// Prior to 2.3 use
// `return $this->redirect($this->Auth->redirect());`
}
$this->Session->setFlash(
__('Username or password is incorrect'),
'default',
array(),
'auth'
);
}
}
In my AppController.php I had the following:
public $components = array(
'Session', 'P28n', 'Store', 'SiteStore', 'UserAccessLevel', 'Auth'
);
Then in AppController.php -> beforeFilter:
$this->Auth->authorize = array('Controller');
$this->Auth->loginError = __('Login failed, invalid username or password. Please try again.');
$this->Auth->authError = __('Please log-in.');
$this->Auth->allow('login', 'logout');
The only thing for sure that I knew is that $this->Auth->login() is returning false. But the problem could be anything.
The problem was hashing of passwords. Easy once you know the answer.
I'd got as far as adding in the Simple password hashing component suggested in the Authentication guide:
public $components = array(
'Auth' => array(
'authenticate' => array(
'Form' => array(
'passwordHasher' => array(
'className' => 'Simple',
'hashType' => 'sha256'
)
)
)
)
);
But this still failed, but I couldn't confirm that password hashing was definitely the cause. It took tracing the code through to BaseAuthenticate::_findUser that was definitely failing on the passwords to confirm it.
At this point I then made a stab that the hashing of the passwords from CakePHP could be made to match the Simple passwordHasher.
The passwords in CakePHP 1.3 are saved using sha1, and switching 'hashType' => 'sha1' fixed the problem:
public $components = array(
'Auth' => array(
'authenticate' => array(
'Form' => array(
'passwordHasher' => array(
'className' => 'Simple',
'hashType' => 'sha1'
)
)
)
)
);

Cakephp 2.3: Auth component, Authenticate user on two column in OR

I am building the application using cakephp.
I have choosed the cakephp2.3.
User would be authenticated using either 'email' OR 'username'.
I found one option with Auth component "scope", but with this we can set static conditions.
LIKE: if user is active,, is_active => 1
But I want that while authenticating auth component should check either 'email' or 'username' field and other is password.
Is there any way?
This needs some code. You can easily find it through Users/CakeDC plugin found here
This plugin Uses the auth component below for login with multiple columns.
https://github.com/CakeDC/users/blob/master/Controller/Component/Auth/MultiColumnAuthenticate.php
It also includes an example of how to use. If you don't want the whole plugin you can just copy the MultiColumnAuthenticate.php to the folder app/Controllers/Components/Auth/.
if you copy only the file then in beforeFilter method inside your AppController you must write:
class AppController extends Controller {
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->authenticate = array(
'MultiColumn' => array( //With no plugin
'fields' => array(
'username' => 'username',
'password' => 'password'
),
'columns' => array('username', 'email'),
)
);
}
}
according to cakephp documentation.
FormAuthenticate allows you to authenticate users based on form POST data. Usually this is a login form that users enter information into
By default AuthComponent uses FormAuthenticate
you can try this:
// Pass settings in $components array
public $components = array(
'Auth' => array(
'authenticate' => array(
'Form' => array(
'fields' => array('username' => 'email', 'password' => 'password')
)
)
)
);

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.

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

cakePHP authentication problems

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.

Categories