I'm playing around with CakePHP and can't seem to get the login working. It seems that $this->Auth->identify() is constantly returning false and not allowing me to login.
I've read all previous posts regarding my issue, however, none have provided me with a solution. The users I am trying to log in as have all been created using the cake password hasher, which I have checked have been stored in the database. I have checked the password field length in the database, which is set to varchar (255), I've checked the Auth => authenticate => Form => fields are set to the correct values (the login.ctp fields are also correct). I also tried changing the $this->Form->control() to $this->Form->input() as someone suggested, with no luck.
AppController:
$this->loadComponent('Auth', [
'loginRedirect' => [
'controller' => 'Users',
'action' => 'classes'
],
'logoutRedirect' => [
'controller' => 'Users',
'action' => 'index'
]
]);
$this->loadComponent('Auth', [
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'email',
'password' => 'password'
]
]
],
'loginAction' => [
'controller' => 'Users',
'action' => 'login'
]
]);
login() function in UsersController:
public function login()
{
if ($this->request->is('post')) {
$user = $this->Auth->identify();
pj($user);
if ($user) {
$this->Auth->setUser($user);
return $this->redirect(['controller' => 'users']);
}
$this->Flash->error(__('Invalid username or password, try again'));
}
}
login.ctp:
<div class="users form">
<?= $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>
EDIT: I forgot to add that I can successfully add users, I just can't log them in.
You are loading the AuthComponent twice in AppController. The second load with the config for form fields is not loaded.
Load the component one time with the wanted config.
$this->loadComponent('Auth', [
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'email',
'password' => 'password'
]
]
],
'loginRedirect' => [
'controller' => 'Users',
'action' => 'classes'
],
'logoutRedirect' => [
'controller' => 'Users',
'action' => 'index'
],
'loginAction' => [
'controller' => 'Users',
'action' => 'login'
]
]);
Related
I need help with saving/updating belongsToMany data with custom field.
I have a tables acl, managers, groups, sections.
I need to save/update data in acl table from sections/edit or sections/add
acl table
id|target_id|target_type|section_id
I need set target_id data 'user' or 'group' depending entities.
edit.ctp
echo $this->Form->control('managers._ids', ['class' => 'multiple', 'multiple' => true]);
echo $this->Form->control('groups._ids', ['class' => 'multiple', 'multiple' => true]);
SectionsTable.php
$this->belongsToMany('Managers', [
'joinTable' => 'acl',
'through' => 'Acl',
'foreignKey' => 'section_id',
'targetForeignKey' => 'target_id',
'conditions' => [
'target_type' => 'user'
]
]);
$this->belongsToMany('Groups', [
'joinTable' => 'acl',
'through' => 'Acl',
'foreignKey' => 'section_id',
'targetForeignKey' => 'target_id',
'conditions' => [
'target_type' => 'group'
]
]);
AclTable.php
$this->belongsTo('Managers', [
'foreignKey' => 'target_id',
'conditions' => [
'target_type' => 'user'
]
]);
$this->belongsTo('Groups', [
'foreignKey' => 'target_id',
'conditions' => [
'target_type' => 'group'
]
]);
I tried to use _joinData, but nothing work
before and after patchEntity()
foreach ($section->groups as &$group) {
$group->_joinData = ['target_type' => 'group'];
}
whithout save()
foreach ($this->request->data['managers']['_ids'] as $id) {
$manager = $this->Sections->Managers->get($id);
$manager->_joinData = new Entity(['target_type' => 'user'], ['markNew' => true]);
$this->Sections->Managers->link($section, [$manager]);
}
$this->request->data has a follow structure:
[
'controller' => '*',
'action' => '*',
'title' => '*',
'managers' => [
'_ids' => [
'0' => '*',
'1' => '*',
'2' => '*',
]
],
'groups' => [
'_ids' => [
'0' => '*',
'1' => '*',
'2' => '*',
]
]
]
Alltimes error: Cannot insert row, some of the primary key values are missing. Got (3, 114, ), expecting (target_id, section_id, target_type)
Now working with following code
$section = $this->Sections->patchEntity($section, $this->request->data, ['associated' => ['Managers', 'Groups']]);
foreach ($section->managers as &$manager) {
$manager->_joinData = new Entity([
'target_id' => $manager->id,
'target_type' => 'user',
'section_id' => $section->id
], ['markNew' => true]);
}
foreach ($section->groups as &$group) {
$group->_joinData = new Entity([
'target_id' => $group->id,
'target_type' => 'group',
'section_id' => $section->id
], ['markNew' => true]);
}
if ($this->Sections->save($section, ['associated' => ['Managers', 'Groups']])) {
$this->Flash->success(__('The section has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The section could not be saved. Please, try again.'));
But, maybe can do it don't listing all fields?
Also I need to create/add new records to acl table when adding new section
But section_id unavailable until save(). Can I save/add acl records by associations
Updated
AclTAble.php
$this->setPrimaryKey(['target_type', 'target_id', 'section_id']);
.
.
.
$this->belongsTo('Managers', [
'foreignKey' => 'target_id',
'conditions' => [
'target_type' => 'user'
]
]);
$this->belongsTo('Groups', [
'foreignKey' => 'target_id',
'conditions' => [
'target_type' => 'group'
]
]);
With primaryKey id, adding and editing entities working, but editing makes dublicates, it's are not perfect for me. And in documentations use composite primaryKey, so i use ['target_id', 'target_type', 'section_id'], with it cake don't make dublicated, but aggain show me error: Cannot insert row, some of the primary key values are missing. Got (8, 197, ), expecting (target_id, section_id, target_type)
I have a frustrating bug in Cakephp 3.7.1 . I know that a similar bug has been reported in
https://discourse.cakephp.org/t/invoked-extension-not-recognized-configured-html/5355 .
The bug is that the xml extension is working yet the html extention is not.
Here is my routes file.
<?php
use Cake\Routing\Router;
use Cake\Routing\Route\DashedRoute;
Router::defaultRouteClass(DashedRoute::class);
$routesArray = [
'/' => [
'defaults' => [
'controller' => 'Pages',
'action' => 'view',
'home',
],
'options' => [],
],
'/pages/*' => [
'defaults' => [
'controller' => 'Pages',
'action' => 'display',
],
'options' => [],
],
'/pages/:page' => [
'defaults' => [
'controller' => 'Pages',
'action' => 'view',
],
'options' => [
'pass' => [
'page',
],
],
],
];
$languages = ['sn', 'fr', 'en'];
foreach ($languages as $language) {
Router::prefix($language, function ($routes) use ($routesArray, $language) {
$routes->setExtensions([
'xml',
'html',
]);
foreach ($routesArray as $key => $value) {
if (!empty($value['options']['_name'])) {
$value['options']['_name'] .= $language;
}
$routes->connect(
$key,
$value['defaults'],
$value['options']
);
}
$routes->fallbacks(DashedRoute::class);
});
}
Router::scope('/', function ($routes) use ($routesArray) {
$routes->setExtensions([
'xml',
'html',
]);
foreach ($routesArray as $key => $value) {
$routes->connect(
$key,
$value['defaults'],
$value['options']
);
}
$routes->fallbacks(DashedRoute::class);
});
This is probably going to be fixed in 3.7.2, see https://github.com/cakephp/cakephp/pull/12845.
Until then, one workaround would be to unset the extension on the request handler component in the Controller.startup event, for example like this in your AppController class' beforeFilter() method:
public function beforeFilter(\Cake\Event\Event $event)
{
parent::beforeFilter($event);
$this->getEventManager()->on('Controller.startup', function () {
if ($this->RequestHandler->ext === 'html') {
$this->RequestHandler->ext = null;
}
});
// ...
}
I am using cakephp 3 installed on xampp. It was running fine. but now I got the error after login.
database table relation:
users hasMany roles
roles hasMany users
relational table:roles_users
AppController.php
$this->loadComponent('TinyAuth.Auth', [
'loginAction' => [
'controller' => 'Users',
'action' => 'login'
],
'loginRedirect' => [
'controller' => 'Users',
'action' => 'dashboard'
],
'authError' => 'Did you really think you are allowed to see that?',
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'username',
'password' => 'password'
],
// 'scope' => ['Users.active' => true],
'contain' => ['Roles']
]
],
]
);
I got the following error in error.log file
2017-02-02 01:04:08 Error: [Cake\Core\Exception\Exception] Missing
TinyAuth role id field (Auth.User.role_id) in user session
It looks you are using muli-role process, but you may be forgot to add multi-role enable
// in your app.php
'TinyAuth' => [
'multiRole' => true,
...
],
I have two tables seller_businesses and seller_business_categories. and their association is as follows
SellerBusinessesTable.php
$this->hasMany('SellerBusinessCategories', [
'foreignKey' => 'seller_business_id'
]);
SellerBusinessCategories.php
$this->belongsTo('SellerBusinesses', [
'foreignKey' => 'seller_business_id',
'joinType' => 'INNER'
]);
I'm using a single form to save data in both tables
<?= $this->Form->create($sellerBusiness, ['type' => 'file']) ?>
<?= $this->Form->input('company_name') ?>
<?= $this->Form->input('proof', ['type' => 'file']) ?>
<?= $this->Form->input('seller_business_categories._category_ids', ['multiple' => true, 'options' => $categories]) ?>
<?= $this->Form->button('submit', ['type' => 'submit']) ?>
<?= $this->Form->end() ?>
And controller action is
$sellerBusiness = $this->SellerBusinesses->newEntity();
if ($this->request->is('post')) {
$sellerBusiness->seller_id = $this->Auth->user('id');
$sellerBusiness = $this->SellerBusinesses->patchEntity($sellerBusiness, $this->request->data, [
'associated' => [
'SellerBusinessCategories'
]
]);
debug($sellerBusiness);
if ($save_s_b = $this->SellerBusinesses->save($sellerBusiness)) {
debug($save_s_b);
$this->Flash->success(__('The seller business has been saved.'));
return $this->redirect(['controller' => 'SellerBusinesses', 'action' => 'view', $save_s_b->id]);
} else {
$this->Flash->error(__('The seller business could not be saved. Please, try again.'));
}
}
But this is not saving record to seller_business_categories table.
From document Here
// Multiple select element for belongsToMany
echo $this->Form->input('tags._ids', [
'type' => 'select',
'multiple' => true,
'options' => $tagList,
]);
But this is not working. Is there any other way for hasMany
debug($this->request->data); gives
'seller_business_categories' => [
'_category_ids' => [
(int) 0 => '1',
(int) 1 => '2'
]
],
and debug($sellerBusiness); after patchEntity
object(App\Model\Entity\SellerBusiness) {
'seller_id' => (int) 16,
'company_name' => 'My company',
'seller_business_categories' => [
(int) 0 => object(App\Model\Entity\SellerBusinessCategory) {
(int) 0 => '1',
(int) 1 => '2',
'[new]' => true,
'[accessible]' => [
'*' => true
],
'[dirty]' => [
(int) 0 => true,
(int) 1 => true
],
'[original]' => [],
'[virtual]' => [],
'[errors]' => [],
'[invalid]' => [],
'[repository]' => 'SellerBusinessCategories'
}
],
'[new]' => true,
'[accessible]' => [
'*' => true,
],
'[dirty]' => [
'seller_id' => true,
'company_name' => true,
'seller_business_categories' => true,
],
'[original]' => [],
'[virtual]' => [],
'[errors]' => [],
'[invalid]' => [],
'[repository]' => 'SellerBusinesses'
}
and error
Error: SQLSTATE[HY000]:
General error: 1364 Field 'category_id' doesn't have a default value in seller_business_categories table
SellerBusinessesTable
$this->belongsToMany('Categories');
CategoriesTable
$this->belongsToMany('SellerBusinesses', [
'foreignKey' => 'category_id',
'targetForeignKey' => 'seller_business_id',
'joinTable' => 'categories_seller_businesses'
]);
// Pivot tables must be sorted alphabetically
bin/cake bake migration CreateCategoriesSellerBusinesses seller_business_id:integer category_id:integer created modified
CategoriesSellerBusinessesTable
$this->belongsTo('SellerBusinesses', [
'foreignKey' => 'seller_business_id',
'joinType' => 'INNER'
]);
$this->belongsTo('Categories', [
'foreignKey' => 'category_id',
'joinType' => 'INNER'
]);
Add.ctp
<?= $this->Form->create($sellerBusiness, ['type' => 'file']) ?>
...
<?= $this->Form->input('categories', ['type' => 'select', 'options' => $categories, 'multiple' => 'select', 'label' => __('Categories')]) ?>
...
<?= $this->Form->end() ?>
SellerBusinessesController
public function add()
{
$sellerBusiness = $this->SellerBusinesses->newEntity();
if ($this->request->is('post')) {
$sellerBusiness = $this->SellerBusinesses->patchEntity($sellerBusiness, $this->request->data);
$sellerBusiness->seller_id = $this->Auth->user('id');
if(isset($this->request->data['categories']))
{
$sellerBusiness -> categories = $this->SellerBusinesses->Categories->find()->where(['id IN' => $this->request->data['categories']])->all()->toArray();
}
if ($this->SellerBusinesses->save($sellerBusiness)) {
$this->Flash->success(__('The sellerBusiness has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The seller could not be saved. Please, try again.'));
}
}
$categories = $this -> SellerBusinesses-> Categories-> find('treeList');
$this->set(compact('sellerBusiness', 'categories'));
$this->set('_serialize', ['sellerBusiness']);
I have scoured the internet and tried figuring this out with the docs, but I don't understand what I am doing wrong.
I have users that can have a membership and many orders. The membership and orders are also associated with a membership level. I am unsure if these associations are correct, but I think they are.
Here are my associations:
Users:
$this->hasOne('Memberships', [
'foreignKey' => 'user_id',
'joinType' => 'INNER'
]);
$this->hasMany('MembershipOrders', [
'foreignKey' => 'user_id',
'joinType' => 'INNER'
]);
Orders:
$this->belongsTo('Users', [
'foreignKey' => 'user_id',
'joinType' => 'INNER'
]);
$this->hasOne('MembershipLevels', [
'foreignKey' => 'membership_level_id',
'joinType' => 'INNER'
]);
Memberships:
$this->belongsTo('Users', [
'foreignKey' => 'user_id',
'joinType' => 'INNER'
]);
$this->hasOne('MembershipLevels', [
'foreignKey' => 'membership_level_id',
'joinType' => 'INNER'
]);
MembershipLevels:
$this->belongsToMany('MembershipOrders', [
'foreignKey' => 'membership_level_id',
'joinType' => 'INNER'
]);
$this->belongsToMany('Memberships', [
'foreignKey' => 'membership_level_id',
'joinType' => 'INNER'
]);
In my users controller I am trying to have a function that will add the user, a membership record, and an order for that user.
I am trying to make sure that validation errors are shown if any for the associated data in my form.
In the controller function I have:
public function checkout($id = null)
{
$user = $this->Users->newEntity($this->request->data(), [
'associated' => [
'MembershipOrders' => ['associated' => ['MembershipLevels']]
]
]);
$membershipLevel = $this->Users->Memberships->MembershipLevels->get($id);
if ( $this->request->is('post') ) {
$user = $this->Users->patchEntity( $user, $this->request->data(), [
'associated' => [
'MembershipOrders' => ['associated' => ['MembershipLevels']]
]
]);
if ( $this->Users->save($user, ['associated' => ['MembershipOrders' => ['associated' => ['MembershipLevels']]]]) ) {
$this->Flash->success(__('User has been added.'));
} else {
$this->Flash->error(__('User could not be added. Please, try again.'));
}
}
$this->set(compact('user', 'membershipLevel'));
$this->set('_serialize', ['user', 'membershipLevel']);
}
A simple form for my view is:
<?= $this->Form->create($user, ['id' => 'userForm']) ?>
<fieldset>
<legend><?= __('Primary Member') ?></legend>
<?= $this->Form->input('full_name', ['required' => false]) ?>
<?= $this->Form->input('username', ['required' => false]) ?>
<?= $this->Form->input('email', ['required' => false]) ?>
<?= $this->Form->input('password', ['required' => false]) ?>
<?= $this->Form->input('password_confirmation', ['type' => 'password', 'required' => false]) ?>
<?= $this->Form->input('specialty', ['required' => false]) ?>
<?= $this->Form->input('membership_orders.0.billing_name', ['label' => 'Name', 'data-stripe' => 'name', 'required' => false] ) ?>
<?= $this->Form->input('membership_orders.0.billing_street_1', ['label' => 'Address 1', 'required' => false] ) ?>
<?= $this->Form->input('membership_orders.0.billing_street_2', ['label' => 'Address 2', 'required' => false] ) ?>
<?= $this->Form->input('membership_orders.0.billing_city', ['label' => 'City', 'data-stripe' => 'address_city', 'required' => false] ) ?>
</fieldset>
<?= $this->Form->button(__('Join'), ['id' => 'submitBtn', 'class' => 'btn']) ?>
<?= $this->Form->end() ?>
I have tried MembershipOrders, membershipOrders, the current membership_orders, and all with and without the .0 in the form and cannot get any validation errors for the order information. The billing info is to be added to the orders table and the exact table name is "membership_orders".
Shouldn't cake be sending associated validation errors to my form as well?