Error FOSUserBundle / User Entity already done - symfony

I have this error when i try to do http://localhost:8000/profile or any search :
(1/1) FatalErrorException
Compile Error: Access level to AppBundle\Entity\User::$id must be protected (as in class FOS\UserBundle\Model\User) or weaker
in User.php line 19
I just want to create a webpage for admin for my application (that webpage will be like a dashboard) and i don't know how to set access to this webpages for only admin so i tried with FOSUser with a login but if there is a quicker method just tell me (i tried the method : https://symfony.com/doc/current/security/form_login_setup.html but that don't work to it just reload the page when i click submit.)
pls help
My config.yml :
imports:
- { resource: parameters.yml }
- { resource: security.yml }
- { resource: services.yml }
# Put parameters here that don't need to change on each machine where
the app is deployed
#
https://symfony.com/doc/current/best_practices/configuration.html#
application-related-configuration
parameters:
locale: en
image_directory: '%kernel.project_dir%/web/uploads/images'
framework:
#esi: ~
translator: { fallbacks: ['%locale%'] }
secret: '%secret%'
router:
resource: '%kernel.project_dir%/app/config/routing.yml'
strict_requirements: ~
form: ~
csrf_protection: ~
validation: { enable_annotations: true }
#serializer: { enable_annotations: true }
default_locale: '%locale%'
trusted_hosts: ~
session:
#
https://symfony.com/doc/current/reference/configuration/framework.html
#handler-id
handler_id: session.handler.native_file
save_path:
'%kernel.project_dir%/var/sessions/%kernel.environment%'
fragments: ~
http_method_override: true
assets: ~
php_errors:
log: true
# Twig Configuration
twig:
debug: '%kernel.debug%'
strict_variables: '%kernel.debug%'
# Doctrine Configuration
doctrine:
dbal:
driver: pdo_mysql
host: '%database_host%'
port: '%database_port%'
dbname: '%database_name%'
user: '%database_user%'
password: '%database_password%'
charset: UTF8
# if using pdo_sqlite as your database driver:
# 1. add the path in parameters.yml
# e.g. database_path:
'%kernel.project_dir%/var/data/data.sqlite'
# 2. Uncomment database_path in parameters.yml.dist
# 3. Uncomment next line:
#path: '%database_path%'
orm:
auto_generate_proxy_classes: '%kernel.debug%'
naming_strategy: doctrine.orm.naming_strategy.underscore
auto_mapping: true
# Swiftmailer Configuration
swiftmailer:
transport: '%mailer_transport%'
host: '%mailer_host%'
username: '%mailer_user%'
password: '%mailer_password%'
spool: { type: memory }
fos_user:
registration:
form:
type: AppBundle\Form\RegistrationType
db_driver: orm # other valid values are 'mongodb' and 'couchdb'
firewall_name: main
user_class: AppBundle\Entity\User
service: # this lines
mailer: fos_user.mailer.twig_swift # this lines
from_email:
address: "testapp#testapp.com"
sender_name: "Test App"
My security file :
# app/config/security.yml
security:
encoders:
FOS\UserBundle\Model\UserInterface: bcrypt
role_hierarchy:
ROLE_ADMIN: ROLE_USER
ROLE_SUPER_ADMIN: ROLE_ADMIN
providers:
fos_userbundle:
id: fos_user.user_provider.username
firewalls:
main:
pattern: ^/
form_login:
provider: fos_userbundle
csrf_token_generator: security.csrf.token_manager
default_target_path: /list
always_use_default_target_path : true
logout: true
anonymous: true
access_control:
- { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/admin/, role: ROLE_ADMIN }
And that is my user entity :
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation as Serializer;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;
use FOS\UserBundle\Model\User as BaseUser;
/**
* User
*
* #ORM\Table(name="user", uniqueConstraints=
{#ORM\UniqueConstraint(name="user_id_uindex", columns={"id"}),
#ORM\UniqueConstraint(name="user_username_uindex", columns=
{"username"})}, indexes={#ORM\Index(name="user_profile_id_fk",
columns={"id_profile"}), #ORM\Index(name="user_localisation_id_fk",
columns={"id_location"})})
* #ORM\Entity(repositoryClass="AppBundle\Repository\UserRepository")
* #UniqueEntity("username", groups={"Default", "Patch"})
*/
class User extends BaseUser
{
const ROLE_USER = 'ROLE_USER';
const ROLE_ADMIN = 'ROLE_ADMIN';
/**
* #var integer
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
* #Serializer\Groups({"Default", "Deserialize", "user_detail"})
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="username", type="string", length=32, nullable=false)
* #Serializer\Groups({"Default", "Deserialize", "user_detail"})
*/
private $username;
/**
* #var string
* #Serializer\Type("string")
* #Assert\Expression(
* "this.getPassword() === this.getRetypedPassword()",
* message="Password does not match",
* groups={"Default", "Patch"}
* )
* #Assert\NotBlank(groups={"Default"})
* #Serializer\Groups({"Deserialize"})
*/
private $retypedPassword;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=255, nullable=false)
* #Serializer\Groups({"Deserialize", "user_detail"})
* #Assert\Regex(
* pattern="/(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).{7,}/",
* message="Password must be seven characters long and contain at least one digit code, upper case, and lower case letter!",
* groups={"Default", "Patch"}
* )
*/
private $password;
/**
* #var boolean
*
* #ORM\Column(name="enabled", type="boolean", nullable=false)
*/
private $enabled = '1';
/**
* #var \AppBundle\Entity\Localisation
*
* #ORM\ManyToOne(targetEntity="Localisation")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="id_location", referencedColumnName="id")
* })
*/
private $idLocation;
/**
* #var \AppBundle\Entity\Profile
*
* #ORM\ManyToOne(targetEntity="Profile")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="id_profile", referencedColumnName="id")
* })
*/
private $idProfile;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="User", inversedBy="idUserOne")
* #ORM\JoinTable(name="friend",
* joinColumns={
* #ORM\JoinColumn(name="id_user_one", referencedColumnName="id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="id_user_two", referencedColumnName="id")
* }
* )
*/
private $idUserTwo;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="Place", inversedBy="idUserInvited")
* #ORM\JoinTable(name="list_invited",
* joinColumns={
* #ORM\JoinColumn(name="id_user_invited", referencedColumnName="id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="id_place_invited", referencedColumnName="id")
* }
* )
*/
private $idPlaceInvited;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="Place", mappedBy="idUserPresent")
*/
private $idPlacePresent;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="Place", inversedBy="idUserPlace")
* #ORM\JoinTable(name="user_place",
* joinColumns={
* #ORM\JoinColumn(name="id_user_place", referencedColumnName="id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="id_place_place", referencedColumnName="id")
* }
* )
*/
private $idPlacePlace;
/**
* #var array
* #ORM\Column(type="simple_array", length=200)
* #Serializer\Exclude()
*/
private $roles;
/**
* Constructor
*/
public function __construct()
{
parent::__construct();
$this->idUserTwo = new \Doctrine\Common\Collections\ArrayCollection();
$this->idPlaceInvited = new \Doctrine\Common\Collections\ArrayCollection();
$this->idPlacePresent = new \Doctrine\Common\Collections\ArrayCollection();
$this->idPlacePlace = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* #return int
*/
public function getId(): int
{
return $this->id;
}
/**
* #param int $id
*/
public function setId(int $id): void
{
$this->id = $id;
}
/**
* #return string
*/
public function getUsername(): string
{
return $this->username;
}
/**
* #param string $username
*/
public function setUsername(string $username): void
{
$this->username = $username;
}
/**
* #return string
*/
public function getPassword(): string
{
return $this->password;
}
/**
* #param string $password
*/
public function setPassword(string $password): void
{
$this->password = $password;
}
/**
* #return bool
*/
public function isEnabled(): bool
{
return $this->enabled;
}
/**
* #param bool $enabled
*/
public function setEnabled(bool $enabled): void
{
$this->enabled = $enabled;
}
/**
* #return mixed
*/
public function getIdLocation()
{
return $this->idLocation;
}
/**
* #param mixed $idLocation
*/
public function setIdLocation($idLocation): void
{
$this->idLocation = $idLocation;
}
/**
* #return mixed
*/
public function getIdProfile()
{
return $this->idProfile;
}
/**
* #param mixed $idProfile
*/
public function setIdProfile($idProfile): void
{
$this->idProfile = $idProfile;
}
/**
* #return \Doctrine\Common\Collections\Collection
*/
public function getIdUserTwo(): \Doctrine\Common\Collections\Collection
{
return $this->idUserTwo;
}
/**
* #param \Doctrine\Common\Collections\Collection $idUserTwo
*/
public function setIdUserTwo(\Doctrine\Common\Collections\Collection $idUserTwo): void
{
$this->idUserTwo = $idUserTwo;
}
/**
* #return \Doctrine\Common\Collections\Collection
*/
public function getIdPlaceInvited(): \Doctrine\Common\Collections\Collection
{
return $this->idPlaceInvited;
}
/**
* #param \Doctrine\Common\Collections\Collection $idPlaceInvited
*/
public function setIdPlaceInvited(\Doctrine\Common\Collections\Collection $idPlaceInvited): void
{
$this->idPlaceInvited = $idPlaceInvited;
}
/**
* #return \Doctrine\Common\Collections\Collection
*/
public function getIdPlacePresent(): \Doctrine\Common\Collections\Collection
{
return $this->idPlacePresent;
}
/**
* #param \Doctrine\Common\Collections\Collection $idPlacePresent
*/
public function setIdPlacePresent(\Doctrine\Common\Collections\Collection $idPlacePresent): void
{
$this->idPlacePresent = $idPlacePresent;
}
/**
* #return \Doctrine\Common\Collections\Collection
*/
public function getIdPlacePlace(): \Doctrine\Common\Collections\Collection
{
return $this->idPlacePlace;
}
/**
* #param \Doctrine\Common\Collections\Collection $idPlacePlace
*/
public function setIdPlacePlace(\Doctrine\Common\Collections\Collection $idPlacePlace): void
{
$this->idPlacePlace = $idPlacePlace;
}
/**
* #return string
*/
public function getRetypedPassword(): string
{
return $this->retypedPassword;
}
/**
* #param string $retypedPassword
*/
public function setRetypedPassword(string $retypedPassword): void
{
$this->retypedPassword = $retypedPassword;
}
/**
* Returns the roles granted to the user.
*
* <code>
* public function getRoles()
* {
* return array('ROLE_USER');
* }
* </code>
*
* Alternatively, the roles might be stored on a ``roles`` property,
* and populated in any number of different ways when the user object
* is created.
*
* #return (Role|string)[] The user roles
*/
public function getRoles()
{
return $this->roles;
}
/**
* #param array $roles
*/
public function setRoles(array $roles)
{
$this->roles = $roles;
}
/**
* Returns the salt that was originally used to encode the password.
*
* This can return null if the password was not encoded using a salt.
*
* #return string|null The salt
*/
public function getSalt()
{
// TODO: Implement getSalt() method.
}
/**
* Removes sensitive data from the user.
*
* This is important if, at any given point, sensitive information like
* the plain-text password is stored on this object.
*/
public function eraseCredentials()
{
// TODO: Implement eraseCredentials() method.
}
}

