I try to create an Admin User with FOsUserBundle from command windows with the following command:
php app/console fos:user:create
In my project the Admin User extends other user with mandatory propriety. So, when I choose my username, mail and password, it tells me:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'latitude' cannot be null
How can I set the value "latitude" in my AdminUser? I also use PUGXMultiUserBundle.
Only possibile way to reach that to me is
1 - override the cli command of FOSUserBundle placed into Command/CreateUserCommand.php
2 - override the user create method of FOSUserBundle placed into Util/UserManipulator.php
// Command/CreateUserCommand.php
protected function execute(InputInterface $input, OutputInterface $output)
{
$username = $input->getArgument('username');
$email = $input->getArgument('email');
$password = $input->getArgument('password');
$inactive = $input->getOption('inactive');
$superadmin = $input->getOption('super-admin');
$latitude = $input->getOption('latitude'); //this will be your own logic add
$manipulator = $this->getContainer()->get('fos_user.util.user_manipulator');
$manipulator->create($username, $password, $email, $latitude, !$inactive, $superadmin);
$output->writeln(sprintf('Created user <comment>%s</comment>', $username));
}
and
// Util/UserManipulator.php
public function create($username, $password, $email, $latitude, $active, $superadmin)
{
$user = $this->userManager->createUser();
$user->setUsername($username);
$user->setEmail($email);
$user->setPlainPassword($password);
$user->setEnabled((Boolean) $active);
$user->setSuperAdmin((Boolean) $superadmin);
$user->setLatitude($latitude);
$this->userManager->updateUser($user);
return $user;
}
Of course when I say override i mean ... override :P So you haven't to modify FOSUserBundle original files (you know, it's dangerous for many reasons) but make your own files by making your bundle extended by FOSUserBundle
Are you wondering how to make your bundle extended by FOSUserBundle?
Into your bundle "mainfile" - is the one you use to register your bundle - just add this lines
public function getParent()
{
return 'FOSUserBundle';
}
Then you simply recreate the tree structure where your ovverride files lives into original bundle, into your custom bundle's Resources/ directory (same position, same file name, same annotations if any) and .... the magic can start :) (this is valid only for views, please pay attention!)
What "override" means?
Override means that you take an existent function, "shadow" it by redefining elsewhere (declare a function with the same name, no matter how many parameters it accept, no matter the type of paramenters since php doesn't support method overloading [except if you do some "hack"]) and then you can use it instead of the original one. This is a common technique for add extra functionalities to a function or to change the function itself.
Say that we have two classes, A and B with B that is a child class of A. Say also that A have a method called myMethod().
In B we can do something like
public function myMethod() {
parent::myMethod();
//add extra functionalities here
}
in that way we're adding extra functionalities as we're calling the parent ("original") method and then execute some extra functionalities
Whereas if in B we make something like
public function myMethod() {
//some code here, but not calling parent method
}
we're redefining the behaviour of myMethod()
How Symfony2 let me override methods?
As I said previously in my answer, you have to make your bundle a child of the bundle that containts the function(s) you're trying to override (in that case FOSUserBundle). Once you did it, use the Resources directory of your bundle to accomplish what you need. reproduce the "tree-folder-structure" of the original bundle (ie.: same names of the folders) until you reach the class that contains the function you need to override.
Follow your real example: you need to override execute() function contained in Command/CreateUserCommand.php. You have to create, into your bundle folder that path:
PathTo/YourCostumBundle/Command/
and place inside the file CreateUserCommand.php with the content I show you above.
If you don't understand where I find that path, please take a look to FOSUserBundle code and it will be absolutely clear!
Why is dangerous to modify the FOSUserBundle code directly?
Well, there's a lot of answer an critic point that I can show you. Choosing the main (not ordered for importance):
What if you need to update FOSUserBundle? You'll use composer and lost every modify that you made to FOSUserBundle code
What if you have more than one bundle into your project that need to use FOSUserBundle? Maybe the custom behaviour makes sense for a bundle but not for the other one. Costumizing the behaviour at local bundle level helps you to keep FOSUserBundle logic intact
What if you're developing a bundle that you want to share with other user? You need to force them to "take" your own costumized FOSUserBundle version and warn them about updating it
Finally: I perfeclty know that your entity isn't into FOSUserBundle, but I can bet that they extend FOSUserBundle base user so what I told above is applicable to your case.
Hope it's less fuzzy now :)
Documentation: http://symfony.com/doc/current/cookbook/bundles/inheritance.html#overriding-controllers
I always follow the pattern I learned in the symfony documentation itself:
php bin/console fos:user:create usertest mail#domain.com password
and sometimes I need change the "roles" on the table "fos_user"
then
a:0:{}
to
a:1:{i:0;s:10:"ROLE_ADMIN";}
After creating a user with:
bash-5.1# bin/console fos:user:create admin admin#mydomain.com password123
Promote the user with the ROLE_ADMIN role:
bash-5.1# bin/console fos:user:promote
Please choose a username:admin
Please choose a role:ROLE_ADMIN
Role "ROLE_ADMIN" has been added to user "admin". This change will not
apply until the user logs out and back in again.
Related
Following this
http://symfony.com/doc/current/security/custom_authentication_provider.html
Results in
Service "security.authentication.provider.wsse.wsse_secured": Cannot replace arguments if none have been configured yet.
I cannot find anything about this error anywhere. This uses the doc's WSSE code and it fails.
This repo shows it failing https://github.com/jakenoble/wsse_test
I want to get it working eventually with the FOS User Bundle. But I cannot get it to work with a basic Symfony3 install so FOS User Bundle is out of the question at the moment.
Having dug around a bit...
There is a an arg at element index_0 on class Symfony\Component\DependencyInjection\ChildDefinition the object for the arg at element index_0 has an id of fos_user.user_provider.username_email.
The replace call then attempts to get the arguments of fos_user.user_provider.username_email, but there are none. Then the error occurs.
Any ideas?
TL;DR Move your service definitions below the autoloading definitions in services.yml and change the WsseFactory code to
$container
->setDefinition($providerId, new ChildDefinition(WsseProvider::class))
->setArgument('$userProvider', new Reference($userProvider))
;
Full explanation.
The first mistake in the supplied code is that the services definitions prepend the autoloading lines. The autoloading will just override the previous definitions and will cause the AuthenticationManagerInterface failure. Moving the definitions below will fix the issue. The other way to fix the issue is aliases as #yceruto and #gintko pointed.
But only that move will not make the code work despite on your answer. You probably didnt notice how changed something else to make it work.
The second issue, the failure of replaceArgument, is related to Symfony's order of the container compilation as was correctly supposed. The order is defined in the PassConfig class:
$this->optimizationPasses = array(array(
new ExtensionCompilerPass(),
new ResolveDefinitionTemplatesPass(),
...
$autowirePass = new AutowirePass(false),
...
));
I omitted the irrelevant passes. The security.authentication.provider.wsse.wsse_secured definition created by the WsseFactory is produced first. Then ResolveDefinitionTemplatesPass will take place, and will try to replace the arguments of the definition and raise the Cannot replace arguments exception you got:
foreach ($definition->getArguments() as $k => $v) {
if (is_numeric($k)) {
$def->addArgument($v);
} elseif (0 === strpos($k, 'index_')) {
$def->replaceArgument((int) substr($k, strlen('index_')), $v);
} else {
$def->setArgument($k, $v);
}
}
The issue will appear cause the pass will call Definition::replaceArgument for index_0. As the parent definition doesn't have an argument at position 0 neither in the former services.xml nor in the fixed one. AutowirePass wasn't executed yet, the autogenerated definitions has no arguments, the manual definition has the named $cachePool argument only.
So to fix the issue you could use rather:
->setArgument(0, new Reference($userProvider)); //proposed by #yceruto
->replaceArgument('$userProvider', new Reference($userProvider)); //proposed by #gintko
->setArgument('$userProvider', new Reference($userProvider)); // by me
All of them will entail the calls of Definition::addArgument or Definition::setArgument and will work out. There are only the little difference:
- setArgument(0, ... could not work for some other scenarios;
- I like ->setArgument('$userProvider' more than ->replaceArgument('$userProvider' due to semantics. Nothing to replace yet!
Hope the details why the issue appears now clear.
PS. There are also few other funny ways to overcome the issue.
Fix the config a bit:
AppBundle\Security\Authentication\Provider\WsseProvider:
arguments:
0: ''
$cachePool: '#cache.app'
public: false
Or set an alias of Symfony\Component\Security\Core\User\UserProviderInterface to let the autowire do the rest for you.
$container
->setDefinition($providerId, new ChildDefinition(WsseProvider::class))
// ->replaceArgument(0, new Reference($userProvider))
;
$container
->setAlias('Symfony\Component\Security\Core\User\UserProviderInterface',$userProvider)
;
This look like at this moment the provider definition doesn't have the autowired arguments ready, maybe related to the order in which the "CompilerPass" are processed, by now you can solve it with these little tweaks:
change this line in WsseFactory.php:
->replaceArgument(0, new Reference($userProvider))
by:
->setArgument(0, new Reference($userProvider))
and add this alias to services.yml to complete the autowired arguments of the new provider:
Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface: '#security.authentication.manager'
EDIT: (deleted the previous contents due to the comment)
I see you don't use FOSUserBundle that makes things more comples. I did not yet create PR.
I think you are missing custom user entity. (see the link I have provided to create your own entity - my PR would be similar to these lines, if you are unable to create your own entity using my description and the link I'll provide PR, but that will take longer).
The steps you have to take:
Create your own User entity via src/AppBundle/Entity/User.php
Create DB table via php bin/console doctrine:schema:update --force
Configure Security to load your Entity - use AppBundle\Entity\User;
Then you have to create your own user. This can be tricky see password encoding for more.
(optional) Forbid interactive users If you want to login using
username OR email you can create Custom Query to Load the User
These steps should be enough for you to create your own user Entity and you don't have to use the FOSUserBundle.
EDIT:
Ok, so read some source code, and in ChildDefinition:100 you can see, that arguments are also indexed by argument's $name. So, it must be, that at compile time arguments of autowired services are passed with their named indexes, instead of numbered indexes.
WsseFactory.php
->replaceArgument(0, new Reference($userProvider));
so argument should be referenced by it's name:
->replaceArgument('$userProvider', new Reference($userProvider));
After this change, you will get new exception error, which says that it's not possible to autowire $authenticationManager in WsseListener service by it's interface. You can fix it simply by specifying alias for that interface in your services.yml:
Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface: '#security.authentication.manager'
I guess this issue is related with new autowire feature, I will try to investigate it later why it is so.
For now, you can use old way to define services:
services.yml:
app.security.wsse_provider:
class: AppBundle\Security\Authentication\Provider\WsseProvider
arguments:
- ''
- '#cache.app'
public: false
app.security.wsse_listener:
class: AppBundle\Security\Firewall\WsseListener
arguments: ['#security.token_storage', '#security.authentication.manager']
public: false
in WsseFactory.php, following lines:
new ChildDefinition(WsseFactory::class);
new ChildDefinition(WsseListener::class);
translates into:
new ChildDefinition('app.security.wsse_provider');
new ChildDefinition('app.security.wsse_listener');
It seems the issue is because my config in services.yml came before the new auto wiring stuff.
So simply moving it below the auto wiring fixes it.
I'm in searching of the best way of removing business logic from controller and correct usage of model(and maybe services).
Some details below.
Actually, my project is more complicated, but as example I will use Simple Blog application.
I have created my application (Simple Blog) in next steps:
created bundle
generated entities(Topic, Post, Comment)
generated controller for each entity, using doctrine:generate:crud
installed FOSUserBundle and generated User entity
So, I have all needed methods and forms in my controllers. But now I have some troubles:
Admin need to be able see all topics and posts, when simple User can only see
topic and posts where he is owner.
Currently there are indexAction, that return findAll common for any user. As solution, I can check in action, if ROLE_USER or ADMIN and return find result for each condition. But this variant keep some logic at action.
I also can generate action for each role, but what happened if roles amount will increase?
What is the best way to solve this problem with result for each role?
I need to edit some parameters before saving.
For example, I have some scheduler, where I create date in some steps, using features of DateTime.
Before saving I need to do some calculations with date.
I can do it in controller using service or simple $request->params edit.
What is the best way to edit some $request parameters before saving?
My questions I have marked with bold.
Thanks a lot for any help!
What I would do is to create a query which fetches the topics. Afterwards I would have a method argument which specifies if the query should select only the topics for a certain user or all topics. Something like this should do the work in your TopicRepository:
public function findTopics($userId = false)
{
$query = $this->createQueryBuilder('topic');
if($userId) {
$query->join('topic.user', 'user')
->where('user.id = :user_id')
->setParameter(':user_id', $userId)
;
}
return $query->getQuery()->getResult();
}
So, whenever you need to get the topics only by a user, you would pass a $userId to the method and it would return the results only for that user. In your controller you'd have something similar to this code (Symfony 2.6+):
$authorizationChecker = $this->get('security.authorization_checker');
if($authorizationChecker->isGranted('ROLE_ADMIN')){
$results = $this->get('doctrine.orm.entity_manager')->getRepository('TopicRepository')->findTopics();
} else {
$results = $this->get('doctrine.orm.entity_manager')->getRepository('TopicRepository')->findTopics($this->getUser()->getId());
}
You can try using Doctrine Events and create a PreUpdate depending on your case. See the documentation for more information. If you have a TopicFormType, you could also try the form events.
You are not supposed to "edit" a $request, which is why you can't directly do that. You can, however, retrieve a value, save it as a $variable and then do whatever you want with it. You can always create a new Request if you really need it. Could you be more specific what you want to do here and why is this necessary?
I am trying to implemt the following instruction, as to have Enum type somehow
Shame on me, but I have not an idea on how/where I go to "register [the defined] type with Type::addType('<enummyfield>', 'MyProject\DBAL\<EnumMyfield>Type')".
EDIT Answer 1 helps. It seems I need too:
to move definition of EnumMyfield to directory MyBundle\Doctrine\DBAL\Types\Type (with appropriate use declarations)
to update app\config\config.yml with lines
types:
<myfield>: <mybundle>\Doctrine\DBAL\Types\Type\<EnumMyfield>Type
since I wish to have a Select on the Form side, to define:
->add('MyField','choice', array('label'=>'Select please', 'choices'=>array('A'=>'A','B'=>'B')), within my MyentityType\buildForm().
With respect to the last point, if I just use choices'=>array('A','B'), values for the select options are rendered as numbers (0,1), and I run into an error (I am not sure why)
your comments/advises are welcome
Just a recap, useful for others (maybe); I will highlight were you're blocked
Create a directory Doctrine\DBAL\Types
Define your new DBAL type there like shown into your link
Register it into your bundle main file (*) <--- this is what you're missing
Use it into entity definition
(*) You have a file inside your bundle named YourBundleNameBundle.php this file is used to register the bundle. If you want to register your custom type also, put inside this bundle the string Type::addType('enum', 'MyProject\DBAL\EnumType')".
So, something like
public function boot()
{
if (false === Type:hasType('enum')) {
$em = $this->container->get('doctrine.orm.entity_manager');
Type::addType('enum', 'Path\To\Bundle\Doctrine\DBAL\Types\EnumType');
$em->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('enum','enum');
}
}
Don't forget the use statement
use Doctrine\DBAL\Types\Type;
at the top of the file
I am new with Symfony2 and so I am with FOSUserbundle, the registration form I wrote got different fields mandatory based on if it is a company or private person, I set it up etc and if I hardcode the valdiation group in the fos config it will work, but what I need is to set it up dynamic based on the form submit data, I tried to follow:
http://symfony.com/doc/current/book/forms.html#book-forms-validation-groups
Seeing that FOSUserbundle use the deprecated OptionsResolverInterface , I even tried it with that one, but whatever I do it is never called.
So my question is kinda, what is the right approach with that bundle to change the valdiation group on the fly based on the submitted data?
Figured it out myself how to do and because I could nowhere on the internet find the solution, answering here my own question for the case someone else need that too:
in the config.yml i set the validationgroup like this
validation_groups: [AppBundle\Form\Type\RegistrationFormType, determineValidationGroups]
and inside that class then:
public static function determineValidationGroups(FormInterface $form){
...
}
And that one returns an array with the validations groups, just dont forget to include for registration for example Registration or it wont validate if the user already exists etc
Using this code in PropertyAdmin extends Admin :
public function createQuery($context = 'list')
{
$user = $this->getConfigurationPool()->getContainer()->get('security.context')->getToken()->getUser();
$query = $this->getModelManager()->createQuery($this->getClass(), 'o');
$query->where('o.Creator=:creator')->setParameter("creator", $user);
return $query;
}
I was able to limit "list" results to those who "belong" to logged admin ie. only Properties (that is an entity) created by logged admin.
The problem:
By manually changing the URL (id value like 1, 2...), I can edit Property that belongs to other user. For edit action, above query is not called at all. How to change that behavior?
2.Instead of putting query in controllers, can I fetch it from PropertyRepository class? That would keep logic in models for which I could write unit tests.
3.I am trying:
ProductAdmin extends AdminHelper {....}
AdminHelper extends Admin { .... }
But it fails saying "Cannot import resource "D:_development\rent2\app/config." from "D:_development\rent2\app/config\routing.yml".
AdminHelper is abstract class but Sonata still reads it. Any solution?
1.a) Use ACL for your objects, CRUD controller has permission checking.
1.b) Redefine edit action, make sure that user tries to edit property that belongs to him, something similar to Page Admin Controller, there create action is redefined
2) In controller $this->getConfigurationPool()->getContainer()->get('doctrine')->getRepository($this->getClass()); gives you access to repository registered for this model. Probably there are few other ways to get service container and entity manager from it.
3) To create your admin class you should extend Sonata Admin: docs for this, this problem does not seems to be related to sonata as for me. Can you please provide content for D:_development\rent2\app/config\routing.yml ?