Symfony Role Hierarchy - security

currently I'm building an application based on a legacy database.
Within this Database there are UserClasses e.g.:
UserclassEntity:
id
classname
parent
UserclassEntity
so I have rewritten the core service and added my custom voter to security.voter:
security.role_hierarchy:
class: AppBundle\Security\Role\RoleHierarchy
arguments:
- '%security.role_hierarchy.roles%'
- '#app.user_class_repository'
security.access.admin_voter:
class: AppBundle\Security\Voter\AdminVoter
arguments: ['#security.role_hierarchy']
tags:
- { name: security.voter, priority: 400 }
public: false
So I implemented all needed MEthods based on Original RoleHierarchy Class:
class RoleHierarchy extends orig_RoleHierarchy
{
/**
* #var array
*/
private $hierarchy;
/**
* #var UserclassRepository
*/
private $userClassRepository;
/**
* #var RoleManager
*/
private $manager;
/**
* #var UserclassRepository
*/
private $userclassRepository;
/**
* #param UserclassRepository $userclassRepository
* #param array $hierarchy
*/
public function __construct(UserclassRepository $userclassRepository, array $hierarchy)
{
$this->hierarchy = $hierarchy;
$this->userclassRepository = $userclassRepository;
$map = $this->buildRolesTree($this->hierarchy);
parent::__construct($map);
}
/**
* Here we build an array with roles. It looks like a two-levelled tree - just
* like original Symfony roles are stored in security.yml
*
* #param array $hierarchy
*
* #return array
*/
private function buildRolesTree(array $hierarchy = [])
{
$userclasses = $this->userclassRepository->findAll();
foreach ($userclasses as $userclass) {
/** #var $userclass Userclass */
if ($userclass->getParent()) {
if (!isset($hierarchy['ROLE_' . $userclass->getName()])) {
$hierarchy['ROLE_' . $userclass->getName()] = array();
}
$hierarchy['ROLE_' . $userclass->getName()][] = 'ROLE_' . $userclass->getParent()->getName();
} else {
if (!isset($hierarchy['ROLE_' . $userclass->getName()])) {
$hierarchy['ROLE_' . $userclass->getName()] = array();
}
}
}
return $hierarchy;
}
}
But when i clear the cache for prod environment i get an error:
[Symfony\Component\Debug\Exception\FatalErrorException]
Compile Error: require(): Failed opening required 'E:\projects\sf2\app\var\cache\pro_/doctrine/orm/Proxies\__CG__AppBundleEntityUserclass.php' (include_path='.;C:\php\pear')
This Exception throws because of missing Proxy Class, but I really don't know how to do this in another way. I need this Entity and I need the Role_Hierarchy based on this Entity.
Any Suggestions in how to fix this?
As suggested some more files:
doctrine's part of config.yml
doctrine:
dbal:
driver: pdo_mysql
host: "%database_host%"
port: "%database_port%"
dbname: "%database_name%"
user: "%database_user%"
password: "%database_password%"
charset: LATIN1
mapping_types:
enum: string
orm:
auto_generate_proxy_classes: "%kernel.debug%"
entity_managers:
default:
naming_strategy: doctrine.orm.naming_strategy.underscore
auto_mapping: true
dql:
string_functions:
COLLATE: AppBundle\DQL\CollateFunction
Doctrine ORM:
<?xml version="1.0" encoding="utf-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
<entity name="AppBundle\Entity\Userclass" table="userclass" repository-class="AppBundle\Repository\UserclassRepository">
<indexes>
<index name="name" columns="name,classname,class,color"/>
</indexes>
<id name="id" type="integer" column="id">
<generator strategy="AUTO"/>
</id>
<field name="name" type="string" column="name" length="50" nullable="false">
<options>
<option name="fixed"/>
</options>
</field>
<field name="classname" type="string" column="classname" length="50" nullable="false">
<options>
<option name="fixed"/>
</options>
</field>
<field name="class" type="integer" column="class" nullable="false">
<options>
<option name="unsigned"/>
</options>
</field>
<field name="color" type="string" column="color" length="10" nullable="false">
<options>
<option name="fixed"/>
</options>
</field>
<many-to-one field="parent" target-entity="AppBundle\Entity\Userclass">
<join-column name="parent_id" referenced-column-name="id" />
</many-to-one>
</entity>
</doctrine-mapping>

