CakePHP 3.0 - Login not working - cakephp

I've been following the CakePHP 3.0 tutorials (Bookmarker & Blog) regarding the Login/Authentication sections and applying it to my own code, but I can't seem to get it working properly.
I'm able to see all indexes without even being logged in. Logging into the system does not work; the login page just refreshes.
EDIT: Okay, seems like my test users were duds, I made a new user and it can login. However, I still have the issue of non-users being able to see indexes of tables (they can't create any variables in any of the tables apart from User, which has been allowed specifically).
EDIT2: I fixed it by removing the beforeFilter function in AppController.
User Controller:
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\Event\Event;
class UsersController extends AppController
{
public function beforeFilter(Event $event)
{
parent::beforeFilter($event);
$this->Auth->allow(['add', 'logout']);
}
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(__('Incorrect username or password, please try again.'));
}
}
public function logout()
{
$this->Flash->success('You are now logged out.');
return $this->redirect($this->Auth->logout());
}
public function index()
{
$this->set('users', $this->Users->find('all'));
}
public function view($id)
{
$user = $this->Users->get($id);
$this->set(compact('user'));
}
}
App Controller:
<?php
namespace App\Controller;
use Cake\Controller\Controller;
use Cake\Event\Event;
class AppController extends Controller
{
public function initialize()
{
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'loginRedirect' => [
'controller' => 'Users',
'action' => 'index'
],
'logoutRedirect' => [
'controller' => 'Pages',
'action' => 'display',
'home'
]
]);
}
}
User Table:
<?php
namespace App\Model\Table;
use Cake\ORM\Table;
use Cake\Validation\Validator;
class UsersTable extends Table
{
public function validationDefault(Validator $validator)
{
$validator
->integer('id')
->allowEmpty('id', 'create');
$validator
->requirePresence('username', 'create')
->notEmpty('username', 'A username is required');
$validator
->requirePresence('password', 'create')
->notEmpty('password', 'A password is required');
$validator
->email('email')
->requirePresence('email', 'create')
->notEmpty('email', 'An email is required');
$validator
->requirePresence('role', 'create')
->notEmpty('role', 'inList', [
'rule' => ['inList', ['admin', 'artist', 'engineer']],
'message' => 'Please enter a valid role'
]);
return $validator;
}
}

I managed to fix it by removing the beforeFilter function in AppController.

public function beforeSave(Event $event)
{
$entity = $event->data['entity'];
// Make a password for digest auth.
$entity->digest_hash = DigestAuthenticate::password(
$entity->username,
$entity->password,
env('SERVER_NAME')
);
return true;
}

Related

Cakephp 3.7.4 Auth hash password Not working

I am trying to implement auth login and register cakephp 3.7.4
I have used following code for UsersController add method
public function add()
{
$this->viewBuilder()->setLayout('login');
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
$post = $this->request->getData();
$post['created'] = date('Y-m-d H:i:s');
$post['modified'] = date('Y-m-d H:i:s');
$user = $this->Users->patchEntity($user, $post);
if ($this->Users->save($user)) {
$this->Flash->success(__('The user has been saved.'));
return $this->redirect(['action' => 'login']);
}
$this->Flash->error(__('Unable to add the user.'));
}
$this->set('user', $user);
}
But it can't save password in Hash Format
I have also create entity and used this function but it also not helped me
class User extends Entity
{
protected $_accessible = [
'email' => true,
'password' => true
];
protected $_hidden = [
'password'
];
protected function _setPassword($password){
return(new DefaultPasswordHasher)->hash($password);
}
}
I installed a fresh Cake 3.7.4 installation, baked a users table, users controller and users table/entity. The following code for the User Class successfully hashed the password before it is written to the database. Please compare it with your code.
namespace App\Model\Entity;
use Cake\Auth\DefaultPasswordHasher;
use Cake\ORM\Entity;
class User extends Entity
{
protected $_accessible = [
'email' => true,
'password' => true,
'modified' => true,
'created' => true
];
protected $_hidden = [
'password'
];
protected function _setPassword($password)
{
return (new DefaultPasswordHasher())->hash($password);
}
}
Just use parenthesis around DefaultPasswordHaser():
return(new DefaultPasswordHasher())->hash($password);

DefaultPasswordHasher store password as plain text

