I'm working on CakePHP 3.3. I want user to login using either email or mobile number along with password.
I have users table with email, mobile, password, etc fields.
According to CakePHP doc, I'm using custom finder auth to login.
Auth component in AppController.php
$this->loadComponent('Auth', [
'loginRedirect' => [
'controller' => 'Dashboard',
'action' => 'index'
],
'logoutRedirect' => [
'controller' => 'Pages',
'action' => 'home'
],
'authenticate' => [
'Form' => [
'finder' => 'auth'
]
]
]);
and findAuth() action in UsersTable.php
public function findAuth(Query $query, array $options)
{
$query
->select(['id', 'email', 'mobile', 'password'])
->where(['Users.email' => $options['login']])
->orWhere(['Users.mobile' => $options['login']]);
return $query;
}
and login() action in UsersController.php
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->registerError(__('Invalid Credentials, try again'), ['key' => 'registration']);
}
}
login.ctp view contains
<?php
echo $this->Form->create();
echo $this->Form->input('login');
echo $this->Form->input('password');
echo $this->Form->submit();
echo $this->Form->end();
?>
But this is not working and prints Invalid Credentials, try again
Update 2
Added a blank column username to users table.
login.ctp
<?php
echo $this->Form->create();
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->submit();
echo $this->Form->end();
?>
AppController.php:authComponent
same as above
findAuth()
public function findAuth(Query $query, array $options)
{
$query
->orWhere(['Users.email' => $options['username']])
->orWhere(['Users.mobile' => $options['username']]);
return $query;
}
Now it's working. But why force to use username column even if not needed in application.
You must SELECT all the fields you need to authenticate a user, as described on doc.
public function findAuth(Query $query, array $options)
{
$query
->select(['id', 'email', 'mobile', 'username', 'password'])
->orWhere(['Users.email' => $options['login']])
->orWhere(['Users.mobile' => $options['login']]);
return $query;
}
And be sure $options['login'] is on your form.
Update:
If you are using 'login' as Form input try using:
'authenticate' => [
'Form' => [
'finder' => 'auth',
'fields' => ['username' => 'login', 'password' => 'password']
]
]
fields The fields to use to identify a user by. You can use keys username and password to specify your username and password fields respectively.
My own Query using my App (without fields => [username => login]):
SELECT
Users.id AS `Users__id`,
Users.username AS `Users__username`,
Users.password AS `Users__password`,
Users.role AS `Users__role`,
Users.email AS `Users__email`
FROM
users Users
WHERE
(
Users.email = 'user#example.com'
OR (
Users.username = 'user#example.com'
AND Users.username = 'user#example.com'
)
)
My login is similar, but is using username and email instead of your fields.
Update 2:
The documentation is not so great. So testing I figured that by default using a custom finder the query will be modified by Cake adding the first WHERE this = 'something', then the solution is using orWhere on all the others (findAuth modified).
New Query:
SELECT
Users.id AS `Users__id`,
Users.username AS `Users__username`,
Users.password AS `Users__password`,
Users.role AS `Users__role`,
Users.email AS `Users__email`
FROM
users Users
WHERE
(
Users.email = 'user'
OR Users.username = 'user'
)
Related
I'm doing the test for my UserController and I'm having trouble with my login test. I'm using cakephp4 with phpunit.
The test I'm doing is this:
public function testLogin(): void
{
$this->enableSecurityToken();
$this->enableCsrfToken();
$this->get('/user/login');
$this->assertResponseOk();
$this->post('/user/login', [
'DNI_CIF' => '22175395Z',
'password' => '$2y$10$ND67aMGqm.qK86MW1wuW9OQLC9vyJQGUn2HnLuSInwrFbXQKBT.V.'
]);
$this->assertResponseCode(302); //Si correcto redirige
// $this->assertSession(1, 'Auth.User.id');
}
My UserController:
public function login()
{
$this->request->allowMethod(['get', 'post']);
$result = $this->Authentication->getResult();
// regardless of POST or GET, redirect if user is logged in
if ($result && $result->isValid()) {
return $this->redirect('/');
}
// display error if user submitted and authentication failed
if ($this->request->is('post') && !$result->isValid()) {
$this->Flash->error(__('Alias de usuario o contraseña incorrecta.'));
}
}
My Application:
public function getAuthenticationService(ServerRequestInterface $request): AuthenticationServiceInterface
{
$authenticationService = new AuthenticationService([
'unauthenticatedRedirect' => Router::url('/user/login'),
'queryParam' => 'redirect',
]);
// Load identifiers, ensure we check email and password fields
$authenticationService->loadIdentifier('Authentication.Password', [
'resolver' => [
'className' => 'Authentication.Orm',
'userModel' => 'User',
],
'fields' => [
'username' => 'DNI_CIF',
'password' => 'password',
]
]);
// Load the authenticators, you want session first
$authenticationService->loadAuthenticator('Authentication.Session');
// Configure form data check to pick email and password
$authenticationService->loadAuthenticator('Authentication.Form', [
'fields' => [
'username' => 'DNI_CIF',
'password' => 'password',
],
'loginUrl' => Router::url('/user/login'),
]);
return $authenticationService;
}
But I'm having this error:
.......object(Authentication\Authenticator\Result)#826 (3) {
["_status":protected]=>
string(27) "FAILURE_CREDENTIALS_MISSING"
["_data":protected]=>
NULL
["_errors":protected]=>
array(1) {
[0]=>
string(27) "Login credentials not found"
}
}
Can someone tell my what I'm doing wrong?
I tried several combinations like:
'username' => '22175395Z',
'password' => '$2y$10$ND67aMGqm.qK86MW1wuW9OQLC9vyJQGUn2HnLuSInwrFbXQKBT.V.'
or:
'DNI_CIF' => '22175395Z',
'password' => 'prueba'
or
'username' => '22175395Z',
'password' => 'prueba'
but nothing works.
In order to validate against a password stored in the database, the stored password must be hashed, and the submitted password must not be.
A want to add, in case of someone having the same problem, to be careful if you are using a user added in Fixture to login because it's password may not be hashed and login test will not work. I added a user and used it in the login test.
This question is asked many times in the stack overflow but I tried every accepted solution.
I'm new to cake PHP and I was assigned to add JWT in our application. Previously the team used the default cake sessions. In order to integrate, I used admad/cakephp-jwt-auth. So In the AppController
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
$this->loadComponent('Recurring');
$this->loadComponent('Auth', [
'storage' => 'Memory',
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'user_name',
'password' => 'password',
],
'contain' => ['Roles']
],
'ADmad/JwtAuth.Jwt' => [
'parameter' => 'token',
'userModel' => 'CbEmployees',
'fields' => [
'username' => 'id'
],
'queryDatasource' => true
]
],
'unauthorizedRedirect' => false,
'checkAuthIn' => 'Controller.initialize'
]);
}
I have to use CbEmployees which is our user model.
Then in my custom controller, I add my login function
public function login()
{
$user = $this->Auth->identify();
if (!$user) {
$data = "Invalid login details";
} else {
$tokenId = base64_encode(32);
$issuedAt = time();
$key = Security::salt();
$data = JWT::encode(
[
'alg' => 'HS256',
'id' => $user['id'],
'sub' => $user['id'],
'iat' => time(),
'exp' => time() + 86400,
],
$key
);
}
$this->ApiResponse([
"data" => $data
]);
}
Then I call this function using postman with body
{
"username": "developer",
"password": "dev2020"
}
I always get the response as Invalid login details. So the suggested solution is to check the password data type and length. The password is varchar(255). Another solution is to check the password in the entity. In the entity I have
protected function _setPassword($password)
{
if (strlen($password) > 0) {
return Security::hash($password, 'sha1', true);
// return (new DefaultPasswordHasher)->hash($password);
}
}
I specifically asked why the team is using Security::hash($password, 'sha1', true); due to migration from cake 2 to cake 3 they have to use the same.
Why I'm getting always Invalid login details? What I'm doing wrong here? I can log in the using the same credentials when I'm using the application.
I copied code from examples to create a basic login screen based on the table individuals with email and password. My AppController has this:
$this->loadComponent('Auth', [
'authenticate' => [
'Form' => [
'fields' => ['username' => 'email', 'password' => 'password'],
'userModel' => 'Individuals']
],
'loginAction' => [
'controller' => 'Individuals',
'action' => 'login'
],
'loginRedirect' => [
'controller' => 'Associations',
'action' => 'login'
],
'logoutRedirect' => [
'controller' => 'Association',
'action' => 'login',
'home'
]
]);
Password resets are done via a token emailed to the user. The controller saves the unencrypted value and /src/Model/Entity/Individual.php has _setPassword that ensures the database has an encrypted value. Every save for the same password is different but that, I gather, is normal.
protected function _setPassword($password) {
if (strlen($password) > 0) {
return (new DefaultPasswordHasher)->hash($password);
}
}
My login function started with the standard stuff, but it always returns false
$user = $this->Auth->identify();
My login function now has this debug code that always gets a "no match"
debug($this->request->data);
$email = $this->request->data['email'];
$pwd = $this->request->data['password'];
$user = $this->Individuals->find()
->select(['Individuals.id', 'Individuals.email', 'Individuals.password'])
->where(['Individuals.email' => $email])
->first();
if ($user) {
if ((new DefaultPasswordHasher)->check($pwd, $user->password)) {
debug('match');
}
else{
debug('no match');
}
if ($user->password == (new DefaultPasswordHasher)->hash($pwd)) {
debug('match2');
}
else {
debug('no match2');
}
}
There's a lot more code in and around that and I'm pretty confident I've got it right. Let me know if you need more. I'm keen to crack this.
thanks in advance.
I have set up my website so only add and login are only accessible before the user log in. And when he log in, he is redirected to the home page.
But when the user tries to log in, the login page refreshes and it shows this message "Username or password is incorrect" which is from the action login of my controller.
I verified and it's "$this->Auth->login()" which is not working.
In my database, i used these fields for the user table: id, password, nom, prenom, username.
Here is the login function code from my controller UsersController:
public function login()
{
if ($this->request->is('post'))
{
if ($this->Auth->login())
{
return $this->redirect($this->Auth->redirectUrl());
}
else
{
$this->Session->setFlash(__('Username or password is incorrect'));
}
}
}
Here is the login view code:
<?php
echo $this->Session->flash('auth');
echo $this->Form->create('User');
echo $this->Form->input('username', array('label' => 'Votre pseudo: '));
echo $this->Form->input('password', array('label' => 'Votre mot de passe: '));
echo $this->Form->end('Se connecter');
?>
Here is User model code:
<?php
App::uses('AppModel', 'Model');
App::uses('SimplePasswordHasher', 'Controller/Component/Auth');
class User extends AppModel
{
public $hasMany = array('Compte','ComptesUtilisateur');
public function beforeSave($options = array()) {
Security::setHash('md5');
if(isset($this->data[$this->alias]['password']))
{
$passwordHasher= new SimplePasswordHasher();
$this->data[$this->alias]['password'] = $passwordHasher->hash($this->data[$this->alias]['password']);
}
return true;
}
}
?>
And here AppController.php code:
class AppController extends Controller {
var $components = array(
'Auth' => array(
'authError' => "Etes-vous sûr(e) d'avoir l'autorisation pour y accéder?",
'loginError' => "Votre pseudo ou votre mot de passe est incorrect",
'loginAction' => array(
'controller' => 'users',
'action' => 'login'
),
'loginRedirect' => array('controller' => 'pages', 'action' => 'home'),
'logoutRedirect' => array('controller' => 'users', 'action' => 'login'),
'authenticate' => array(
'Form' => array(
'fields' => array(
'username' => 'username',
'password' => 'password'
),
'passwordhasher' => array(
'className' => 'Simple',
'hashType' => 'md5'
)
)
)
),
'Session'
);
public function beforeFilter()
{
$this->Auth->allow('login');
}
public function beforeRender()
{
$this->set('auth', $this->Auth->loggedIn());
}
}
I searched the solution on forums but i found nothing.
Any indication?
Thanks,
Louberlu.
I would like to implement CakePHP 2 website over existing database with plain-text password field.
This is my AppController
class AppController extends Controller {
public $components = array(
'Session',
'Auth' => array(
'loginRedirect' => array('controller' => 'users', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'users', 'action' => 'home'),
'authError' => 'You cannot view this page',
'authorize' => array('Controller'),
'authenticate' => array(
'Form' => array(
'userModel' => 'User',
'fields' => array('username' => 'user_id', 'password' => 'user_password')
)
)
)
);
public function isAuthorized($user) {
return true;
}
function beforeFilter() {
$this->Auth->allow('home');
//$this->Auth->authenticate = $this->User;
parent::beforeFilter();
}
This is my UserController.
class UsersController extends AppController {
public $paginate = array(
'fields' => array('user_id', 'user_desc', 'user_password'),
'limit' => 25,
'order' => array(
'user_id' => 'asc'
)
);
function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
$this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash('Cannot Login');
}
}
}
}
This is my User model
class User extends AppModel {
public $name = 'User';
public $primaryKey = 'user_id';
public $belongsTo = 'Group';
}
According to those files above, when I pressed the Login button on login.ctp, I saw
select * from users where user_password = 'this_is_hashing_password'
on the sql dump section.
So, how to turn-off the automatic hashing algorithm, so the login() will compare the user input to the database stored password as plain-text???
I have tried lots of reading on the CakePHP book but I cannot find any, also using hashPasswords($data) technique which found from the internet is not working.
Please help.
Kongthap.
The best answer really is to batch-process your stored passwords so they are hashed, however there are cases where you may be adding a Cake app to an existing application that hashes passwords differently (say by not hashing them at all), so the question is valid even if the goal in this case is not.
Try these resources for modifying Cake's password hashing function, depending on your Cake version:
Cake 2.x
Cake 1.3
I got plain text password working in Cakephp 3, this should only be use for DEVELOPMENT purpose, you should never store password in plain text in production.
That being said, during development, plain text password allows me to focus on login instead of implementing a fully functional user encrypt/decrypt logic. Which is going to be replaced by an OAuth / SAML module anyway...
OK here comes the source code:
ROOT/src/Auth/PlainTextPasswordHasher.php
<?php
namespace App\Auth;
use Cake\Auth\AbstractPasswordHasher;
/**
* Plain text password for demo use, DO NOT PUSTH THIS TO PROD
*/
class PlainTextPasswordHasher extends AbstractPasswordHasher
{
public function hash($password)
{
return $password;
}
public function check($password, $hashedPassword)
{
return $password === $hashedPassword;
}
}
ROOT/src/Controller/PagesController.php
<?php
class PagesController extends AppController
{
public function initialize()
{
parent::initialize();
$this->loadComponent('Auth', [
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'username',
'password' => 'password',
],
'passwordHasher' => [
'className' => 'PlainText',
],
'userModel' => 'YourUsers',
]
],
'loginAction' => [
'controller' => 'Logins',
'action' => 'login'
]
]);
}
}
Source: This video https://www.youtube.com/watch?v=eASSNS1f3V4 and this section of the official doc: https://book.cakephp.org/3.0/en/controllers/components/authentication.html#creating-custom-password-hasher-classes