Related

Cannot refresh token because user has changed Syfmony 4 - EquatableInterface problem

I have made login form with Security Guide. When I try to login I have logs like below:
2019-06-10 10:16:56] security.INFO: User has been authenticated successfully. {"username":"user#example.com"} []
[2019-06-10 10:16:56] security.DEBUG: Stored the security token in the session. {"key":"_security_main"} []
[2019-06-10 10:16:56] request.INFO: Matched route "app_user_dashboard". {"route":"app_user_dashboard","route_parameters":{"_route":"app_user_dashboard","_controller":"App\\Controller\\User\\UserController::dashboard"},"request_uri":"https://127.0.0.1:8001/app/dashboard","method":"GET"} []
[2019-06-10 10:16:56] security.DEBUG: Read existing security token from the session. {"key":"_security_main","token_class":"Symfony\\Component\\Security\\Core\\Authentication\\Token\\UsernamePasswordToken"} []
[2019-06-10 10:16:57] doctrine.DEBUG: SELECT t0.id AS id_1, t0.password AS password_2, t0.email AS email_3, t0.first_name AS first_name_4, t0.last_name AS last_name_5, t0.username AS username_6, t0.referral_code AS referral_code_7, t0.referred_by_code AS referred_by_code_8, t0.roles AS roles_9, t0.active_to AS active_to_10, t0.created_at AS created_at_11, t0.updated_at AS updated_at_12 FROM users t0 WHERE t0.id = ? [15] []
[2019-06-10 10:16:57] security.DEBUG: Cannot refresh token because user has changed. {"username":"user#example.com","provider":"Symfony\\Bridge\\Doctrine\\Security\\User\\EntityUserProvider"} []
[2019-06-10 10:16:57] security.DEBUG: Token was deauthenticated after trying to refresh it. [] []
and also I use EquatableInterface. My User.php code:
namespace App\Entity\User;
use DateTime;
use Doctrine\ORM\Mapping as ORM;
use Exception;
use Serializable;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\EquatableInterface;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* Class User
*
* #ORM\Table(name="users")
* #ORM\Entity(repositoryClass="App\Repository\User\UserRepository")
* #ORM\HasLifecycleCallbacks
*
* #ORM\Entity
* #UniqueEntity(fields="username", message="username taken")
* #UniqueEntity(fields="email", message="email taken")
*/
class User implements UserInterface, Serializable, EquatableInterface
{
/**
* #var int
*
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(type="string", length=256)
*/
private $password;
/**
* #var string
*
* #ORM\Column(type="string", length=64, unique=true)
*/
private $email;
/**
* #var string|null
*
* #ORM\Column(type="string", length=64, nullable=true)
*/
private $firstName;
/**
* #var string|null
*
* #ORM\Column(type="string", length=64, nullable=true)
*/
private $lastName;
/**
* #var string
*
* #ORM\Column(type="string", length=64, unique=true)
*/
private $username;
/**
* #var string
*
* #ORM\Column(type="string", length=64, unique=true)
*/
private $referralCode;
/**
* #var string|null
*
* #ORM\Column(type="string", length=64, nullable=true)
*/
private $referredByCode;
/**
* #var array
*
* #ORM\Column(type="array", length=64)
*/
private $roles;
/**
* #var DateTime
*
* #ORM\Column(type="datetime")
*/
private $activeTo;
/**
* #var DateTime
*
* #ORM\Column(type="datetime")
*/
private $createdAt;
/**
* #var DateTime
*
* #ORM\Column(type="datetime", nullable=true)
*/
private $updatedAt;
/**
* User constructor.
*
* #throws Exception
*/
public function __construct()
{
$this->createdAt = new DateTime();
$this->updatedAt = new DateTime();
$this->activeTo = new DateTime('now + 14 days');
$this->referralCode = substr(hash('sha256', uniqid()), 0, 5);
}
/**
* #return string
*/
public function __toString()
{
return $this->getUsername();
}
/**
* #return int
*/
public function getId(): int
{
return $this->id;
}
/**
* #param string $username
*/
public function setUsername(string $username): void
{
$this->username = $username;
}
/**
* #return string
*/
public function getUsername(): ?string
{
return $this->username;
}
/**
* #return null|string
*/
public function getSalt(): ?string
{
// you *may* need a real salt depending on your encoder
// see section on salt below
return null;
}
/**
* #return string
*/
public function getPassword(): ?string
{
return $this->password;
}
/**
* #param string $password
*/
public function setPassword(string $password)
{
$this->password = $password;
}
/**
* #return array
*/
public function getRoles(): array
{
// return $this->roles;
return ['ROLE_USER', 'ROLE_API_USER'];
}
/**
*
*/
public function eraseCredentials()
{
}
/**
* #see Serializable::serialize()
*/
public function serialize()
{
return serialize(array($this->id, $this->email));
}
/**
* #see Serializable::unserialize()
*
* #param $serialized
*/
public function unserialize($serialized)
{
list ($this->id, $this->email) = unserialize($serialized, array('allowed_classes' => false));
}
/**
* #return string
*/
public function getEmail(): ?string
{
return $this->email;
}
/**
* #param string $email
*/
public function setEmail(string $email): void
{
$this->email = $email;
}
/**
* #return DateTime
*/
public function getCreatedAt(): DateTime
{
return $this->createdAt;
}
/**
* #ORM\PrePersist
*
* #throws Exception
*/
public function setCreatedAt(): void
{
$this->createdAt = new DateTime();
}
/**
* #return DateTime
*/
public function getUpdatedAt(): DateTime
{
return $this->updatedAt;
}
/**
* #ORM\PreUpdate
*
* #throws Exception
*/
public function setUpdatedAt(): void
{
$this->updatedAt = new DateTime();
}
/**
* #return DateTime
*/
public function getActiveTo(): DateTime
{
return $this->activeTo;
}
/**
* #param DateTime $activeTo
*/
public function setActiveTo(DateTime $activeTo): void
{
$this->activeTo = $activeTo;
}
/**
* #return string
*/
public function getReferralCode(): string
{
return $this->referralCode;
}
/**
* #param string $referralCode
*/
public function setReferralCode(string $referralCode): void
{
$this->referralCode = $referralCode;
}
/**
* #return string|null
*/
public function getReferredByCode():? string
{
return $this->referredByCode;
}
/**
* #param string|null $referredByCode
*/
public function setReferredByCode(?string $referredByCode): void
{
$this->referredByCode = $referredByCode;
}
/**
* #return string|null
*/
public function getFirstName(): ?string
{
return $this->firstName;
}
/**
* #param string|null $firstName
*/
public function setFirstName(?string $firstName): void
{
$this->firstName = $firstName;
}
/**
* #return string|null
*/
public function getLastName(): ?string
{
return $this->lastName;
}
/**
* #param string|null $lastName
*/
public function setLastName(?string $lastName): void
{
$this->lastName = $lastName;
}
/**
* #param array $roles
*/
public function setRoles(array $roles): void
{
$this->roles = $roles;
}
/**
* The equality comparison should neither be done by referential equality
* nor by comparing identities (i.e. getId() === getId()).
*
* However, you do not need to compare every attribute, but only those that
* are relevant for assessing whether re-authentication is required.
*
* #param UserInterface $user
*
* #return bool
*/
public function isEqualTo(UserInterface $user)
{
if ($this->username !== $user->getUsername()) {
return false;
}
return true;
}
}
and security.yaml
encoders:
App\Entity\User\User:
algorithm: auto
providers:
user_provider:
entity:
class: App\Entity\User\User
property: username
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
http_basic: ~
anonymous: true
# logout_on_user_change: true
provider: user_provider
form_login:
login_path: app_user_login
check_path: app_user_login
default_target_path: app_user_dashboard
csrf_token_generator: security.csrf.token_manager
logout:
path: /app/logout
target: /app/login
# activate different ways to authenticate
# http_basic: true
# https://symfony.com/doc/current/security.html#a-configuring-how-your-users-will-authenticate
# form_login: true
# https://symfony.com/doc/current/security/form_login_setup.html
# Easy way to control access for large sections of your site
# Note: Only the *first* access control that matches will be used
access_control:
- { path: ^/app/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/app/register, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/app, roles: IS_AUTHENTICATED_FULLY }
I have red this post: Token was deauthenticated after trying to refresh it and that solution does not work for me. Any ideas?
You've got 2 options here:
Make your firewall stateless or
update your serialization in you User
I'm referring to https://symfony.com/doc/current/security/user_provider.html#understanding-how-users-are-refreshed-from-the-session btw, as I had the same issue.
First solution:
firewalls:
# ...
main:
http_basic: ~
anonymous: true
stateless: true
This should make Symfony ignore your serialization and just reload the whole entity from database.
Second solution:
class User implements UserInterface, Serializable, EquatableInterface
{
public function serialize()
{
return serialize(array(
$this->id,
$this->password,
$this->email,
$this->username,
$this->activeTo,
));
}
public function unserialize($serialized)
{
list (
$this->id,
$this->password,
$this->email,
$this->username,
$this->activeTo,
) = unserialize($serialized, array('allowed_classes' => false));
}
}
You should keep any information that Symfony might need in any of your user_checker classes (or the default ones).