Am using cakephp 3 and i want to create login sistem on my app. I follow blog tutorial for auth. When i create new user password is stored as plain text, its not hashed. I dont know what do wrong. Check my code
I create table:
CREATE TABLE users (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50),
PASSWORD VARCHAR(255),
role VARCHAR(20),
created DATETIME DEFAULT NULL,
modified DATETIME DEFAULT NULL
);
Also i create UsersTable and entity Users
class UsersTable extends Table
{
/**
* Initialize method
*
* #param array $config
*/
public function initialize(array $config)
{
$this->table('users');
$this->primaryKey('id');
}
}
class User extends Entity
{
protected $_accessible = [
'username' => true,
'password' => true
];
protected function _setPassword($password) {
return (new DefaultPasswordHasher)->hash($password);
}
}
// App\Controller\AppController.php
$this->loadComponent('Auth', [
'loginRedirect' => [
'controller' => 'Users',
'action' => 'index'
],
'logoutRedirect' => [
'controller' => 'Pages',
'action' => 'display',
'home'
]
]);
And inside UsersController i add:
public function beforeFilter(Event $event)
{
parent::beforeFilter($event);
$this->Auth->allow('add', 'logout');
}
// Login
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'));
}
}
// Add
public function add() {
$user = $this->Users->newEntity($this->request->data);
if ($this->request->is('post')) {
if ($this->Users->save($user)) {
$this->Flash->success(__('The user has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('Unable to add the user.'));
}
$this->set(compact('user'));
}

Cakephp 3.0 Login

I'm facing trouble with my login system. I managed to register my user in my database but whenever I try to log in, it keeps prompting "Invalid email or password, try again".
This is my model:
<?php
namespace App\Model\Table;
use Cake\ORM\Table;
use Cake\Validation\Validator;
class UsersTable extends Table
{
public function validationDefault(Validator $validator)
{
return $validator
->notEmpty('email', 'A email is required')
->add('email', 'valid' , ['rule'=> 'email'])
->add('email', [
'unique' => ['rule' => 'validateUnique', 'provider' => 'table']
])
->requirePresence('email','create')
->notEmpty('password', 'A password is required')
->notEmpty('role', 'A role is required')
->add('role', 'inList', [
'rule' => ['inList', ['admin', 'author']],
'message' => 'Please enter a valid role'
]);
}
}
My controller:
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\Event\Event;
use Cake\Network\Exception\NotFoundException;
class UsersController extends AppController
{
public function beforeFilter(Event $event)
{
parent::beforeFilter($event);
$this->Auth->allow(['add', 'logout']);
}
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 email or password, try again'));
}
}
public function logout()
{
return $this->redirect($this->Auth->logout());
}
public function index()
{
$this->set('users', $this->Users->find('all'));
}
public function view($id)
{
if (!$id) {
throw new NotFoundException(__('Invalid user'));
}
$user = $this->Users->get($id);
$this->set(compact('user'));
}
public function add()
{
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user)) {
$this->Flash->success(__('The user has been saved.'));
return $this->redirect(['action' => 'add']);
}
$this->Flash->error(__('Email already existed.'));
}
$this->set('user', $user);
}
}
AppController:
<?php
namespace App\Controller;
use Cake\Controller\Controller;
use Cake\Event\Event;
class AppController extends Controller
{
public function initialize()
{
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'authorize' => ['Controller'],
'loginRedirect' => [
'controller' => 'Articles',
'action' => 'index'
],
'logoutRedirect' => [
'controller' => 'Pages',
'action' => 'display',
'home'
]
]);
}
public function isAuthorized($user)
{
if (isset($user['role']) && $user['role'] === 'admin') {
return true;
}
return false;
}
public function beforeFilter(Event $event)
{
$this->Auth->allow(['index', 'view', 'display']);
}
}
login.ctp
<div class="users form">
<?= $this->Flash->render('auth') ?>
<?= $this->Form->create() ?>
<fieldset>
<legend><?= __('Please enter your username and password') ?></legend>
<?= $this->Form->input('email') ?>
<?= $this->Form->input('password') ?>
</fieldset>
<?= $this->Form->button(__('Login')); ?>
<?= $this->Form->end() ?>
</div>
I think the problem comes from the AppController
Have a quick look at this : CookBook CakePHP 3.0 Example Bookmarker Part 1
The login part is here : CookBook CakePHP 3.0 Example Bookmarker Part 2
Find the similarities with your project, try to make an analogy, a relation.
Thanks guys! Managed to find the answer after referring to the tutorials. Turns out i miss out
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'email',
'password' => 'password'
All good now! Cheers =)

