Symfony2 - $this->getUser() vs $this->get('fos_user.user_manager');

Asked
Active3 hr before
Viewed126 times

9 Answers

90%

With $this->getUser() is only a shortcut to,So this means you get the user object according to the current security token. It's perfect and easy, when you want to retrieve the actual logged in user.,...so should I have used the same method for both?,I've found I've used both of the above at different times and everything works fine.

With $this->getUser() is only a shortcut to

$this - > get('security.context') - > getToken() - > getUser()
88%

either returns an object which implements __toString(), or a primitive string is returned.,I think that you actually get the User object but because it implements a __toString method it can be rendered directly in templates.,I think Ramon is right. You already have the user object. ,To see what kind of object you have. But You are actually using an object, not a string.

Also in Symfony > 2.1.x you can use

$this - > getUser();
load more v
72%

either returns an object which implements __toString(), or a primitive string is returned.,I'm using FOSUserBundle to authenticate my users.,I think that you actually get the User object but because it implements a __toString method it can be rendered directly in templates.,For FOSUser ^1.3 you can get current user from inside a controller that extends BaseController like this :

I did not found how to do that because next method where I found it in symfony doc:

$user = $this - > container - > get('security.context') - > getToken() - > getUser();

Currently, I use this method, but it's not working properly.

$username = $this - > container - > get('security.context') - > getToken() - > getUser();
$em = $this - > container - > get('doctrine') - > getEntityManager();
$user = $em - > getRepository('SiteUtilisateurBundle:Utilisateur') - > find($username);
load more v
65%

Я использую FOSUserBundle. В чем разница между этими двумя? , Symfony пользовательский запрос для $this->getUser() в контроллере , MediaWiki $wgUser до $this->getUser() и $context->getUser() не работают , $this->getUser()->isAdmin() VS $this->get('security.authorization_checker')->isGranted('ROLE_ADMIN')

Я использую FOSUserBundle. В чем разница между этими двумя?

$this - > get('fos_user.user_manager');

...и...

$this - > getUser();

Это один из фрагментов кода, который я использовал:

$user = $this - > getUser();
if ($user) {
   $email = $user - > getEmail();
} else {
   $email = "no email";
}

.... и еще один...

$userManager = $this - > get('fos_user.user_manager');
$user = $userManager - > findUserBy(array('memberID' => '123'));
load more v
75%

I am trying to configure FOSOAuthServerBundle with FOSUserBundle using the documentation of FOSOAuthServerBundle. This is the config:,@dre Your configuration for oauth/v2/auth should be under the firewall and under,so $user = $this->getTokenStorage()->getToken()->getUser(); gives you access to user object.,When a user is logged in its info is stored and can be retrieved from the tokenStorage out of the box

fos_user:
   db_driver: orm
firewall_name: oauth_token #main
user_class: Minn\ UserBundle\ Entity\ User

fos_oauth_server:
   db_driver: orm
client_class: Minn\ UserBundle\ Entity\ Client
access_token_class: Minn\ UserBundle\ Entity\ AccessToken
refresh_token_class: Minn\ UserBundle\ Entity\ RefreshToken
auth_code_class: Minn\ UserBundle\ Entity\ AuthCode
service:
   user_provider: fos_user.user_manager # this is added to fos_oauth to use fos_user
for authentication
options:
   supported_scopes: api
load more v
40%

restetToken does this : ,If this function returns true, I set up a new account registration form and on submit the roles are changed and ROLE_USER is removed. ,FOSUserBundle always add the default role (ROLE_USER) to the list of roles to ensure that users always have at least on role, so no matter what you do you won't be able to remove it.,I have checked the database and there is no role user anymore. If I logout, and login back again, $user->hasDefaultRole() still returns true. What am I not seeing here? Or is this an expected behaviour?

I am using FOSUserBundle for my symfony2 project. Upon registration, I check with the function below if the user has the default role ROLE_USER that FOSUB gives.

 /**
  * Returns true if user has ROLE_USER
  *
  * @return boolean 
  */
 public
 function hasDefaultRole() {
    return ($this - > hasRole('ROLE_USER'));
 }