Doctrine Extension Translatable doesn't retrieve translation

I use personal translation of StofDoctrineExtensionsBundle.
I've configured my App but i can't retrieve the translated labels, i get always the default text.
config.yml
# Doctrine Configuration
doctrine:
orm:
auto_generate_proxy_classes: "%kernel.debug%"
naming_strategy: doctrine.orm.naming_strategy.underscore
auto_mapping: true
mappings:
menu_tree:
type: annotation
prefix: Gedmo\Tree\Entity
dir: "%kernel.root_dir%/../vendor/gedmo/doctrine-extensions/lib/Gedmo/Tree/Entity"
alias: MenuTree
is_bundle: false
gedmo_translatable:
type: annotation
prefix: Gedmo\Translatable\Entity
dir: "%kernel.root_dir%/../vendor/gedmo/doctrine-extensions/lib/Gedmo/Translatable/Entity"
alias: GedmoTranslatable # (optional) it will default to the name set for the mapping
is_bundle: false
gedmo_translator:
type: annotation
prefix: Gedmo\Translator\Entity
dir: "%kernel.root_dir%/../vendor/gedmo/doctrine-extensions/lib/Gedmo/Translator/Entity"
alias: GedmoTranslator # (optional) it will default to the name set for the mapping
is_bundle: false
stof_doctrine_extensions:
default_locale: "%locale%"
translation_fallback: true
orm:
default:
tree: true
translatable: true
sluggable: true
Then i wrote my personal Entity, this is a MenuItem
<?php
namespace App\Entity\Menu;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
/**
*
* #ORM\Table(name="mnu_item")
* #ORM\Entity(repositoryClass="App\Repository\Menu\MenuItem")
* #Gedmo\Tree(type="nested")
* #Gedmo\TranslationEntity(class="App\Entity\Menu\MenuItemTranslation")
*/
class MenuItem{
/**
*
* #var integer
*
* #ORM\Column(name="id", type="integer", options={"unsigned"=true})
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
*
* #var string
* #Gedmo\Translatable
* #ORM\Column(name="label", type="string", length=255, nullable=true)
*/
private $label;
/**
* #Gedmo\Locale
* Used locale to override Translation listener`s locale
* this is not a mapped field of entity metadata, just a simple property
* and it is not necessary because globally locale can be set in listener
*/
private $locale;
/**
* #ORM\OneToMany(targetEntity="\App\Entity\Menu\MenuItemTranslation",
* mappedBy="object",
* cascade={"persist", "remove"})
*/
private $translations;
/**
* #var \App\Entity\Menu\Menu
*
* #ORM\ManyToOne(targetEntity="App\Entity\Menu\Menu", inversedBy="menuItems")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="menu_id", referencedColumnName="id", onDelete="CASCADE")
* })
*/
private $menu;
/**
* Constructor
*/
public function __construct() {
$this->ruoli = new \Doctrine\Common\Collections\ArrayCollection();
$this->children = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId() {
return $this->id;
}
/**
* Set label
*
* #param string $label
*
* #return MenuItem
*/
public function setLabel($label) {
$this->label = $label;
return $this;
}
/**
* Get label
*
* #return string
*/
public function getLabel() {
return $this->label;
}
/**
* Set menu
*
* #param \App\Entity\Menu\Menu $menu
*
* #return MenuItem
*/
public function setMenu(\App\Entity\Menu\Menu $menu = null) {
$this->menu = $menu;
return $this;
}
/**
* Get menu
*
* #return \App\Entity\Menu\Menu
*/
public function getMenu() {
return $this->menu;
}
/**
*
* #return type
*/
public function getTranslations(){
return $this->translations;
}
/**
*
* #param \App\Entity\Menu\MenuItemTranslation $t
*/
public function addTranslation(MenuItemTranslation $t){
if (!$this->translations->contains($t)) {
$this->translations[] = $t;
$t->setObject($this);
}
}
public function setTranslatableLocale($locale){
$this->locale = $locale;
}
}
At least i have my Translator Class
<?php
namespace App\Entity\Menu;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Translatable\Entity\MappedSuperclass\AbstractPersonalTranslation;
/**
* Description of MenuItemTranslation
/*
* #ORM\Entity
* #ORM\Table(name="mnu_menu_item_translations",
* uniqueConstraints={#ORM\UniqueConstraint(name="lookup_unique_idx", columns={
* "locale", "object_id", "field"
* })}
* )
*/
class MenuItemTranslation extends AbstractPersonalTranslation {
/**
* Convenient constructor
*
* #param string $locale
* #param string $field
* #param string $value
*/
public function __construct($locale, $field, $value)
{
$this->setLocale($locale);
$this->setField($field);
$this->setContent($value);
}
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Menu\MenuItem", inversedBy="translations")
* #ORM\JoinColumn(name="object_id", referencedColumnName="id", onDelete="CASCADE")
*/
protected $object;
}
I have translated my label and it works, but in a twig tempate, using item.label or item.getLabel() i obtain always the default MenuItem valu (E.g. Test insted of Prova, see images)
Menu Item
Menu Item Translation
I've messed with locale.
I changed the stof config 'cos my site is all in english and i need italian translation
stof_doctrine_extensions:
default_locale: "%locale%" #this is my error, just remove this line
# to set it back to en_US (default value).
# This indicates the locale of original table,
# if it's set to the same
# locale of the entire system it won't
# retrieve any translation
translation_fallback: true
orm:
default:
tree: true
translatable: true
sluggable: true
So the correct one is
Then i changed the stof config 'cos my site is all in english and i need italian translation
stof_doctrine_extensions:
translation_fallback: true
orm:
default:
tree: true
translatable: true
sluggable: true

Login without FOSuser

I'm trying to make a login form without FOSuser, as I need to override a lot in the entity User. I tried to find a lot of informations with the cookbook, and on several sites, but the mere informations were for SF2, which is quite annoying as the code may be different.
I managed to make a registration form, which records the User on the db, but my login form doesn't want to work whatever I can do. I have only one error message, "Invalid credential". I thought it could be because of a bad algorithm, but I changed it three or four times (bcrypt, sha512, none...), no success.
Here's my security.yml (I know that there's a lot a useless code but I don't want to remove anything that could be useful):
security:
encoders:
Symfony\Component\Security\Core\User\User:
algorithm: sha512
role_hierarchy:
ROLE_ADMIN: ROLE_USER
# http://symfony.com/doc/current/book/security.html#where-do-users-come-from-user-providers
providers:
in_memory:
memory:
users:
user: { password: userpass, roles: [ 'ROLE_USER' ] }
admin: { password: adminpass, roles: [ 'ROLE_ADMIN' ] }
our_db_provider:
entity:
class: FrontBundle:User
property: username
firewalls:
# disables authentication for assets and the profiler, adapt it according to your needs
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
login:
pattern: ^/login$
security: false
login:
pattern: ^/register$
security: false
main:
anonymous: false
pattern: ^/
form_login:
login_path: login
check_path: login_check
logout:
path: /logout
target: /
# activate different ways to authenticate
# http_basic: ~
# http://symfony.com/doc/current/book/security.html#a-configuring-how-your-users-will-authenticate
# form_login: ~
# http://symfony.com/doc/current/cookbook/security/form_login_setup.html
access_control:
- { path: ^/register$, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/login_check, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/, roles: ROLE_ADMIN }
Here's my entity User (excuse my french, it's a school project :) ):
<?php
namespace FrontBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;
/**
* User
*
* #ORM\Table(name="user")
* #ORM\Entity(repositoryClass="FrontBundle\Repository\UserRepository")
*/
class User implements UserInterface
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="nom", type="string", length=255)
*/
private $nom;
/**
* #var string
*
* #ORM\Column(name="username", type="string", length=255, unique=true)
*/
private $username;
/**
* #var string
*
* #ORM\Column(name="prenom", type="string", length=255)
*/
private $prenom;
/**
* #var string
*
* #ORM\Column(name="mail", type="string", length=255, unique=true)
*/
private $mail;
/**
* #Assert\NotBlank()
* #Assert\Length(max=4096)
*/
private $plainPassword;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=255)
*/
private $password;
/**
* #var string
*
* #ORM\Column(name="salt", type="string", length=255, nullable=true)
*/
private $salt;
/**
* #var string
*
* #ORM\Column(name="photo", type="string", length=255, nullable=true)
*/
private $photo;
/**
* #var string
*
* #ORM\Column(name="ville", type="string", length=255, nullable=true)
*/
private $ville;
/**
* #var array
*
* #ORM\Column(type="array", nullable=false)
*/
protected $roles;
/**
* #ORM\ManyToOne(targetEntity="Entreprise", inversedBy="users", cascade={"remove"})
* #ORM\JoinColumn(name="entreprise_id", referencedColumnName="id")
*/
protected $entreprise;
/**
* #ORM\ManyToOne(targetEntity="Promotion", inversedBy="users", cascade={"remove"})
* #ORM\JoinColumn(name="promotion_id", referencedColumnName="id")
*/
protected $promotion;
/**
* #ORM\OneToMany(targetEntity="Annonce", mappedBy="user", cascade={"remove", "persist"})
*/
protected $annonces;
/**
* #ORM\OneToMany(targetEntity="Commentaire", mappedBy="user", cascade={"remove", "persist"})
*/
protected $commentaires;
/**
* #ORM\OneToMany(targetEntity="Article", mappedBy="user", cascade={"remove", "persist"})
*/
protected $articles;
/**
* #ORM\OneToMany(targetEntity="Evenement", mappedBy="user", cascade={"remove", "persist"})
*/
protected $evenements;
/**
* #ORM\ManyToMany(targetEntity="Evenement", inversedBy="users")
* #ORM\JoinTable(name="evenement_user")
*/
private $participe;
/**
* #ORM\ManyToMany(targetEntity="Groupe", inversedBy="users")
* #ORM\JoinTable(name="groupe_user")
*/
private $groupes;
public function __construct() {
$this->participe = new \Doctrine\Common\Collections\ArrayCollection();
$this->groupes = new \Doctrine\Common\Collections\ArrayCollection();
$this->roles = array("ROLE_USER");
$this->salt = base_convert(sha1(uniqid(mt_rand(), true)), 16, 36);
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set nom
*
* #param string $nom
*
* #return User
*/
public function setNom($nom)
{
$this->nom = $nom;
return $this;
}
/**
* Get nom
*
* #return string
*/
public function getNom()
{
return $this->nom;
}
/**
* Set prenom
*
* #param string $prenom
*
* #return User
*/
public function setPrenom($prenom)
{
$this->prenom = $prenom;
return $this;
}
/**
* Get prenom
*
* #return string
*/
public function getPrenom()
{
return $this->prenom;
}
/**
* Set mail
*
* #param string $mail
*
* #return User
*/
public function setMail($mail)
{
$this->mail = $mail;
return $this;
}
/**
* Get mail
*
* #return string
*/
public function getMail()
{
return $this->mail;
}
/**
* Set password
*
* #param string $password
*
* #return User
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Get password
*
* #return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Set photo
*
* #param string $photo
*
* #return User
*/
public function setPhoto($photo)
{
$this->photo = $photo;
return $this;
}
/**
* Get photo
*
* #return string
*/
public function getPhoto()
{
return $this->photo;
}
/**
* Set ville
*
* #param string $ville
*
* #return User
*/
public function setVille($ville)
{
$this->ville = $ville;
return $this;
}
/**
* Get ville
*
* #return string
*/
public function getVille()
{
return $this->ville;
}
/**
* Set entreprise
*
* #param \FrontBundle\Entity\Entreprise $entreprise
*
* #return User
*/
public function setEntreprise(\FrontBundle\Entity\Entreprise $entreprise = null)
{
$this->entreprise = $entreprise;
return $this;
}
/**
* Get entreprise
*
* #return \FrontBundle\Entity\Entreprise
*/
public function getEntreprise()
{
return $this->entreprise;
}
/**
* Set promotion
*
* #param \FrontBundle\Entity\Promotion $promotion
*
* #return User
*/
public function setPromotion(\FrontBundle\Entity\Promotion $promotion = null)
{
$this->promotion = $promotion;
return $this;
}
/**
* Get promotion
*
* #return \FrontBundle\Entity\Promotion
*/
public function getPromotion()
{
return $this->promotion;
}
/**
* Add annonce
*
* #param \FrontBundle\Entity\Annonce $annonce
*
* #return User
*/
public function addAnnonce(\FrontBundle\Entity\Annonce $annonce)
{
$this->annonces[] = $annonce;
return $this;
}
/**
* Remove annonce
*
* #param \FrontBundle\Entity\Annonce $annonce
*/
public function removeAnnonce(\FrontBundle\Entity\Annonce $annonce)
{
$this->annonces->removeElement($annonce);
}
/**
* Get annonces
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getAnnonces()
{
return $this->annonces;
}
/**
* Add commentaire
*
* #param \FrontBundle\Entity\Commentaire $commentaire
*
* #return User
*/
public function addCommentaire(\FrontBundle\Entity\Commentaire $commentaire)
{
$this->commentaires[] = $commentaire;
return $this;
}
/**
* Remove commentaire
*
* #param \FrontBundle\Entity\Commentaire $commentaire
*/
public function removeCommentaire(\FrontBundle\Entity\Commentaire $commentaire)
{
$this->commentaires->removeElement($commentaire);
}
/**
* Get commentaires
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getCommentaires()
{
return $this->commentaires;
}
/**
* Add article
*
* #param \FrontBundle\Entity\Article $article
*
* #return User
*/
public function addArticle(\FrontBundle\Entity\Article $article)
{
$this->articles[] = $article;
return $this;
}
/**
* Remove article
*
* #param \FrontBundle\Entity\Article $article
*/
public function removeArticle(\FrontBundle\Entity\Article $article)
{
$this->articles->removeElement($article);
}
/**
* Get articles
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getArticles()
{
return $this->articles;
}
/**
* Add evenement
*
* #param \FrontBundle\Entity\Evenement $evenement
*
* #return User
*/
public function addEvenement(\FrontBundle\Entity\Evenement $evenement)
{
$this->evenements[] = $evenement;
return $this;
}
/**
* Remove evenement
*
* #param \FrontBundle\Entity\Evenement $evenement
*/
public function removeEvenement(\FrontBundle\Entity\Evenement $evenement)
{
$this->evenements->removeElement($evenement);
}
/**
* Get evenements
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getEvenements()
{
return $this->evenements;
}
/**
* Add participe
*
* #param \FrontBundle\Entity\Evenement $participe
*
* #return User
*/
public function addParticipe(\FrontBundle\Entity\Evenement $participe)
{
$this->participe[] = $participe;
return $this;
}
/**
* Remove participe
*
* #param \FrontBundle\Entity\Evenement $participe
*/
public function removeParticipe(\FrontBundle\Entity\Evenement $participe)
{
$this->participe->removeElement($participe);
}
/**
* Get participe
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getParticipe()
{
return $this->participe;
}
/**
* Add groupe
*
* #param \FrontBundle\Entity\Groupe $groupe
*
* #return User
*/
public function addGroupe(\FrontBundle\Entity\Groupe $groupe)
{
$this->groupes[] = $groupe;
return $this;
}
/**
* Remove groupe
*
* #param \FrontBundle\Entity\Groupe $groupe
*/
public function removeGroupe(\FrontBundle\Entity\Groupe $groupe)
{
$this->groupes->removeElement($groupe);
}
/**
* Get groupes
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getGroupes()
{
return $this->groupes;
}
public function getRoles() {
return array($this->roles);
}
public function getUsername() {
return $this->username;
}
public function getSalt() {
return $this->salt;
}
public function eraseCredentials() {
// Ici nous n'avons rien à effacer.
// Cela aurait été le cas si nous avions un mot de passe en clair.
}
/**
* Set username
*
* #param string $username
*
* #return User
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* Set salt
*
* #param string $salt
*
* #return User
*/
public function setSalt($salt)
{
$this->salt = $salt;
return $this;
}
/**
* Set roles
*
* #param string $roles
*
* #return User
*/
public function setRoles($roles)
{
$this->roles = $roles;
return $this;
}
public function getPlainPassword()
{
return $this->plainPassword;
}
public function setPlainPassword($password)
{
$this->plainPassword = $password;
}
}
Here's my SecurityController:
namespace FrontBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Request;
class SecurityController extends Controller
{
/**
* #Route("/login", name="login")
* #Template()
*/
public function loginAction(Request $request)
{
$authenticationUtils = $this->get('security.authentication_utils');
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('FrontBundle:Security:login.html.twig', array(
'last_username' => $lastUsername,
'error' => $error,
));
}
}
Here are my routes:
login:
path: /login
defaults: { _controller: FrontBundle:Security:login}
login_check:
path: /login_check
I think these are the only files needed to make it work, please tell me if you need anything else.
Thanks if you can help me :)