Cakephp 3 - public function add doesn't work with isAuthorized

I have a little problem with the isAuthorized function.
When I use the public function add, isAuthorized doesn't recognize the action request. I changed the name to 'addv' and now it's working. So why? Why can't I use the word 'add'? I used it twice on another project and I used it once on my current project.
Thanks you for you help !
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\Event\Event;
use Cake\Validation\Validator;
class VideosController extends AppController{
public function isAuthorized($user){
if(in_array($this->request->action, ['addv'])){
die();
if($user){
return true;
}
}
return parent::isAuthorized($user);
}
public function addv($idc= null,$idg = null){
debug($idc);
debug($this->request->action);
}
}
?>
AppController
class AppController extends Controller {
public function initialize() {
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'authorize' => ['Controller'],
'loginRedirect' => [
'controller' => 'Pages',
'action' => 'display',
'home'
],
'logoutRedirect' => [
'controller' => 'Pages',
'action' => 'display',
'home'
]
]);
$this->loadComponent('RequestHandler');
$this->set('info_session', $this->Auth->user());
}
public function beforeFilter(Event $event){
$this->Auth->allow(['register']);
$this->Auth->allow(['display']);
$this->Auth->allow(['controller' => 'Users', 'action' => 'add']);
}
public function isAuthorized($user){
if(isset($user['grade']) && $user['grade']=== 3){
return true;
}
}
}

Auth login action not generating query in CakePHP

I have a simple login form, just like the Cake Blog Tutorial.
It works like a charm when I use 'UsersController' and 'User' model naming conventions, passing the rights queries in debug.
But when I change it to other name, Alunos in my case, it generates no QUERY and give me 'Incorrect username and/or password.'.
My login.ctp
<H1> Login </H1>
<?php
debug($this->data);
echo $this->Form->create('Aluno', array('action' => 'login'));
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->end('Login');
?>
My AppController
<?php
class AppController extends Controller {
public $components = array (
'Session',
'Auth' => array (
'loginAction' => array ('controller'=>'alunos', 'action'=>'login'),
'loginRedirect'=>array ('controller'=>'alunos', 'action'=>'inicio'),
'logoutRedirect'=>array ('controller'=>'alunos', 'action'=>'index'),
'authError'=>"Ops, você não está autorizado a fazer isso.",
'authorize'=>array('Controller'),
)
);
public function isAuthorized($user) {
return true;
}
public function beforeFilter() {
$this->Auth->allow('index', 'add');
$this->set('logged_in', $this->Auth->loggedIn());
$this->set('current_user', $this->Auth->user());
}
}
And my 'AlunosController.php' (see that its not USERSController, like common codes)
<?php
class AlunosController extends AppController {
public $name = 'Alunos';
public function beforeFilter(){
parent::beforeFilter();
}
public function index() {}
public function login(){
debug($this->Auth->login());
if ($this->request->is('post')) {
if ($this->Auth->login()){
$this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash('Incorrect username and/or password.');
}
}
}
public function logout() {
$this->redirect($this->Auth->logout());
}
public function add() {
debug($this->Auth->login());
if($this->request->is('post')) {
if ($this->Aluno->save($this->request->data)) {
$this->Session->setFlash('Cadastrado.');
}else {
$this->Session->setFlash('Falha no cadastro.');
}
}
}
public function inicio() {
debug($this->Auth->login());
}
}
?>
My debug($this->data) in login.ctp result:
array(
'Aluno' => array(
'password' => '*****',
'username' => 'anyuser'
)
)
What am I doing wrong?
Add this code to your app controller:
function beforeFilter() {
$this->Auth->userModel = 'Aluno'; <-- Should be singular. My mistake
parent::beforeFilter();
}
UPDATE FOR CAKE2
// Place in beforeFilter() of AppController.php
$this->Auth->authenticate = array(
'Form' => array(
'userModel' => 'Aluno'
)
);
Your problem is because you are not telling cake what to use for a user table. This is why your first instance works, and the second does not.
Change this:
echo $this->Form->create('Aluno', array('action' => 'login'));
to:
echo $this->Form->create('Alunos', array('url' => 'alunos/login'));
To call Alunos Controller's login() method.

Resources