I'm trying to setup ZfcUser with BjyAuthorize. I'm getting the following error when trying to access the guarded route "/user".
Fatal error: Uncaught exception 'Zend\Permissions\Acl\Exception\InvalidArgumentException' with message 'Role '3' not found' in /home/brian/dev/ptapp/app/vendor/zendframework/zendframework/library/Zend/Permissions/Acl/Role/Registry.php:106
Stack trace:
#0 /home/brian/dev/ptapp/app/vendor/zendframework/zendframework/library/Zend/Permissions/Acl/Role/Registry.php(67): Zend\Permissions\Acl\Role\Registry->get('3')
#1 /home/brian/dev/ptapp/app/vendor/zendframework/zendframework/library/Zend/Permissions/Acl/Acl.php(112): Zend\Permissions\Acl\Role\Registry->add(Object(Zend\Permissions\Acl\Role\GenericRole), Array)
#2 /home/brian/dev/ptapp/app/vendor/bjyoungblood/bjy-authorize/src/BjyAuthorize/Service/Authorize.php(277): Zend\Permissions\Acl\Acl->addRole('bjyauthorize-id...', Array)
#3 /home/brian/dev/ptapp/app/vendor/bjyoungblood/bjy-authorize/src/BjyAuthorize/Service/Authorize.php(90): BjyAuthorize\Service\Authorize->load()
#4 /home/brian/dev/ptapp/app/vendor/bjyoungblood/bjy-authorize/src/BjyAuthorize/Service/Authorize.php(239) in /home/brian/dev/ptapp/app/vendor/zendframework/zendframework/library/Zend/Permissions/Acl/Role/Registry.php on line 69
My database tables were created with the provided schema.sql in the bjyauthorize repository, which contains the following code:
CREATE TABLE IF NOT EXISTS `user_role` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`roleId` varchar(255) NOT NULL,
`is_default` tinyint(1) NOT NULL,
`parent_id` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `user_role_linker` (
`user_id` int(11) unsigned NOT NULL,
`role_id` int(11) NOT NULL,
PRIMARY KEY (`user_id`,`role_id`),
KEY `role_id` (`role_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
;
With entries:
user_role
id | roleId | is_default | parent_id
---------------------------------------------
1 admin 0 therapist
2 therapist 0 patient
3 patient 0 user
4 guest 1 NULL
5 user 0 NULL
user_role_linker
user_id role_id
-------------------
3 3
I had to modify my bjyauthorize.global.php file because the "role_id_field" and the "parent_role_field" value didn't match up with sql schema provided. It looks like this:
<?php
return array(
'bjyauthorize' => array(
'default_role' => 'guest',
'identity_provider' => 'BjyAuthorize\Provider\Identity\ZfcUserZendDb',
'role_providers' => array(
'BjyAuthorize\Provider\Role\ZendDb' => array(
'table' => 'user_role',
'role_id_field' => 'roleId',
'parent_role_field' => 'parent_id',
),
),
'guards' => array(
'BjyAuthorize\Guard\Route' => array(
array('route' => 'zfcuser', 'roles' => array('user')),
array('route' => 'zfcuser/logout', 'roles' => array('user')),
array('route' => 'zfcuser/login', 'roles' => array('guest')),
array('route' => 'zfcuser/register', 'roles' => array('guest')),
// Below is the default index action used by the ZendSkeletonApplication
array('route' => 'home', 'roles' => array('guest', 'user')),
),
),
),
);
And my application.config.php looks like this:
<?php
return array(
'modules' => array(
'Application',
'ZfcBase',
'ZfcUser',
'User',
'BjyAuthorize',
),
'module_listener_options' => array(
'module_paths' => array(
'./module',
'./vendor',
),
'config_glob_paths' => array(
'config/autoload/{,*.}{global,local}.php',
),
),
);
Where the module "User" Is my custom ZfcUser Entity.
Any ideas where the problem is? I'm pretty new to ZF2 and zfc so thanks for your help!
EDIT: I should note that when I'm not logged in, I correctly get a 403 when trying to access /user, it's when I'm logged in that I receive this message. I receive it when trying to access any route (except invalid routes, I get a 404)
Based on first Comment, following sql works,
the same problem exists on parent_id, you need to change it, too:
CREATE TABLE IF NOT EXISTS `user_role` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`role_id` VARCHAR(255) NOT NULL,
`is_default` TINYINT(1) NOT NULL DEFAULT 0,
`parent_id` VARCHAR(255) NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `unique_role` (`role_id` ASC),
INDEX `idx_parent_id` (`parent_id` ASC),
CONSTRAINT `fk_parent_id` FOREIGN KEY (`parent_id`) REFERENCES `user_role` (`role_id`) ON DELETE SET NULL
) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COLLATE = utf8_unicode_ci;
CREATE TABLE IF NOT EXISTS `user_role_linker` (
`user_id` INT UNSIGNED NOT NULL,
`role_id` VARCHAR(255) NOT NULL,
PRIMARY KEY (`user_id`, `role_id`),
INDEX `idx_role_id` (`role_id` ASC),
INDEX `idx_user_id` (`user_id` ASC),
CONSTRAINT `fk_role_id` FOREIGN KEY (`role_id`) REFERENCES `user_role` (`role_id`) ON DELETE CASCADE,
CONSTRAINT `fk_user_id` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`) ON DELETE CASCADE
) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COLLATE = utf8_unicode_ci;
The problem seems to be with the provided sql schema. In the user_role_linker table, change the role_id field to a VARCHAR. When making entries to this table, user_id should correspond to the user's numerical id, but the role_id should be the text id of the "roleId" field in the user_role table.
Related
I am using a project which has T4MVC generating classes from a database table. I have several issues but this seems to be a pattern with them. I have not posted the .tt file because it is pretty large.
for example
HasRequired(a => a.AccountPaymentSettingId).WithMany(b => b.CustomerFileTypeAccountPaymentSettingFlexibles).HasForeignKey(c => c.AccountPaymentSettingId);
has a => a.AccountPaymentSettingId and I want a => a.AccountPaymentSetting
Here is the top of the .tt file to show the version
<## include file="..\\EF.Reverse.POCO.Core.ttinclude" #>
<#
// v2.17.1
It is not using desired names in the generated code.
This is what is generated:
public CustomerFileTypeAccountPaymentSettingFlexibleConfiguration(string schema)
{
ToTable(schema + ".Customer_FileType_Account_Payment_Setting_Flexible");
HasKey(x => x.AccountPaymentSettingFlexibleId);
Property(x => x.AccountPaymentSettingFlexibleId).HasColumnName("Account_Payment_Setting_Flexible_ID").IsRequired().HasColumnType("int").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(x => x.AccountPaymentSettingId).HasColumnName("Account_Payment_Setting_ID").IsRequired().HasColumnType("int");
Property(x => x.PaymentMethod).HasColumnName("Payment_Method").IsRequired().IsUnicode(false).HasColumnType("varchar").HasMaxLength(5);
Property(x => x.Priority).HasColumnName("Priority").IsRequired().HasColumnType("int");
Property(x => x.RowCreatedDate).HasColumnName("RowCreatedDate").IsRequired().HasColumnType("datetime2");
HasRequired(a => a.AccountPaymentSettingId).WithMany(b => b.CustomerFileTypeAccountPaymentSettingFlexibles).HasForeignKey(c => c.AccountPaymentSettingId);
HasRequired(a => a.PaymentMethod).WithMany(b => b.CustomerFileTypeAccountPaymentSettingFlexibles).HasForeignKey(c => c.PaymentMethod);
InitializePartial();
}
and this is my desired results:
public CustomerFileTypeAccountPaymentSettingFlexibleConfiguration(string schema)
{
ToTable(schema + ".Customer_FileType_Account_Payment_Setting_Flexible");
HasKey(x => x.AccountPaymentSettingFlexibleId);
Property(x => x.AccountPaymentSettingFlexibleId).HasColumnName("Account_Payment_Setting_Flexible_ID").IsRequired().HasColumnType("int").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(x => x.AccountPaymentSettingId).HasColumnName("Account_Payment_Setting_ID").IsRequired().HasColumnType("int");
Property(x => x.PaymentMethodCode).HasColumnName("Payment_Method").IsRequired().IsUnicode(false).HasColumnType("varchar").HasMaxLength(5);
Property(x => x.Priority).HasColumnName("Priority").IsRequired().HasColumnType("int");
HasRequired(a => a.AccountPaymentSetting).WithMany(b => b.CustomerFileTypeAccountPaymentSettingFlexibles).HasForeignKey(c => c.AccountPaymentSettingId);
HasRequired(a => a.PaymentMethod).WithMany(b => b.CustomerFileTypeAccountPaymentSettingFlexibles).HasForeignKey(c => c.PaymentMethodCode);
InitializePartial();
}
Just for completeness, this is the relevant part of the table (I left off some default and FK constraints to keep it compact)
CREATE TABLE [dbo].[Customer_FileType_Account_Payment_Setting_Flexible](
[Account_Payment_Setting_Flexible_ID] [int] IDENTITY(1,1) NOT NULL,
[Account_Payment_Setting_ID] [int] NOT NULL,
[Payment_Method] [varchar](5) NOT NULL,
[Priority] [int] NOT NULL,
[RowCreatedDate] [datetime2](7) NOT NULL,
CONSTRAINT [PK_Customer_FileType_Account_Payment_Setting_Flexible] PRIMARY KEY CLUSTERED
(
[Account_Payment_Setting_Flexible_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PayspanHealth_Data3],
CONSTRAINT [UK_CustomerFileTypeAccountPaymentSettingFlexible_SettingId_PaymentMethod] UNIQUE NONCLUSTERED
(
[Account_Payment_Setting_ID] ASC,
[Payment_Method] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PayspanHealth_Data3],
CONSTRAINT [UK_CustomerFileTypeAccountPaymentSettingFlexible_SettingId_Priority] UNIQUE NONCLUSTERED
(
[Account_Payment_Setting_ID] ASC,
[Priority] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PayspanHealth_Data3]
) ON [PayspanHealth_Data3]
GO
ALTER TABLE [dbo].[Customer_FileType_Account_Payment_Setting_Flexible] ADD CONSTRAINT [DF_CustomerFileTypeAccountPaymentSettingFlexible_RowCreatedDate] DEFAULT (sysdatetime()) FOR [RowCreatedDate]
GO
ALTER TABLE [dbo].[Customer_FileType_Account_Payment_Setting_Flexible] WITH CHECK ADD CONSTRAINT [FK_CustomerFileTypeAccountPaymentSettingFlexible_AccountPaymentSettingId] FOREIGN KEY([Account_Payment_Setting_ID])
REFERENCES [dbo].[Customer_FileType_Account_Payment_Settings] ([Account_Payment_Setting_ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Customer_FileType_Account_Payment_Setting_Flexible] CHECK CONSTRAINT [FK_CustomerFileTypeAccountPaymentSettingFlexible_AccountPaymentSettingId]
GO
ALTER TABLE [dbo].[Customer_FileType_Account_Payment_Setting_Flexible] WITH CHECK ADD CONSTRAINT [FK_CustomerFileTypeAccountPaymentSettingFlexible_PaymentMethod] FOREIGN KEY([Payment_Method])
REFERENCES [dbo].[Payment_Method] ([Payment_Method_Code])
GO
ALTER TABLE [dbo].[Customer_FileType_Account_Payment_Setting_Flexible] CHECK CONSTRAINT [FK_CustomerFileTypeAccountPaymentSettingFlexible_PaymentMethod]
GO
Table definition:
CREATE TABLE [Index].[Dependency] (
[RevisionId] INT NOT NULL,
[MapCode] VARCHAR (10) NOT NULL,
[GroupId] SMALLINT NOT NULL,
[DependencyTypeId] TINYINT NOT NULL,
[InputThreshold] DECIMAL (9, 2) NOT NULL,
[InjectMapCode] VARCHAR (10) NULL,
[InjectAmount] DECIMAL (9, 2) NOT NULL,
CONSTRAINT [UQ_Dependency_RevisionId_MapCode_GroupId] UNIQUE NONCLUSTERED ([RevisionId] ASC, [MapCode] ASC, [GroupId] ASC),
CONSTRAINT [FK_Dependency_MapCode] FOREIGN KEY ([MapCode]) REFERENCES [Index].[Material] ([MapCode]),
CONSTRAINT [FK_Dependency_InjectMapCode] FOREIGN KEY ([InjectMapCode]) REFERENCES [Index].[Material] ([MapCode]),
CONSTRAINT [FK_Dependency_Revision] FOREIGN KEY ([RevisionId]) REFERENCES [Index].[DependencyRevision] ([DependencyRevisionId]),
CONSTRAINT [FK_Dependency_DependencyType] FOREIGN KEY ([DependencyTypeId]) REFERENCES [Index].[DependencyType] ([DependencyTypeId]),
CONSTRAINT [FK_Dependency_Group] FOREIGN KEY ([GroupId]) REFERENCES [Index].[Group] ([GroupId])
);
My attempt to map to it:
public class DependencyMap : EntityTypeConfiguration<Entities.Dependency>
{
public DependencyMap()
{
ToTable("Dependency", "Index");
HasKey(md => new { md.RevisionId, md.MapCode, md.GroupId });
Property(s => s.RevisionId).IsRequired().HasColumnName("RevisionId");
Property(s => s.MapCode).IsRequired().HasMaxLength(10).HasColumnName("MapCode");
Property(s => s.GroupId).IsRequired().HasColumnName("GroupId");
Property(s => s.DependencyTypeId).IsRequired().HasColumnName("DependencyId");
Property(s => s.InputThreshold).IsRequired().HasColumnName("InputThreshold").HasPrecision(9, 2);
Property(s => s.InjectMapCode).IsOptional().HasColumnName("InjectEngineMapCode").HasMaxLength(10);
Property(s => s.InjectAmount).HasColumnName("InjectAmount").IsRequired().HasPrecision(9, 2);
}
}
When I try to call a method that retrieves from the table an exception is thrown on
'HasKey(md => new { md.RevisionId, md.MapCode, md.GroupId })'
saying that 'properties expression is not valid. The expression should represent a property' when mapping the table. If anyone could show me how to properly map a table like this without explicitly defined primary key it would be much appreciated. Thanks.
-- Typo3 CMS version 6.2 --
I have some entities which have a country property.
In the backend, when inserting/editing one of such entities I would like to be able to pick the country from a select.
As different entity types all share the same countries I thought it would be appropriate to store the countries in a db table. Then the countries are not going to be modified via the backend, so I don't need an admin interface for them.
Can this be achieved? How?
Up until now this is what I've come up with in my TCA configuration for one of my entities...
'country' => array(
'exclude' => 1,
'label' => 'LLL:EXT:ape/Resources/Private/Language/locallang_db.xlf:tx_myext_domain_model_building.country',
'config' => array(
'type' => 'select',
'foreign_table' => 'tx_myext_countries',
'size' => 1,
'maxitems' => 1,
'eval' => 'required'
),
)
...and this is the countries table sql...
CREATE TABLE tx_myext_countries (
uid int(11) NOT NULL auto_increment,
pid int(11),
name varchar(30) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
code varchar(3) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
PRIMARY KEY (uid)
);
...but while not giving any error it displays an empty select in the backend.
What am I missing?
Should I create a model for the countries? Should I treat them as entities? Would it be appropriate to configure it as an external data source?
Any help greatly appreciated!
Update
This is my attempt at configuring the tx_myext_countries table in TCA:
$GLOBALS['TCA']['tx_myext_countries'] = array(
'ctrl' => array(
'title' => 'Country',
'label' => 'name',
'searchFields' => 'name,code,',
),
);
My problem is as follows.
After deleting multiple rows from table, inserting new record into same table results in error.
Database Error
Error: SQLSTATE[42P01]:
Undefined table: 7 ERROR: relation "order_details_id_seq" does not exist
Table
CREATE TABLE schema.order_details (
id serial NOT NULL,
order_id integer NOT NULL,
field_1 integer,
field_2 real,
field_3 character varying(15),
CONSTRAINT order_details_pkey PRIMARY KEY (id )
)
WITH (
OIDS=FALSE
);
Insert is
INSERT INTO "schema"."order_details" ("order_id", "field_1", "field_2", "field_3")
VALUES (37, 1, 2, 'value');
Sequence "schema"."order_details_id_seq" in used schema exists.
CREATE SEQUENCE schema.order_details_id_seq
INCREMENT 1
MINVALUE 1
MAXVALUE 9223372036854775807
START 37
CACHE 1;
Models.
// Model
class Order extends AppModel {
public $useDbConfig = 'other_data';
public $hasMany = array(
'OrderDetail' => array(
'className' => 'OrderDetail',
'foreignKey' => 'order_id',
'dependent' => true,
'order' => array(
'OrderDetail.order_id',
'OrderDetail.field_1'
))
);
class OrderDetail extends AppModel {
public $useDbConfig = 'other_data';
public $belongsTo = array(
'Order' => array(
'className' => 'Order',
'foreignKey' => 'order_id',
'dependent' => true
),
// model Order save code on recreation of order
$this->OrderDetail->deleteAll(array('OrderDetail.order_id' => $this->id));
At this point tried to insert $this->OrderDetail->query('VACUUM FULL ANALYZE order_details'); with no effect
foreach ($details as $d) {
$this->OrderDetail->create();
$this->OrderDetail->save($d /*array(
'order_id' => $this->id,
'field_1' => 1,
'field_2' => 2,
'field_3' => 'value'
)*/);
}
I get error on first foreach loop.
Weirdest thing is that problem appears and disappears after some time randomly.
Any suggestions on what it could be and how to get rid of it?
Currently solved problem using code.
$this->Order->id = $id;
$this->Order->delete();
It fires 2 queries for each row (100 extra in my case!) of delete statements instead of two in case of
$this->OrderDetail->deleteAll(array('OrderDetail.order_id' => $id));
So for this time it has space for improvement.
EDIT: Currently code works as it should with tweaked DboSource.
It seems that cake was looking in public schema for sequence where it is not located.
Fixed it by tweaking to include schema name in last insert getter inf file Model/Datasource/DboSource.php create method with this diff
## -1006,7 +1006,7 ##
if ($this->execute($this->renderStatement('create', $query))) {
if (empty($id)) {
- $id = $this->lastInsertId($this->fullTableName($model, false, false), $model->primaryKey);
+ $id = $this->lastInsertId($this->fullTableName($model, false, true), $model->primaryKey);
}
$model->setInsertID($id);
$model->id = $id;
I know that modifying core is not the way to go, but as long as it is working it is fine with me.
This happened to me because I modified the name of the table, but PostgreSQL did not change the name of the sequences. Knowing this, I changed the name of the sequences that affected this table and it was resolved.
To prevent this error, use this convention to name your sequence when using cakephp: table_name_id_seq. For example:
table name: user
sequence name should be: user_id_seq
If you alredy have sequences, you can rename it in posgres like this
alter sequence user_seq rename to user_id_seq
I'm not a fun of this way to name sequence but it prenvent this kind of errors in my case
I have two tables with structure as mentioned below:
CREATE TABLE `up_offer` (
`up_offer_id` int(11) NOT NULL AUTO_INCREMENT,
`from_subscription_id` int(11) NOT NULL,
`to_subscription_id` int(11) NOT NULL,
PRIMARY KEY (`up_offer_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `subscription` (
`subscription_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(1000) NOT NULL,
`code` varchar(45) NOT NULL,
`price` decimal(6,2) NOT NULL,
`billing_cycle` int(11) NOT NULL,
`desc` varchar(2000) DEFAULT NULL,
`start_date` date NOT NULL,
`end_date` date NOT NULL,
`emaillist_id` int(11) NOT NULL,
`old_created_date` datetime NOT NULL,
`old_last_updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`created_on` datetime NOT NULL,
`last_updated_on` datetime NOT NULL,
`is_active` bit(1) NOT NULL DEFAULT b'1',
PRIMARY KEY (`subscription_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
The dbTable Class am using for both the tables is as follows:
class Admin_Model_DbTable_Subscription extends Zend_Db_Table_Abstract
{
protected $_name = 'subscription';
protected $_primary = 'subscription_id';
protected $_dependentTables = 'Admin_Model_DbTable_UpOffer';
protected $_referenceMap = array(
'UpOffer' => array(
'columns' => array('subscription_id'),
'refTableClass' => 'Admin_Model_DbTable_UpOffer',
'refColumns' => array('from_subscription_id','to_subscription_id'),
),
);
}
class Admin_Model_DbTable_UpOffer extends Zend_Db_Table_Abstract{
protected $_name = 'up_offer';
protected $_dependentTables = 'Admin_Model_DbTable_Offer';
protected $_referenceMap = array(
'Offer'=>array(
'columns' => 'up_offer_id',
'refTableClass' => 'Admin_Model_DbTable_Offer',
'refColumns' => 'up_offer_id'
)
);
}
I want to get the dependent data from the 'Zend_Db_Table_Row Object':
the code am writing is:
$upOfferData->toArray() gives the fields:
Array
(
[up_offer_id] => 1
[from_subscription_id] => 10
[to_subscription_id] => 9
)
And $upOfferData->findDependentRowset('Admin_Model_DbTable_Subscription'); gives output as follows:
Array
(
[0] => Array
(
[subscription_id] => 10
[name] => 001
[code] => 010
[price] => 10.00
[billing_cycle] => 1
[desc] => Test
[start_date] => 2012-04-21
[end_date] => 2012-05-20
[emaillist_id] => 0
[old_created_date] => 0000-00-00 00:00:00
[old_last_updated] => 2012-04-20 15:29:57
[created_on] => 2012-04-20 09:59:56
[last_updated_on] => 2012-04-20 01:31:44
[is_active] => 1
)
)
What about the to_subscription_id?
How do i correctly map the DbTable Classes and what is the correct way of obtaining the desired out?
The desired should be something like:
Array
(
[0] => Array
(
[subscription_id] => 10
[name] => 001
[code] => 010
[price] => 10.00
[billing_cycle] => 1
[desc] => Test
[start_date] => 2012-04-21
[end_date] => 2012-05-20
[emaillist_id] => 0
[old_created_date] => 0000-00-00 00:00:00
[old_last_updated] => 2012-04-20 15:29:57
[created_on] => 2012-04-20 09:59:56
[last_updated_on] => 2012-04-20 01:31:44
[is_active] => 1
)
[1] => Array
(
[subscription_id] => 9
[name] => 002
[code] => 011
[price] => 50.00
[billing_cycle] => 2
[desc] => Test
[start_date] => 2012-04-21
[end_date] => 2012-05-20
[emaillist_id] => 0
[old_created_date] => 0000-00-00 00:00:00
[old_last_updated] => 2012-04-20 15:29:57
[created_on] => 2012-04-20 09:59:56
[last_updated_on] => 2012-04-20 01:31:44
[is_active] => 1
)
)