FOSUserBundle: Unrecognized field: usernameCanonical

First of all, I know SO is full of questions like this but I tried to combine different config values according to those responses with no luck.
I'm using FOSUserBundle with my own User class and when submiting login form I get this error:
Unrecognized field: usernameCanonical
Here are some bits of my code:
doctrine:
auto_generate_proxy_classes: "%kernel.debug%"
naming_strategy: doctrine.orm.naming_strategy.underscore
auto_mapping: true
# mappings:
# FOSUserBundle: ~
fos_user:
service:
mailer: fos_user.mailer.twig_swift
db_driver: orm
firewall_name: main
user_class: AppBundle\Entity\User
Some variations tested include setting auto_mapping: false and/or uncommenting mappings.FOSUserBundle: ~
This is my user class:
<?php
namespace AppBundle\Entity;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* AppBundle\Entity\User
*
* #ORM\Entity
* #ORM\Table(name="user")
*/
class User extends BaseUser implements UserInterface
{
const ROLE_DEFAULT = 'ROLE_ADMIN';
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="string", length=100)
*/
protected $name;
/**
* #ORM\Column(type="string", length=40)
* #Assert\Email()
*/
protected $login;
/**
* #ORM\Column(type="string", length=255)
*/
protected $password;
/**
* #ORM\Column(type="string", length=255)
*/
protected $salt;
/**
* #ORM\Column(type="array", length=255)
*/
protected $roles;
/**
* Método requerido por la interfaz UserInterface
*/
public function equals(\Symfony\Component\Security\Core\User\UserInterface $user)
{
return $this->getLogin() == $user->getLogin();
}
/**
* Método requerido por la interfaz UserInterface
*/
public function eraseCredentials()
{
}
/**
* Método requerido por la interfaz UserInterface
*/
public function getUsername()
{
return $this->getLogin();
}
public function __toString()
{
return $this->getName();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set login
*
* #param string $login
*/
public function setLogin($login)
{
$this->login = $login;
}
/**
* Get login
*
* #return string
*/
public function getLogin()
{
return $this->login;
}
/**
* Set password
*
* #param string $password
*/
public function setPassword($password)
{
$this->password = $password;
}
/**
* Get salt
*
* #return string
*/
public function getSalt()
{
return $this->salt;
}
/**
* Set salt
*
* #param string $salt
*/
public function setSalt($salt)
{
$this->salt = $salt;
}
/**
* Get password
*
* #return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Adds a role to the user.
*
* #param string $role
*/
public function addRole($role)
{
$role = strtoupper($role);
if ($role === static::ROLE_DEFAULT) {
return;
}
if (!in_array($role, $this->roles, true)) {
$this->roles[] = $role;
}
}
/**
* Returns the user roles
*
* Implements SecurityUserInterface
*
* #return array The roles
*/
public function getRoles()
{
$roles = $this->roles;
foreach ($this->getGroups() as $group) {
$roles = array_merge($roles, $group->getRoles());
}
// we need to make sure to have at least one role
$roles[] = static::ROLE_DEFAULT;
return array_unique($roles);
}
/**
* Set roles
*
* #param string $roles
*/
public function setRoles(array $roles)
{
$this->roles = $roles;
}
/**
* Never use this to check if this user has access to anything!
*
* Use the SecurityContext, or an implementation of AccessDecisionManager
* instead, e.g.
*
* $securityContext->isGranted('ROLE_USER');
*
* #param string $role
* #return Boolean
*/
public function hasRole($role)
{
return in_array(strtoupper($role), $this->getRoles(), true);
}
}
Login (layout.html.twig actually) template has been overriden and apparently renders properly, my versions are:
Symonfy: Symfony version 2.8.2 - app/dev/debug
"friendsofsymfony/user-bundle": "^1.3"
console doctrine:schema:updatehas been executed and it doesn't detect any more changes, although usernameCanonical or email do not exist in the DB table.
Thanks
With FOSUserBundle 1.3.x you have to extend FOS\UserBundle\Entity\User instead of FOS\UserBundle\Model\User (see http://symfony.com/doc/1.3.x/bundles/FOSUserBundle/index.html#a-doctrine-orm-user-class).

Unrecognized field: usernameCanonical for symfony2 FosUserbundle

I have a problem with the FOSUserBundle.
A know problem : 'Unrecognized field: usernameCanonical for symfony2 FosUserbundle' when I try a login
AND
on schema update I get this error:
Duplicate definition of column 'username' on entity 'Acme\ProjectBundle\Entity\User' in a field or discriminator column mapping.
I get this error ONLY IF I add the 'FOSUserBundle: ~' to settings of doctrine's mapping in the config.yml
I have tried a lot of solutions but I don't have resoved my problem :/
Please help me.
I have followed the FOS' team: https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Resources/doc/index.md
Before everything worked perfectly ...
I have Symfony 2.1.9
My config.yml:
doctrine:
dbal:
default_connection: default
connections:
default:
driver: "%database_driver%"
host: "%database_host%"
port: "%database_port%"
dbname: "%database_name%"
user: "%database_user%"
password: "%database_password%"
charset: UTF8
service:
driver: "%database_driver2%"
host: "%database_host2%"
port: "%database_port2%"
dbname: "%database_name2%"
user: "%database_user2%"
password: "%database_password2%"
charset: UTF8
orm:
auto_generate_proxy_classes: "%kernel.debug%"
#auto_mapping: true
default_entity_manager: default
entity_managers:
default:
metadata_cache_driver: apc
result_cache_driver: apc
query_cache_driver: apc
connection: default
mappings:
FOSUserBundle: ~
AcmeProjectBundle: {type: yml, dir: Resources/config/doctrine/ } #also tried wit '~'
fos_user:
db_driver: orm # other valid values are 'mongodb', 'couchdb' and 'propel'
firewall_name: main
user_class: Acme\ProjectBundle\Entity\User
My Acme\ProjectBundle\Entity\User.php:
namespace Acme\ProjectBundle\Entity;
use FOS\UserBundle\Entity\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Security\Core\User\UserInterface;
class User extends BaseUser implements UserInterface, \Serializable
{
const TYPE_ADMIN = 0;
const TYPE_USER = 2;
const TYPE_ARTIST = 3;
/**
* #var string $salt
*/
protected $salt;
/**
* #var boolean $is_active
*/
private $is_active;
protected $id;
private $name;
protected $username;
protected $email;
/**
* #var tinyint $type
*/
private $type;
protected $password;
private $description;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return User
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set type
*
* #param integer $type
* #return User
*/
public function setType($type)
{
$this->type = $type;
return $this;
}
/**
* Get type
*
* #return integer
*/
public function getType()
{
return $this->type;
}
/**
* Set description
*
* #param string $description
* #return User
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set username
*
* #param string $username
* #return User
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* Get username
*
* #return string
*/
public function getUsername()
{
return $this->username;
}
/**
* Set password
*
* #param string $password
* #return User
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Get password
*
* #return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Set email
*
* #param string $email
* #return User
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
public function isPasswordName()
{
return ($this->name != $this->password);
}
public function isPassUsername()
{
return ($this->password != $this->username);
}
/**
* #var \DateTime $date
*/
private $date;
/**
* Set date
*
* #param \DateTime $date
* #return User
*/
public function setDate($date)
{
$this->date = $date;
return $this;
}
/**
* Get date
*
* #return \DateTime
*/
public function getDate()
{
return $this->date;
}
private $updateDate;
/**
* Set updateDate
*
* #param \DateTime $updateDate
* #return User
*/
public function setUpdateDate($updateDate)
{
$this->updateDate = $updateDate;
return $this;
}
/**
* Get updateDate
*
* #return \DateTime
*/
public function getUpdateDate()
{
return $this->updateDate;
}
public function setIsActive($value)
{
$this->is_active = $value;
return $this;
}
public function gettIsActive()
{
return $this->is_active;
return $this;
}
/**
* Set salt
*
* #param string $salt
* #return User
*/
public function setSalt($salt)
{
$this->salt = $salt;
return $this;
}
/**
* Get salt
*
* #return string
*/
public function getSalt()
{
return $this->salt;
}
/**
* #inheritDoc
*/
public function eraseCredentials()
{
}
public function __construct()
{
parent::__construct();
$this->isActive = true;
$this->salt = md5(uniqid(null, true));
}
public function getRoles()
{
switch ($this->getType())
{
case 0:
return array('ROLE_ADMIN');
break;
case 1:
case 2:
case 3:
return array('ROLE_USER');
break;
}
}
/**
* #see \Serializable::serialize()
*/
public function serialize()
{
return serialize(array(
$this->id,
));
}
/**
* #see \Serializable::unserialize()
*/
public function unserialize($serialized)
{
list (
$this->id,
) = unserialize($serialized);
}
/**
* #var integer $first_login
*/
private $first_login;
/**
* Get is_active
*
* #return boolean
*/
public function getIsActive()
{
return $this->is_active;
}
/**
* Set first_login
*
* #param integer $firstLogin
* #return User
*/
public function setFirstLogin($firstLogin)
{
$this->first_login = $firstLogin;
return $this;
}
/**
* Get first_login
*
* #return integer
*/
public function getFirstLogin()
{
return $this->first_login;
}
/**
* #var \Doctrine\Common\Collections\ArrayCollection
*/
private $userPoints;
/**
* #var integer $privacy
*/
private $privacy;
/**
* Set privacy
*
* #param integer $privacy
* #return User
*/
public function setPrivacy($privacy)
{
$this->privacy = $privacy;
return $this;
}
/**
* Get privacy
*
* #return integer
*/
public function getPrivacy()
{
return $this->privacy;
}
/**
* #var integer
*/
private $enable;
/**
* Set enable
*
* #param integer $enable
* #return User
*/
public function setEnable($enable)
{
$this->enable = $enable;
return $this;
}
/**
* Get enable
*
* #return integer
*/
public function getEnable()
{
return $this->enable;
}
}
My security.yml
security:
firewalls:
main:
pattern: ^/
form_login:
provider: fos_userbundle
login_path: /login
use_forward: false
check_path: /login_check
csrf_provider: form.csrf_provider
logout: true
anonymous: true
providers:
fos_userbundle:
id: fos_user.user_provider.username
encoders:
FOS\UserBundle\Model\UserInterface: sha512
role_hierarchy:
ROLE_ADMIN: ROLE_USER
ROLE_SUPER_ADMIN: ROLE_ADMIN
access_control:
- { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/admin/, role: ROLE_ADMIN }
It seems your version of the FOSUserBundle is not good ... I had the same problem with a 1.3.* that I solved just changing this to version "~2.0#dev".
You can check this looking at your "fos_user" table ; if it just contains a single "id" field, your User entity is not extending the right "FOS\Entity\User" object ... try to upgrade your required version of the bundle in your "composer.json" and then rebuild your tables (below a full HARD rebuild - data are lost):
php app/console doctrine:schema:drop --force
php app/console doctrine:schema:create
If your "fos_user" table have all required fields, then you're good.
Review the docs on creating a use class: https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Resources/doc/index.md
Your User class should not be repeating all the properties (username etc) from the base class. It should only have the new properties like name and id.
And while you didn't show your doctrine mapping file, I'm guessing your probably duplicated everything in there is well? Only map the new properties.
In fact, i guess, you should have some piece of code on config.yml as
fos_user:
db_driver: orm # other valid values are 'mongodb', 'couchdb' and 'propel'
firewall_name: main
user_class: Acme\ProjectBundle\Entity\User
and you should have no need to add sth. to orm settings for FOSUser.
orm:
auto_generate_proxy_classes: "%kernel.debug%"
#auto_mapping: true
default_entity_manager: default
entity_managers:
default:
// that's for APCu or APC
metadata_cache_driver: apc
result_cache_driver: apc
query_cache_driver: apc
in dev env APC disabled, that's why you get this error. You have to comment it for dev or enable cacheClassLoader
I had this trouble and applied PieroWbmstr's suggestion, and started using 2.0 instead of 1.3.6... with doctrine.orm.auto_mapping set to true in config.yml
Once I made the composer.json version switch and upgraded, my doctrine:schema:update instantly recognised the new fields as missing in the current database instance, and applied them.
The newer version of the user class within FOS/UserBundle doesn't seem to have any significant changes that would force the mapping to play nicely. Does anyone have an idea as to what the difference is in these two versions? Or more directly, why the older version somehow didn't let doctrine recognise it's xml mappings (hint: in both of my FOS/UserBundle versions, I had my local custom bundles set to use annotations).
Thanks

Resources