I'm new to CakePHP and just starting with the CookBook Examples. Now I want to create a simple registration and Login form with my custome Table columns. But the system do not want to insert the data! Where is my mistake? Is it right to tell him in the AppController which fields to use?
add.ctp=
<div class="users_form">
<?= $this->Form->create($user) ?>
<fieldset>
<legend><?= __('Add') ?></legend>
<?= $this->Form->input('username') ?>
<?= $this->Form->input('password') ?>
</fieldset>
<?= $this->Form->button(__('Submit')); ?>
<?= $this->Form->end() ?>
UsersTable.php
class UsersTable extends Table{
public function initialize(array $config)
{
parent::initialize($config);
$this->table('ab_login');
}
public function validationDefault(Validator $validator)
{
return $validator
->notEmpty('username', 'insert name')
->notEmpty('password', 'pw insert');
}
}
AppController.php
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'authenticate' => [
'Form' => [
'fields' => ['username' => 'ab_mail', 'password' => 'ab_pass']
]
]
]);
UsersController.php
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(__('inserted!'));
return $this->redirect(['action' => 'add']);
}
$this->Flash->error(__('Error!'));
}
$this->set('user', $user);
}
Change the form elements in your view to:
<?= $this->Form->input('ab_mail') ?>
<?= $this->Form->input('ab_pass') ?>
Need to Change in AppController.php
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'authenticate' => [
'Form' => [
'fields' => ['username' => 'username', 'password' => 'password'] // Password and Username fields are pre-define in cakephp.
]
]
]);
It will definitely work.
thanks :)
Related
I'm New to CakePHP is an amazing PHP framework I'm trying to build a new application
so I get to the part of login page this is my code when I try to login I get ' incorrect login '
and the password is hashed
AppController
public function beforeFilter(Event $event) {
$this->Auth->allow('display');
}
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler', [
'enableBeforeRedirect' => false,
]);
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'authenticate' => [
'Form' => [
'fields' => [
'username' => ' email',
'password' => 'password'
]
]
],
'loginAction' => [
'controller' => 'user',
'action' => 'login'
]
]);
/*
* Enable the following component for recommended CakePHP security settings.
* see https://book.cakephp.org/3.0/en/controllers/components/security.html
*/
//$this->loadComponent('Security');
}
}
//UserController
public function login(){
if($this->request->is('post')){
$user = $this->Auth->identify();
if($user){
$this->Auth->setUser($user);
return $this->redirect(['controller' => 'reference']);
}
// Bad Login
$this->Flash->error('Incorrect Login');
}
}
// Logout
public function logout(){
$this->Flash->success('You are logged out');
return $this->redirect($this->Auth->logout());
}
//Login.ctp
<div class="users form">
<?= $this->Flash->render() ?>
<?= $this->Form->create() ?>
<fieldset>
<legend><?= __("Merci de rentrer vos nom d'utilisateur et mot de passe") ?></legend>
<?= $this->Form->control('username') ?>
<?= $this->Form->control('password') ?>
</fieldset>
<?= $this->Form->button(__('Se Connecter')); ?>
<?= $this->Form->end() ?>
</div>
I am working on login and registration module in Cakephp 3 but is not able to login and while registration the password is also not hashed it is saving as plain text. I am getting error : Invalid username or password, try again.
I have followed some tutorial but some thing is missing which causes application to not properly logging in. Please help to sort out my issue.
Below is the complete code:
Login.ctp
<h1> Login </h1>
<p>Enter your username & password: </p>
<?php echo $this->Form->create();
echo $this->Form->input('email');
echo $this->Form->input('password');
echo $this->Form->button('Login');
echo $this->Form->end()
?>
AppController.ctp
<?php
namespace PanelAdmin\Controller;
use Cake\Event\Event;
use Cake\View\Helper\FlashHelper;
use Cake\Controller\Component\FlashComponent;
use App\Controller\AppController as BaseController;
class AppController extends BaseController
{
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'authorize'=> 'Controller',
'authenticate' => [
'Form' => [
// fields used in login form
'fields' => [
'username' => 'email',
'password' => 'password'
]
]
],
// login Url
'loginAction' => [
'controller' => 'Users',
'action' => 'login'
],
// where to be redirected after logout
'logoutRedirect' => [
'controller' => 'Topics',
'action' => 'index'//,
//'home'
],
// if unauthorized user go to an unallowed action he will be redirected to this url
'unauthorizedRedirect' => [
'controller' => 'Topics',
'action' => 'index'//,
//'home'
],
'authError' => 'Did you really think you are allowed to see that?',
]);
// Allow the display action so our pages controller still works and user can visit index and view actions.
$this->Auth->allow(['index','display','view']);
}
public function isAuthorized($user)
{
$this->Flash->error('You aren\'t allowed');
return false;
}
public function beforeFilter(Event $event)
{
$this->Auth->allow(['index', 'view', 'display']);
}
public function beforeRender(Event $event)
{
if (!array_key_exists('_serialize', $this->viewVars) &&
in_array($this->response->type(), ['application/json', 'application/xml'])
) {
$this->set('_serialize', true);
}
}
}
?>
UsersController.ctp
<?php
namespace PanelAdmin\Controller;
use Cake\Controller\Controller;
use Cake\ORM\TableRegistry;
use Cake\Event\Event;
class UsersController extends AppController
{
public function initialize()
{
parent::initialize();
$this->loadComponent('Flash'); // Include the FlashComponent
// Auth component allow visitors to access add action to register and access logout action
$this->Auth->allow(['logout', 'add']);
}
public function login()
{
if ($this->request->is('post')) {
// Auth component identify if sent user data belongs to a user
$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.'));
}
}
public function logout(){
$this->Flash->success('You successfully have loged 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('user',$user);
}
public function add()
{
$user = $this->Users->newEntity();
if($this->request->is('post')) {
$this->Users->patchEntity($user,$this->request->data);
if($this->Users->save($user)){
$this->Flash->success(__('Your account has been registered .'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('Unable to register your account.'));
}
$this->set('user',$user);
}
public function edit($id)
{
$user = $this->Users->get($id);
if ($this->request->is(['post', 'put'])) {
$this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user)) {
$this->Flash->success(__('Your profile data has been updated.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('Unable to update your profile.'));
}
$this->set('user', $user);
}
public function delete($id)
{
$this->request->allowMethod(['post', 'delete']);
$user = $this->Users->get($id);
if ($this->Users->delete($user)) {
$this->Flash->success(__('The user with id: {0} has been deleted.', h($id)));
return $this->redirect(['action' => 'index']);
}
}
}
?>
UsersTable.ctp
<?php
namespace App\Model\Table;
use Cake\ORM\Table;
use Cake\Validation\Validator;
use Cake\Auth\DefaultPasswordHasher;
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'
]);
}
}
?>
Entity : User.php
<?php
namespace App\Model\Entity;
use Cake\ORM\Entity;
use Cake\Auth\DefaultPasswordHasher;
class User extends Entity
{
protected $accessible = [
'*' => true,
'id' => false,
];
protected function _setPassword($password) {
if (strlen($password) > 0) {
return (new DefaultPasswordHasher)->hash($password);
}
}
}
?>
add.ctp
<h1>Register new user </h1>
<?php
echo $this->Flash->render('auth');
echo $this->Form->create($user);
echo $this->Form->input('name');
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->input('password2',array('label'=>"confirm password",'type'=>'password'));
echo $this->Form->input('email');
echo $this->Form->input('phone');
echo $this->Form->input('birthdate',[
'minYear' => date('Y') - 80,
'maxYear' => date('Y') - 10
]);
echo $this->Form->button(__('Register'));
echo $this->Form->end();
?>
I am working on a personal project and I have searched through multiple topics that are related to my issue and I cannot find a solution to my problem.
Whenever I enter an email and password on my login page it always give me an invalid username or password pop up. I debugged a part of code in my UserloginController and it just returns false. There is probably a problem here but i cannot see it.
Some solutions for other people were to change the VARCHAR length of the password field, my password field is already a VARCHAR(255) and it hashes properly so this is not the problem.
Here is my AppController
class AppController extends Controller
{
public function isAuthorized($user = null)
{
// Any registered user can access public functions
if (empty($this->request->params['prefix'])) {
return true;
}
// Only admins can access admin functions
if ($this->request->params['prefix'] === 'admin') {
return (bool)($user['role'] === 'admin');
}
// Default deny
return false;
}
public function initialize()
{
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'authenticate' => [
'Form' => [
'userModel' => 'userlogin',
'fields' => [
'username' => 'email',
'password' => 'password'
]
]
],
'loginAction' => [
'controller' => 'userlogin',
'action' => 'login'
],
'logoutRedirect' => [
'controller' => 'userlogin',
'action' => 'login'
],
]);
// Allow the display action so our pages controller
// continues to work.
$this->Auth->allow(['display']);
}
public function beforeRender(Event $event)
{
if (!array_key_exists('_serialize', $this->viewVars) &&
in_array($this->response->type(), ['application/json', 'application/xml'])
) {
$this->set('_serialize', true);
}
}
}
Here is my UserLoginController
class UserloginController extends AppController
{
public function initialize() {
parent::initialize();
$this->Auth->allow(['logout', 'add']);
}
//login
public function login(){
if ($this->request->is('post')) {
$user = $this->Auth->identify();
debug($this->Auth->identify()); // Returns False
if ($user) {
$this->Auth->setUser($user);
return $this->redirect($this->Auth->redirectUrl());
}
$this->Flash->error('Your username or password is incorrect.');
}
}
public function logout() {
$this->Flash->success('You are now logged out.');
return $this->redirect($this->Auth->logout());
}
public function beforeFilter(Event $event) {
parent::beforeFilter($event);
$this->Auth->allow('logout', 'login', 'index', 'add'); //you can add others here...
}
}
And Here is my Login.ctp
<br>
<div class="index large-4 medium-4 large-offset-4 medium-offset-4 columns">
<div class="panel">
<h1>Login</h1>
<?= $this->Form->create(); ?>
<?= $this->Form->input('email'); ?>
<?= $this->Form->input('password'); ?>
<?= $this->Form->button('Login'); ?>
<?= $this->Form->end(); ?>
Any sort of help will be greatly appreciated!
I am trying to upload image using cakephp 3. I tried it in cake 2.x, it worked fine there but not in cake 3.0. My image is uploaded but it is not getting saved in DB.
view
<div class="col-lg-8">
<div class="articles form large-9 medium-8 columns content">
<?= $this->Form->create($article,['type' => 'file']) ?>
<fieldset>
<legend><?= __('Add Article') ?></legend>
<?php
echo $this->Form->input('title', [ "class" => "form-control"]);
echo $this->Form->input('body', [ "class" => "form-control"]);
echo $this->Form->file('image',[ "class" => "form-control"]);
?>
</fieldset>
<?= $this->Form->button(__('Submit'), ["class" => "btn btn-primary"]) ?>
<?= $this->Form->end() ?>
</div>
Controller
public function add() {
$article = $this->Articles->newEntity();
if ($this->request->is('post')) {
$filepath = getcwd() . '/uploads/' . $this->request->data['image']['name'];
$filename = $this->request->data['image']['name'];
$article = $this->Articles->patchEntity($article, $this->request->data);
if ($this->Articles->save($article)) {
move_uploaded_file($this->request->data['image']['tmp_name'], $filepath);
$this->Flash->success(__('The article has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The article could not be saved. Please, try again.'));
}
}
$this->set(compact('article'));
$this->set('_serialize', ['article']);
}
Model
namespace App\Model\Table;
use App\Model\Entity\Article;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
class ArticlesTable extends Table
{
public function initialize(array $config)
{
parent::initialize($config);
$this->table('articles');
$this->displayField('title');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->hasMany('Comments', [
'foreignKey' => 'article_id'
]);
}
public function validationDefault(Validator $validator)
{
$validator
->add('id', 'valid', ['rule' => 'numeric'])
->allowEmpty('id', 'create');
$validator
->allowEmpty('title');
$validator
->allowEmpty('body');
$validator
->add('image', [
'fileSize' => [
'rule' => [
'fileSize', '<', '5MB'
],
'message' => 'Please upload file smaller than 5MB'
],
'mimeType' => [
'rule' => [
'mimeType', ['image/jpeg','image/png','image/jpg']
],
'message' => 'Please upload only png images'
]
]
)
->requirePresence('image', 'create')
->notEmpty('image');
return $validator;
}
}
I have found a solution myself but I am not sure whether it is the right way. But by doing this my problem has been solved.
public function add() {
$article = $this->Articles->newEntity();
if ($this->request->is('post')) {
$imageName = $this->request->data['image']['name'];
$filepath = getcwd() . '/uploads/' . $imageName;
$article = $this->Articles->patchEntity($article, $this->request->data);
$article->image = $imageName ;
if ($this->Articles->save($article)) {
move_uploaded_file($this->request->data['image']['tmp_name'], $filepath);
chmod($filepath, 0777);
$this->Flash->success(__('The article has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The article could not be saved. Please, try again.'));
}
}
$this->set(compact('article'));
$this->set('_serialize', ['article']);
}
I'm new to CakePhp framework and followed the blog tutorial.
Everything went smooth until authentication part.
The following two lines were the problem:
<?= $this->Form->input('Usuario') ?>
<?= $this->Form->input('Contraseña') ?>
The correct lines are:
<?= $this->Form->input('username') ?>
<?= $this->Form->input('password') ?>
This is my login method from UsersControllers.php, the debug line always returns false.
public function login()
{
if ($this->request->is('post')) {
debug($this->Auth->identify());
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
return $this->redirect($this->Auth->redirectUrl());
}
$this->Flash->error(__('Usuario o contraseña inválida, intente nuevamente'));
}
}
This is my user class
I had to change the line protected $_accessible = ['*' => true]; as appears in the tutorial, otherwise users wouldn't be saved.
class User extends Entity
{
// Make all fields mass assignable for now.
protected $_accessible = ['username' => true,'password'=>true,'role'=>true,'created'=>true,'modified'=>true];
// ...
protected function _setPassword($password)
{
return (new DefaultPasswordHasher)->hash($password);
}
// ...
}
This is my login.ctp
<div class="users form">
<?= $this->Flash->render('auth') ?>
<?= $this->Form->create() ?>
<fieldset>
<legend><?= __('Ingrese su usuario y contraseña') ?></legend>
<?= $this->Form->input('Usuario') ?>
<?= $this->Form->input('Contraseña') ?>
</fieldset>
<?= $this->Form->button(__('Login')); ?>
<?= $this->Form->end() ?>
</div>
These are my AppController.php methods:
public function initialize()
{
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'loginRedirect' => [
'controller' => 'Expedientes',
'action' => 'index'
],
'logoutRedirect' => [
'controller' => 'Pages',
'action' => 'display',
'home'
]
]);
}
public function beforeFilter(Event $event)
{
$this->Auth->allow(['index', 'view']);
}
At this point I can add users, their passwords are hashed but I can't login.
Any help will be greatly appreciated.
Thanks in advance.
Alternatively, while setting your Auth componenent configurations, you can set which fields, in your db, serve as username and password
$this->Auth->config('authenticate', [
'Form' => [
'fields' => [
'username'=>'email',
'password' => 'password'
],
'userModel' => 'Users'
]
]);
Thanks #ndm for the answer. I translated username and password fields in the following lines:
<?= $this->Form->input('Usuario') ?>
<?= $this->Form->input('Contraseña') ?>
Correct lines are:
<?= $this->Form->input('username') ?>
<?= $this->Form->input('password ') ?>