EDIT :

$user = $this - > container - > get('security.context') - > getToken() - > getUser();
...
$userManager = $this - > container - > get('fos_user.user_manager');
$user - > removeRole("ROLE_USER");
$user - > setRoles(array("ROLE_TEACHER", "ROLE_TEACHER_BASIC"));
$user - > setStatus(1);
$userManager - > updateUser($user);
$this - > resetToken($user);

restetToken does this :

 $token = new UsernamePasswordToken($user, null, 'main', $user - > getRoles());
 $this - > container - > get('security.context') - > setToken($token);
load more v
22%

sonata.admin.security.handler.noop: always returns true, can be used with the Symfony firewall,sonata.admin.security.handler.acl: ACL and ROLES to handle permissions,sonata.admin.security.handler.role: ROLES to handle permissions,ACL permissions are immutables

1
2
3
4
5
6
7
8
# config / packages / sonata_admin.yaml

sonata_admin:
   security:
   handler: sonata.admin.security.handler.role

role_admin: ROLE_ADMIN
role_super_admin: ROLE_SUPER_ADMIN
load more v
60%

[Symfony2] FOSUserBundle User en inverse , Rechercher dans le forum ,J'ai légèrement changé mon RegistrationController,Maintenant j'ai tout ça en code

User.php

< ? php
namespace AMiE\ UserBundle\ Entity;

use FOS\ UserBundle\ Entity\ User as BaseUser;
use Doctrine\ ORM\ Mapping as ORM;
use Symfony\ Component\ Validator\ Constraints as Assert;

/**
 * @ORM\Entity
 * @ORM\Table(name="utilisateurs")
 */
class User extends BaseUser {
   /**
    * @ORM\Id
    * @ORM\Column{type="integer", undefined=true}
    * @ORM\GeneratedValue(strategy="AUTO")
    */
   protected $id;

   /*
    * @ORM\OneToOne(targetEntity="AMiE\UserBundle\Entity\Miagiste", inversedBy="utilisateur", cascade={"remove", "persist"})
    */
   protected $miagiste;

   public
   function __construct() {
      parent::__construct();

   }

   public
   function getMiagiste() {
      return $this - > miagiste;
   }

   public
   function setMiagiste($miag) {
      $this - > miagiste = $miag;
   }

} ?
>

Miagiste.php

< ? php
namespace AMiE\ UserBundle\ Entity;

use Doctrine\ ORM\ Mapping as ORM;
use Symfony\ Component\ Validator\ Constraints as Assert;
use AMiE\ UserBundle\ Entity\ User;

/**
 * @ORM\Entity
 * @ORM\Table(name="miagiste")
 */
class Miagiste {
   /**
    * @ORM\Id
    * @ORM\Column{type="integer"}
    * @ORM\GeneratedValue(strategy="AUTO")
    */
   protected $id;

   /**
    * @ORM\OneToOne(targetEntity="AMiE\UserBundle\Entity\User", mappedBy="miagiste", cascade={"remove", "persist"})
    * @ORM\JoinColumn(referencedColumnName="id")
    */
   protected $utilisateur;

   /**
    * @ORM\Column(type="string", length=255)
    */
   protected $prenom;

   public
   function getUtilisateur() {
      return $this - > utilisateur;
   }

   public
   function setUtilisateur(AMiE\ UserBundle\ Entity\ User $user) {
      return $this - > utilisateur = $user;
   }

   public
   function getPrenom() {

      return $this - > prenom;
   }

   public
   function setPrenom($prenom) {
      $this - > prenom = $prenom;
   }
} ?
>

RegistrationFormType.php

< ? php
namespace AMiE\ UserBundle\ Form\ Type;

use Symfony\ Component\ Form\ AbstractType;
use Symfony\ Component\ Form\ FormBuilderInterface;
use Symfony\ Component\ Form\ FormEvent;
use Symfony\ Component\ Form\ FormEvents;