I tried a lot of things but nothing really worked. As I found out, the proxy generate Task from doctrine:orm was removed in latest VErsion compatible with Symfony 3.1.x.
If someone struggle into this, the best way (I could find) was to set the
auto_generate_proxy_classes from "%kernel.debug%" to true
orm:
auto_generate_proxy_classes: "%kernel.debug%"
As simple as hell, only in dev environment this parameter is true. Running the application in productive mode, turns this obviosly to false, so Proxyclasses are not generated as they are needed. The Role Hierarchy is somehow triggered before doctrine got a chance to generate those needed proxies.
By enabling this auto_generate-option those proxies are generated as they were needed, and also cached. So any minimal performance break will only happen once. After generation these classes als also cached.
On my application I was not able to find any relevant or even little performance issues.

Related

Add additional fields in registration using Jhipster 4.10.2

I need to add phone number to the registration page and need to save it in the db as well. I followed following link.
http://www.jhipster.tech/tips/022_tip_registering_user_with_additional_information.html
But since here Jhispter version is changed code is bit different than the code in above link. So I am bit confusing to go with it. According to the link instructions I did upto "Updating ManagedUserVM". Then after I need the help since code is differed.
It really didn't change that much, and the logic remains the same.
The registerAccount function should look like this now :
public void registerAccount(#Valid #RequestBody ManagedUserVM managedUserVM) {
if (!checkPasswordLength(managedUserVM.getPassword())) {
throw new InvalidPasswordException();
}
userRepository.findOneByLogin(managedUserVM.getLogin().toLowerCase()).ifPresent(u -> {throw new LoginAlreadyUsedException();});
userRepository.findOneByEmailIgnoreCase(managedUserVM.getEmail()).ifPresent(u -> {throw new EmailAlreadyUsedException();});
User user = userService.registerUser(managedUserVM, managedUserVM.getPassword(), managedUserVM.getPhone());
mailService.sendActivationEmail(user);
}
And the registerUser function in the UserService (which is a rename of the former createUser) :
public User registerUser(UserDTO userDTO, String password, String phone) {
// JHipster code omitted for brevity
...
// Create and save the UserExtra entity
UserExtra newUserExtra = new UserExtra();
newUserExtra.setUser(newUser);
newUserExtra.setPhone(phone);
userExtraRepository.save(newUserExtra);
log.debug("Created Information for UserExtra: {}", newUserExtra);
return newUser;
}
Just note that you may have to manually change your database changelog (if using a SQL database) to correctly link the ids of User and UserExtra, so it looks like this :
<createTable tableName="user_extra">
<column name="phone" type="varchar(255)">
<constraints nullable="true" />
</column>
<column name="user_id" type="bigint">
<constraints primaryKey="true" nullable="false" />
</column>
<!-- jhipster-needle-liquibase-add-column - JHipster will add columns here, do not remove-->
</createTable>

Node-soap consuming delphi soap webservice