use FOS\ UserBundle\ Form\ Type\ RegistrationFormType as BaseType;

use AMiE\ UserBundle\ Form\ Type\ EnregistrementMiagisteType;
use AMiE\ UserBundle\ Entity\ Miagiste;

class RegistrationFormType extends AbstractType {
   public
   function buildForm(FormBuilderInterface $builder, array $options) {
      // add your custom field
      $builder - > add('miagiste', new EnregistrementMiagisteType())
      //		->remove('username')
      ;
   }

   public
   function getParent() {
      return 'fos_user_registration';
   }

   public
   function getName() {
      return 'acme_user_registration';
   }
}

RegistrationFormHandler.php

<?php

/*
 * This file is part of the FOSUserBundle package.
 *
 * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace AMiE\UserBundle\Form\Handler;

use FOS\UserBundle\Model\UserManagerInterface;
use FOS\UserBundle\Model\UserInterface;
use FOS\UserBundle\Mailer\MailerInterface;
use FOS\UserBundle\Util\TokenGeneratorInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request;

use FOS\UserBundle\Form\Handler\RegistrationFormHandler as BaseHandler;

class RegistrationFormHandler extends BaseHandler
{
	protected $miagiste;
	
    public function process($confirmation = false)
    {
        $user = $this->userManager->createUser();
        $this->form->setData($user);

        if ('POST' == $this->request->getMethod()) {
            $this->form->bindRequest($this->request);
            if ($this->form->isValid()) {

                // do your custom logic here

                return true;
            }
        }

        return false;
    }
}

EnregistrementMiagisteType.php

< ? php

namespace AMiE\ UserBundle\ Form\ Type;

use Symfony\ Component\ Form\ AbstractType;
use Symfony\ Component\ Form\ FormBuilderInterface;
use Symfony\ Component\ OptionsResolver\ OptionsResolverInterface;
use Symfony\ Component\ Form\ FormEvent;
use Symfony\ Component\ Form\ FormEvents;

class EnregistrementMiagisteType extends AbstractType {
   public
   function buildForm(FormBuilderInterface $builder, array $options) {
      $builder - > add('prenom', 'text', array('max_length' => 20, 'required' => false, 'label' => 'Prénom* :', 'trim' => true, 'read_only' => false, 'error_bubbling' => false))

      ;
   }

   public
   function setDefaultOptions(OptionsResolverInterface $resolver) {
      $resolver - > setDefaults(array(
         'data_class' => 'AMiE\UserBundle\Entity\Miagiste'
      ));
   }

   public
   function getName() {
      return 'enregistrementMiagiste';
   }
}
load more v
48%

Tutorial: Symfony Administrations-Backend erstellen ,In dem folgenden Beispiel habe ich einen Guard konfiguriert für den Administrationsbereich, der mitzählt, wie oft sich ein User falsch eingeloggt hat.

security.yaml:

security:
   providers:
   fos_userbundle:
   id: App\ Security\ UserProvider
admin:
   pattern: /admin(.*)
context: user
form_login:
   provider: fos_userbundle
login_path: /admin/login
use_forward: false
check_path: /admin/login_check
failure_path: null
default_target_path: sonata_admin_dashboard
logout:
   path: /admin/logout
target: /admin/login
anonymous: true
guard:
   authenticators:
   -App\ Security\ AdminAuthenticator
provider: fos_userbundle
access_control:
   # Admin login page needs to be accessed without credential -
   {
      path: ^ /admin/login$,
      role: IS_AUTHENTICATED_ANONYMOUSLY
   } -
   {
      path: ^ /admin/logout$,
      role: IS_AUTHENTICATED_ANONYMOUSLY
   } -
   {
      path: ^ /admin/login_check$,
      role: IS_AUTHENTICATED_ANONYMOUSLY
   } -
   {
      path: ^ /admin/,
      role: ROLE_SONATA_ADMIN
   }
load more v

Other "undefined-undefined" queries related to "Symfony2 - $this->getUser() vs $this->get('fos_user.user_manager');"