I'm using nodejs and node-soap as client to consume a webservice published on iis and developed in delphi. The webservice is published with document/literal style.
On Node I'm invoking and logging the response of the operations like this:
client[functionName](args, function (err, result) {
if (err) {
console.log(err);
} else {
console.log(result);
}
});
Here is a portion of the xml result from delphi:
...
<GetValuesResponse xmlns="urn:WS_TEST">
<res xmlns="urn:UTest">
<matrixData>
<TDoubleDynArray>
<double>4.32427893698308</double>
<double>4.40404718921869</double>
<double>4.50060875771443</double>
<double>4.56778202275494</double>
<double>4.61816197153533</double>
<double>4.73991351442126</double>
<double>4.78609513413661</double>
<double>4.8238800957219</double>
<double>4.8238800957219</double>
<double>4.81128510852681</double>
...
And this is the json obtained from node-soap (response):
...
"matrixData": {
"TDoubleDynArray": [
{
"double": [
"4.32427893698308",
"4.40404718921869",
"4.50060875771443",
"4.56778202275494",
"4.61816197153533",
"4.73991351442126",
"4.78609513413661",
"4.8238800957219",
"4.8238800957219",
"4.81128510852681",
...
I dont understand why node-soap includes the types of the data in the structure of the resulting json. Also, I don`t understand why arrays are parsed to json like an object with an array inside, instead of just an array.
Is there any way to ask node-soap just to include the data and the arrays just like simple arrays?
Here is the wsdl portion with the defines involved:
<element name="matrixData" type="ns6:TMatOfDouble"/>
<complexType name="TMatOfDouble">
<complexContent>
<restriction base="soapenc:Array">
<sequence/>
<attribute ref="soapenc:arrayType" n1:arrayType="ns1:TDoubleDynArray[]"/>
</restriction>
</complexContent>
</complexType>
<complexType name="TDoubleDynArray">
<complexContent>
<restriction base="soapenc:Array">
<sequence/>
<attribute ref="soapenc:arrayType" n1:arrayType="xs:double[]"/>
</restriction>
</complexContent>
</complexType>
Thanks in advance for any help
It result to be a bug in the node-soap library so we are trying to fix it.

The given key is not present in the dictionary

Hi I am trying to fetch the accounts from CRM 2011. I am fetching the data in the EntityCollection . But when I am trying to read or access data from entityCollection it displayed first record but throwing an error after that record. Kindly have a look to below code and suggest me.
string fetch2 = #"
<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
<entity name='account'>
<attribute name='name' />
<attribute name='address1_city' />
<attribute name='primarycontactid' />
<attribute name='telephone1' />
<attribute name='accountid' />
<order attribute='name' descending='false' />
<filter type='and'>
<condition attribute='accounttype' operator='eq' value='01' />
</filter>
</entity>
</fetch>";
try
{
EntityCollection fxResult = _service.RetrieveMultiple(new FetchExpression(fetch2));
foreach (var e in fxResult.Entities)
{
Console.WriteLine("Id:{0},Name:{1},City:{2}", e.Attributes ["accountid"].ToString(), e.Attributes["name"].ToString(), e.Attributes["address1_city"].ToString());
// Console.WriteLine("Id:{0},Name:{1},City:{2}", e.ToEntity["accountid"]);
}
}
catch (Exception e)
{
Console.WriteLine("Error:==" + e.Message);
}
Before access an attribute you need to ask if it is in the context:
e.Attributes.Contains("address1_city")
If the collection contains the attribute, then you can access it safe.
string accountid = (string)e.Attributes["address1_city"]
The reason the attribute doesn't come in the collection it's because it is null or you are not retrieving it. In this case maybe, one of your attributes is null. Maybe address1_city.
When retrieving attribute values of late-bound Entity objects, the recommended approach is to use method getAttributeValue<T>. When the attribute is not present in the entity's attribute collection, it returns default(T).
The primary key ('id') of the record is always present when it is returned by the OrganizationService.
So your code should look like this:
EntityCollection fxResult = _service.RetrieveMultiple(new FetchExpression(fetch2));
foreach (var e in fxResult.Entities)
{
Console.WriteLine(
"Id:{0},Name:{1},City:{2}",
e.Id,
e.GetAttributeValue<string>("name"),
e.GetAttributeValue<string>("address1_city"));
}
You can safely use the item selector when you need to assign a value to an attribute, regardless if it is already present or not.
E.g. the following code line is valid:
e["name"] = "Demo Accountname";

Anyone configured apache solr FieldReaderDataSource?

I have a datbase column containing xml and I want to index using apache solr content in that column i have following data-config.xml (configuration). The database name is "solrdb" and columns name is "xmlfield", There seems to be some problem in it, the error is specified at the bottom.
<dataConfig>
<!--Data source to connect to database-->
<dataSource
name="XmlDocDS"
type="JdbcDataSource"
driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://127.0.0.1/solrdb"
user="root"
password="root" />
<!-- Data Source for getting xml columne data-->
<dataSource
name="solrFieldReaderDS"
type="FieldReaderDataSource"/>
<document>
<entity
name="xmltable"
rootEntity="false"
datasource="XmlDocDS"
query="select xmlfield from xmltable">
<field column="xmldata" blob="true" />
<entity
name="page"
dataSource="solrFieldReaderDS"
dataField="xmltable.xmldata"
processor="XPathEntityProcessor"
forEach="/page">
<field column="id" xpath="/mediawiki/page/id"/>
<field column="Title" xpath="/mediawiki/page/title"/>
</entity>
</entity>
</document>
</dataConfig>
The error is following:
SEVERE: Exception while processing: xmltable document : null:org.apache.solr.handler.dataimport.DataImportHandlerException: Unable to execute query: select xmlfield from xmltable Processing Document # 1
The error is thrown in this part of JDBC importer code:
try {
Connection c = getConnection();
stmt = c.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
stmt.setFetchSize(batchSize);
stmt.setMaxRows(maxRows);
LOG.debug("Executing SQL: " + query);
long start = System.currentTimeMillis();
if (stmt.execute(query)) {
resultSet = stmt.getResultSet();
}
LOG.trace("Time taken for sql :"
+ (System.currentTimeMillis() - start));
colNames = readFieldNames(resultSet.getMetaData());
} catch (Exception e) {
wrapAndThrow(SEVERE, e, "Unable to execute query: " + query);
}
So there can be error in connection or query (smth wrong with DB?). Also grep logs for "Executing SQL" and "Time taken for sql :"
there was an error in connection, for some reason it was nto able to connect to my local machine, i changed the database host and it connected!, the problem is that I have the configuration in place and FieldReaderDataSource seems to work fine, but now when it completes everything it says documents indexed/updated = 0
here is my xml configuration
<dataSource
name="jdbcDataSource"
driver="com.mysql.jdbc.Driver"
url="xxxx"
user="yyyy"
password="zzzz" readOnly="true"/>
<dataSource
name="solrFieldReaderDS"
type="FieldReaderDataSource"/>
<document>
<entity
name="tabledata"
dataSource="jdbcDataSource"
query="select codeID,codeText from ArticlePoolState where codeID=3">
<entity
name="xmldata"
dataSource="solrFieldReaderDS"
forEach="/med"
dataField="tabledata.codeText"
processor="XPathEntityProcessor">
<field column="title" xpath="/title"/>
</entity>
</entity>
</document>
The query is fine.

Problem displaying custom property values for SharePoint custom field types

I'm trying to create a custom field type in SharePoint (WSS 3.0) that has custom properties. I have created my fldtypes*.xml file based on the SDK docs and this blog post and it seems to render fine and I can retrieve the custom property values inside my code. My problem is that after the initial field creation, if I go back to the list settings page and click on my newly added field, the form shows my custom properties with some value that I'm not providing it. For example, if my custom property's display name is "My Custom Prop" then the value in its textbox will be "My Custom Prop field value".
My question is this: how can I properly show the actual string values of my custom property types in these textboxes?
Here's my fldtypes*.xml file:
<?xml version="1.0" encoding="utf-8"?>
<FieldTypes>
<FieldType>
<Field Name="TypeName">MyCustomField</Field>
<Field Name="TypeDisplayName">My Custom Field</Field>
<Field Name="TypeShortDescription">MyCustomField</Field>
<Field Name="ParentType">Text</Field>
<Field Name="UserCreatable">TRUE</Field>
<Field Name="FieldTypeClass">MyCustomField.CustomFields.MyCustomField, MyCustomField, Version=1.0.0.0, Culture=neutral, PublicKeyToken=d772gbab82fe6996</Field>
<PropertySchema>
<Fields>
<Field Name="MyCustomProp" DisplayName="My Custom Prop" Type="Text" MaxLength="50" DisplaySize="30" />
</Fields>
</PropertySchema>
</FieldType>
</FieldTypes>
And here's the code for my field type class:
public class MyCustomField : SPFieldText
{
private string propval;
public MyCustomField(SPFieldCollection fields, string fieldName)
: base(fields, fieldName)
{
}
public MyCustomField(SPFieldCollection fields, string typeName, string displayName)
: base(fields, typeName, displayName)
{
}
public override void Update()
{
// I can see any updated value here
propval = GetCustomProperty("MyCustomProp") as string;
base.Update();
}
public override Type FieldValueType
{
get { return typeof (string); }
}
}
What can I do to see the correct custom property values in my "Change Column" page (FldEditEx.aspx) in my SharePoint app?
There is a well known issue with saving and retrieving custom properties on a custom field type. Here is a direct link to the work around.
btw, some of the comments on the post purport the same problem.

Resources