I am really getting nervous because of lacking of enough resource for installing SonataDoctrineMongoDBAdminBundle and it's dependencies like sonataUserBundle. I have been trying to install this bundle for 15 days. I did everyting agaian and again what telling in sonata's official page. But it does not work properly. After extending sonataUserBundle as ApplicationUserBundle my final documents are:
User.php
<?php
/**
* This file is part of the <name> project.
*
* (c) <yourname> <youremail>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Application\Sonata\UserBundle\Document;
use Sonata\UserBundle\Document\BaseUser as BaseUser;
/**
* This file has been generated by the EasyExtends bundle ( http://sonata-project.org/bundles/easy-extends )
*
* References :
* working with object : http://www.doctrine-project.org/docs/mongodb_odm/1.0/en/reference/working-with-objects.html
*
* #author <yourname> <youremail>
*/
class User extends BaseUser
{
/**
* #var integer $id
*/
protected $id;
/**
* Get id
*
* #return integer $id
*/
public function getId()
{
return $this->id;
}
}
Group.php
<?php
/**
* This file is part of the <name> project.
*
* (c) <yourname> <youremail>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Application\Sonata\UserBundle\Document;
use Sonata\UserBundle\Document\BaseGroup as BaseGroup;
/**
* This file has been generated by the EasyExtends bundle ( http://sonata-project.org/bundles/easy-extends )
*
* References :
* working with object : http://www.doctrine-project.org/docs/mongodb_odm/1.0/en/reference/working-with-objects.html
*
* #author <yourname> <youremail>
*/
class Group extends BaseGroup
{
/**
* #var integer $id
*/
protected $id;
/**
* Get id
*
* #return integer $id
*/
public function getId()
{
return $this->id;
}
}
config.yml
imports:
- { resource: parameters.yml }
- { resource: security.yml }
framework:
#esi: ~
translator: { fallback: %locale% }
secret: %secret%
router:
resource: "%kernel.root_dir%/config/routing.yml"
strict_requirements: %kernel.debug%
form: ~
csrf_protection: ~
validation: { enable_annotations: true }
templating:
engines: ['twig']
#assets_version: SomeVersionScheme
default_locale: "%locale%"
trusted_proxies: ~
session: ~
fragments: ~
# Twig Configuration
twig:
debug: %kernel.debug%
strict_variables: %kernel.debug%
# Assetic Configuration
assetic:
debug: %kernel.debug%
use_controller: false
bundles: [ ]
#java: /usr/bin/java
filters:
cssrewrite: ~
#closure:
# jar: %kernel.root_dir%/Resources/java/compiler.jar
#yui_css:
# jar: %kernel.root_dir%/Resources/java/yuicompressor-2.4.7.jar
# Swiftmailer Configuration
swiftmailer:
transport: %mailer_transport%
host: %mailer_host%
username: %mailer_user%
password: %mailer_password%
spool: { type: memory }
doctrine_mongodb:
connections:
default:
server: mongodb://localhost:27017
options: {}
default_database: test_database
document_managers:
default:
auto_mapping: true
# app/config/config.yml
sonata_block:
default_contexts: [cms]
blocks:
sonata.admin.block.admin_list:
contexts: [admin]
#sonata.admin_doctrine_orm.block.audit:
# contexts: [admin]
sonata.block.service.text:
sonata.block.service.rss:
# Some specific block from the SonataMediaBundle
#sonata.media.block.media:
#sonata.media.block.gallery:
#sonata.media.block.feature_media:
sonata_user:
security_acl: false
manager_type: mongodb # can be orm or mongodb
sonata_admin:
security:
handler: sonata.admin.security.handler.role
title: Sonatas Project
title_logo: /bundles/sonataadmin/logo_title.png
templates:
# default global templates
layout: SonataAdminBundle::standard_layout.html.twig
ajax: SonataAdminBundle::ajax_layout.html.twig
dashboard: SonataAdminBundle:Core:dashboard.html.twig
# default actions templates, should extend a global templates
list: SonataAdminBundle:CRUD:list.html.twig
show: SonataAdminBundle:CRUD:show.html.twig
edit: SonataAdminBundle:CRUD:edit.html.twig
dashboard:
blocks:
# display a dashboard block
- { position: left, type: sonata.admin.block.admin_list }
# Customize this part to add new block configuration
- { position: right, type: sonata.block.service.text, settings: { content: "<h2>Welcome to the Sonata Admin</h2> <p>This is a <code>sonata.block.service.text</code> from the Block Bundle, you can create and add new block in these area by configuring the <code>sonata_admin</code> section.</p> <br /> For instance, here a RSS feed parser (<code>sonata.block.service.rss</code>):"} }
- { position: right, type: sonata.block.service.rss, settings: { title: Sonata Project's Feeds, url: http://sonata-project.org/blog/archive.rss }}
# set to true to persist filter settings per admin module in the user's session
fos_user:
db_driver: mongodb # can be orm or odm
firewall_name: main
user_class: Application\Sonata\UserBundle\Document\User
group:
group_class: Application\Sonata\UserBundle\Document\Group
security.yml
jms_security_extra:
secure_all_services: false
expressions: true
security:
encoders:
FOS\UserBundle\Model\UserInterface: sha512
role_hierarchy:
ROLE_ADMIN: [ROLE_USER, ROLE_SONATA_ADMIN]
ROLE_SUPER_ADMIN: [ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]
SONATA:
- ROLE_SONATA_PAGE_ADMIN_PAGE_EDIT # if you are using acl then this line must be commented
providers:
fos_userbundle:
id: fos_user.user_manager
firewalls:
# -> custom firewall for the admin area of the URL
admin:
switch_user: true
context: user
pattern: /admin(.*)
form_login:
provider: fos_userbundle
login_path: /admin/login
use_forward: false
check_path: /admin/login_check
failure_path: null
use_referer: true
logout:
path: /admin/logout
target: /admin/login
anonymous: true
# -> end custom configuration
# defaut login area for standard users
main:
switch_user: true
context: user
pattern: .*
form_login:
provider: fos_userbundle
login_path: /login
use_forward: false
check_path: /login_check
failure_path: null
logout: true
anonymous: true
access_control:
# URL of FOSUserBundle which need to be available to anonymous users
- { path: ^/_wdt, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/_profiler, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
# -> custom access control for the admin area of the URL
- { path: ^/admin/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/admin/logout$, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/admin/login-check$, role: IS_AUTHENTICATED_ANONYMOUSLY }
# -> end
- { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
# Secured part of the site
# This config requires being logged for the whole site and having the admin role for the admin part.
# Change these rules to adapt them to your needs
- { path: ^/admin, role: [ROLE_ADMIN, ROLE_SONATA_ADMIN] }
- { path: ^/.*, role: IS_AUTHENTICATED_ANONYMOUSLY }
After all I run:
php app/console fos:user:create --super-admin
The task tells me the user created succesfully. Then I check my mongodb and there is only a record with 3 fields.
Here is the output:
> db.fos_user_user.findOne();
{
"_id" : 1,
"createdAt" : ISODate("2013-05-25T19:43:52Z"),
"updatedAt" : ISODate("2013-05-25T19:43:52Z"),
"gender" : "u"
}
As you see there is no a username or password or another field which pointed in sonata's or fos' document files. I installed SonataDoctrineORMAdminBundle to look if there is any problem with SonataAdminBundle but it works like a charm with mysql.
I am getting so crazy. Please tell me, what is the correct way to install sonataAdminBundle with mongoDB?
Thank you for your interest.
Seems that inheritance mapping is not working right, I followed the instructions but it lead to same problem. I got it fixed by changing reference to BaseUser to class provided by FOS\UserBundle
# Application\Sonata\UserBundle\Document\User.php
namespace Application\Sonata\UserBundle\Document;
//use Sonata\UserBundle\Document\BaseUser as BaseUser;
use FOS\UserBundle\Document\User as BaseUser;
I was also having issues with this, the users were created with just an ID, gender: 'u', createdAt, etc. And with this, I was able to make it work:
# app/config/config.yml
doctrine_mongodb:
connections:
default:
server: mongodb://localhost:27017
options: {}
default_database: test
document_managers:
default:
mappings:
ApplicationSonataUserBundle: ~
SonataUserBundle: ~
FOSUserBundle: ~
I hope someone find this useful.
I'm stucked at the same point.
I created user.php in a different folder with a different name, for my organization.
The difference was that I put direcly mongodb annotations
namespace myProject\BackEndBundle\Document;
use FOS\UserBundle\Document\User as BaseUser;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
/**
* #MongoDB\Document
*/
class BackEndUser extends BaseUser {
/**
* #MongoDB\Id
*/
protected $id;
/**
* Get id
*
* #return id $id
*/
public function getId()
{
return $this->id;
}
public function __construct()
{
parent::__construct();
// your own logic
}
}
Now user creation and authentication works, but user management in SonataAdminBundle don't works.
Related
I followed this two post about "how to install fosuserbundle in symfony 4.4":
https://vfac.fr/blog/how-install-fosuserbundle-with-symfony-4
https://ourcodeworld.com/articles/read/794/how-to-install-and-configure-fosuserbundle-in-symfony-4
But at the end i got this error:
Argument 3 passed to FOS\UserBundle\Doctrine\UserManager::__construct() must be an instance of Doctrine\Common\Persistence\ObjectManager, instance of Doctrine\ORM\EntityManager
given, called in /url/to/symfony/proyect/var/cache/dev/ContainerKx7xY28/srcApp_KernelDevDebugContainer.php on line 1466
i didn't change anything about FOSUserBundle but it's seems that something is wrong in my configuration...
My config files are these:
security.yaml
security:
encoders:
FOS\UserBundle\Model\UserInterface: bcrypt
role_hierarchy:
ROLE_ADMIN: ROLE_USER
ROLE_SUPER_ADMIN: ROLE_ADMIN
# https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
providers:
#users_in_memory: { memory: null }
fos_userbundle:
id: fos_user.user_provider.username
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
#anonymous: lazy
#provider: users_in_memory
pattern: ^/
form_login:
provider: fos_userbundle
csrf_token_generator: security.csrf.token_manager
logout: true
anonymous: true
# 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: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/admin/, role: ROLE_ADMIN }
packages/fos_user.yaml
# config/packages/fos_user.yaml
fos_user:
db_driver: orm # other valid values are 'mongodb' and 'couchdb'
firewall_name: main
user_class: App\Entity\User
from_email:
address: "email#email.com"
sender_name: "email#email.com"
src/Entity/User.php
<?php
// src/Entity/User.php
namespace App\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="fos_user")
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
public function __construct()
{
parent::__construct();
// your own logic
}
}
EDIT: I just tried the same guide with symfony 4.3 and it's work! so i think is something about compability of symfony 4.4 and FOSUserBundle...
This is not a problem related to the fos user bundle, but with your declaration of user.
Read this post first.
See your User declaration :
<?php
// src/Entity/User.php
namespace App\Entity;
use Doctrine\Common\Persistence\ObjectManager; <---
Try replace it with
use Doctrine\ORM\EntityManagerInterface; <---
You may have somewhere in your code where you use an entity object which is declared with ObjectManager instead of EntityManagerInterface.
Please if this is not working explain why you add this line :
// AƱadimos esta linea porque parece que hacer algo...
use Doctrine\Common\Persistence\ObjectManager;
EDIT
Ok I've been looking for it, and that's look like a bug with doctrine.
I found this issue : https://github.com/doctrine/orm/issues/8242.
It solve your problem.
Just update your composer.json like :
...
"require": {
"php": ">=7.1.3",
"ext-ctype": "*",
"ext-iconv": "*",
"composer/package-versions-deprecated": "^1.11",
"doctrine/annotations": "^1.0",
"doctrine/doctrine-bundle": "^2.1",
"doctrine/doctrine-migrations-bundle": "^3.0",
"doctrine/orm": "^2.7",
"doctrine/common":"^2.13", <------
...
I found a lot on internet finding the best solution and there was not one solved my problem, so I saw the services that uses the bundle and see that fos_user.user_manager.default: service is the one who call the Doctrine\Modle\UserManager so I rewrite it with my own class
fos_user.user_manager.default:
class: App\Model\UserManager
arguments:
- '#fos_user.util.password_updater'
- '#fos_user.util.canonical_fields_updater'
- '#doctrine.orm.entity_manager'
- '%fos_user.model.user.class%'
Create your own class to manage your fosUser entity, it has to extends of FOS\UserBundle\Model\UserManager (can copy the code of the same class)
Rewrite the service injecting the same parameters, except the third parameter, it will be replaced by EntityManagerInterface
I hope that will help you, It worked for me.
I have a problem with getting the logged in user in and Admin class. What I would like to do is to restrict a choice field to logged in users organization (so that he is not able to pick another organization when creating an event). Therefore I've injected TokenStorage into my CalendarAdmin, but $tokenStorage->getToken() is null even if I'm logged in.
Here is my relevant code:
security.yml:
providers:
in_memory:
memory: ~
fos_userbundle:
id: fos_user.user_manager
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
logout:
path: /admin/logout
anonymous: true
services.yml:
pozsonyba.calendar_bundle.admin.calendar:
class: Pozsonyba\Bundle\CalendarBundle\Admin\CalendarAdmin
arguments: [~, Pozsonyba\Bundle\CalendarBundle\Entity\Calendar, SonataAdminBundle:CRUD, #security.token_storage, #pozsonyba_organization.repository.organization_repository]
tags:
- {name: sonata.admin, manager_type: orm, group: admin, label: Calendar}
I read that this security.yml might have been set up wrong, that the firewall is missing something, I just can't figure out what.
Thank you for help.
CalendarAdmin.php:
public function __construct($code, $class, $baseControllerName, TokenStorage $tokenStorage, OrganizationRepository $organizationRepository)
{
parent::__construct($code, $class, $baseControllerName);
VarDumper::dump($tokenStorage->getToken());die;
$this->organizationRepository = $organizationRepository;
}
Check out the \Sonata\AdminBundle\Admin\AbstractAdmin class. You can get access to the container and the token storage via the configuration pool:
$this->getConfigurationPool()->getContainer()->get('security.token_storage')->getToken()->getUser()
I guess, the token is not set when the admin object is created, so as an alternative way you can try to inject the TokenStorage via setter injection:
# CalendarAdmin.php
/** #var TokenStorageInterface */
private $tokenStorage;
/**
* #param TokenStorageInterface $tokenStorage
*/
public function setTokenStorage($tokenStorage)
{
$this->tokenStorage = $tokenStorage;
}
update services definition
# services.yml
pozsonyba.calendar_bundle.admin.calendar:
class: Pozsonyba\Bundle\CalendarBundle\Admin\CalendarAdmin
arguments: [~, Pozsonyba\Bundle\CalendarBundle\Entity\Calendar, SonataAdminBundle:CRUD, #security.token_storage, #pozsonyba_organization.repository.organization_repository]
calls:
- [setTokenStorage, ["#security.token_storage"]]
tags:
- {name: sonata.admin, manager_type: orm, group: admin, label: Calendar}
Recently, I started working with Symfony2. Now I want to add a user management engine to my site.
But I'm facing a problem. This is what I'm doing:
In terms of creating/installing a basic Symfony2 project:
$ composer create-project symfony/framework-standard-edition path/ "2.5.*"
$ mv path/* ./
$ rm -r path/
Ok, so much for Symfony 2.5.5. Next, download the FOSUserBundle and create a custom bundle:
$ composer require friendsofsymfony/user-bundle '~2.0#dev'
$ php app/console generate:bundle --namespace=Meiblorn/CoreBundle --format=yml
Create the User class in the Meiblorn\CoreBundle\Framework\Domain namespace
/**
* User: Meiblorn
* Date: 15/10/14
* Time: 20:17
*/
namespace Meiblorn\CoreBundle\Framework\Domain;
use FOS\UserBundle\Model\User as FOSUserBundleUser;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(
* name = "users"
* )
*/
class User extends FOSUserBundleUser {
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
public function __construct() {
parent::__construct();
// your own logic
}
}
?>
Configure the security.yml and config.yml. Finally, I got this:
AppKernel.php
$bundles = array(
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
new Symfony\Bundle\MonologBundle\MonologBundle(),
new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
new Symfony\Bundle\AsseticBundle\AsseticBundle(),
new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
new FOS\UserBundle\FOSUserBundle(),
new Meiblorn\CoreBundle\MeiblornCoreBundle(),
);
config.yml
imports:
- { resource: parameters.yml }
- { resource: security.yml }
framework:
#esi: ~
translator: { fallback: "%locale%" }
secret: "%secret%"
router:
resource: "%kernel.root_dir%/config/routing.yml"
strict_requirements: ~
form: ~
csrf_protection: ~
validation: { enable_annotations: true }
templating:
engines: ['twig']
#assets_version: SomeVersionScheme
default_locale: "%locale%"
trusted_hosts: ~
trusted_proxies: ~
session:
# handler_id set to null will use default session handler from php.ini
handler_id: ~
fragments: ~
http_method_override: true
# Twig Configuration
twig:
debug: "%kernel.debug%"
strict_variables: "%kernel.debug%"
# Assetic Configuration
assetic:
debug: "%kernel.debug%"
use_controller: false
bundles: [ ]
#java: /usr/bin/java
filters:
cssrewrite: ~
#closure:
# jar: "%kernel.root_dir%/Resources/java/compiler.jar"
#yui_css:
# jar: "%kernel.root_dir%/Resources/java/yuicompressor-2.4.7.jar"
# Doctrine Configuration
doctrine:
dbal:
driver: "%database_driver%"
host: "%database_host%"
port: "%database_port%"
dbname: "%database_name%"
user: "%database_user%"
password: "%database_password%"
charset: UTF8
orm:
auto_generate_proxy_classes: "%kernel.debug%"
auto_mapping: true
# Swiftmailer Configuration
swiftmailer:
transport: "%mailer_transport%"
host: "%mailer_host%"
username: "%mailer_user%"
password: "%mailer_password%"
spool: { type: memory }
fos_user:
db_driver: orm
firewall_name: prod
user_class: Meiblorn\CoreBundle\Framework\Domain\User
security.yml
security:
encoders:
FOS\UserBundle\Model\UserInterface: sha512
role_hierarchy:
ROLE_ADMIN: ROLE_USER
ROLE_SUPER_ADMIN: ROLE_ADMIN
providers:
fos_userbundle:
id: fos_user.user_provider.username
firewalls:
prod:
pattern: ^/
form_login:
provider: fos_userbundle
csrf_provider: form.csrf_provider
logout: true
anonymous: true
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
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 }
THIS IS THE PROBLEM
In browser: http://localhost/test.meiblorn.com/web/app_dev.php/
MappingException: The class 'Meiblorn\CoreBundle\Framework\Domain\User' was not found in the chain configured namespaces FOS\UserBundle\Model
in /Library/WebServer/Documents/test.meiblorn.com/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/MappingException.php line 37
at MappingException::classNotFoundInNamespaces('Meiblorn\CoreBundle\Framework\Domain\User', array('FOS\UserBundle\Model')) in /Library/WebServer/Documents/test.meiblorn.com/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/Driver/MappingDriverChain.php line 113
at MappingDriverChain->loadMetadataForClass('Meiblorn\CoreBundle\Framework\Domain\User', object(ClassMetadata)) in /Library/WebServer/Documents/test.meiblorn.com/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php line 117
at ClassMetadataFactory->doLoadMetadata(object(ClassMetadata), object(ClassMetadata), false, array()) in /Library/WebServer/Documents/test.meiblorn.com/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/AbstractClassMetadataFactory.php line 318
Also Doctrine doesn't create tables for this mapping when calling doctrine:schema:update
Please, help me to fix this exception
UPDATE! How to fix
Final configuration for my namespace
orm:
auto_generate_proxy_classes: "%kernel.debug%"
auto_mapping: false
mappings:
FOSUserBundle: ~
MeiblornCoreBundle:
type: annotation
dir: %kernel.root_dir%/../src/Meiblorn/CoreBundle/Framework/Entity
prefix: Meiblorn\CoreBundle\Framework\Entity
# alias: MyModels
# is_bundle: true
First you need to configure psr-4 autoload in your composer.js, for example
"autoload": {
"psr-4": {
"Meiblorn\\CoreBundle\\": "src/Meiblorn/CoreBundle/"
}
},
Then call composer dumpautoload.
Secondly, I believe Doctrine expects the entities to live in a folder Entity/, so try to move you model: src/Meiblorn/CoreBundle/Framework/Domain/User.php to src/Meiblorn/CoreBundle/Entity/User.php or How do I change symfony 2 doctrine mapper to use my custom directory instead of my Entity Directory under the bundle
I am trying to implement HWIOAuthBundle with FOSUserBundle for having both standard (login and registration) and OAuth (login and registration).
I don't know how to finalise this.
Here is my config files:
config.yml
imports:
- { resource: parameters.yml }
- { resource: security.yml }
framework:
#esi: ~
translator: { fallback: "%locale%" }
secret: "%secret%"
router:
resource: "%kernel.root_dir%/config/routing.yml"
strict_requirements: ~
form: ~
csrf_protection: ~
validation: { enable_annotations: true }
templating:
engines: ['twig']
#assets_version: SomeVersionScheme
default_locale: "%locale%"
trusted_hosts: ~
trusted_proxies: ~
session:
# handler_id set to null will use default session handler from php.ini
handler_id: ~
fragments: ~
http_method_override: true
# Twig Configuration
twig:
debug: "%kernel.debug%"
strict_variables: "%kernel.debug%"
globals:
title: %app_title%
contact: %app_contact%
# Assetic Configuration
assetic:
debug: "%kernel.debug%"
use_controller: false
bundles: [ ]
#java: /usr/bin/java
filters:
cssrewrite: ~
#closure:
# jar: "%kernel.root_dir%/Resources/java/compiler.jar"
#yui_css:
# jar: "%kernel.root_dir%/Resources/java/yuicompressor-2.4.7.jar"
# Doctrine Configuration
doctrine:
dbal:
driver: "%database_driver%"
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, add the path in parameters.yml
# e.g. database_path: "%kernel.root_dir%/data/data.db3"
# path: "%database_path%"
#config.yml
orm:
auto_generate_proxy_classes: "%kernel.debug%"
auto_mapping: true
# Swiftmailer Configuration
swiftmailer:
transport: "%mailer_transport%"
host: "%mailer_host%"
username: "%mailer_user%"
password: "%mailer_password%"
spool: { type: memory }
fos_user:
db_driver: orm
firewall_name: main
user_class: IService\MyFuckingBundles\UserBundle\Entity\User
registration:
confirmation:
enabled: false #change to true for production use!
hwi_oauth:
# name of the firewall in which this bundle is active, this setting MUST be set
firewall_name: social
connect:
confirmation: false
#account_connector: hwi_oauth.user.provider.fosub_bridge
#registration_form_handler: hwi_oauth.registration.form.handler.fosub_bridge
#registration_form: fos_user.registration.form
resource_owners:
facebook:
type: facebook
client_id: 11111111111111111
client_secret: abcdefg
scope: "email"
options:
display: popup
fosub:
# try 30 times to check if a username is available (foo, foo1, foo2 etc)
username_iterations: 30
# mapping between resource owners (see below) and properties
properties:
facebook: facebookID
security.yml
# app/config/security.yml
jms_security_extra:
secure_all_services: false
expressions: true
security:
encoders:
FOS\UserBundle\Model\UserInterface: sha512
role_hierarchy:
ROLE_ADMIN: ROLE_USER
ROLE_SUPER_ADMIN: ROLE_ADMIN
providers:
fos_userbundle:
id: fos_user.user_provider.username_email
firewalls:
main:
pattern: ^/
form_login:
provider: fos_userbundle
csrf_provider: form.csrf_provider
logout: true
anonymous: true
remember_me:
key: %secret%
social:
pattern: ^/c
oauth:
failure_path: /c/connect
login_path: /c/connect
check_path: /c/connect
provider: fos_userbundle
resource_owners:
facebook: "/c/connect/check-facebook"
oauth_user_provider:
service: hwi_oauth.user.provider.fosub_bridge
anonymous: true
logout: true
access_control:
- { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/c/connect, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/admin/, role: ROLE_ADMIN }
routing.yml
i_service_score_it_page:
resource: "#IServiceMyFuckingBundlesPageBundle/Controller/"
type: annotation
prefix: /
i_service_score_it_user:
resource: "#IServiceMyFuckingBundlesUserBundle/Controller/"
type: annotation
prefix: /
fos_user_security:
resource: "#FOSUserBundle/Resources/config/routing/security.xml"
fos_user_profile:
resource: "#FOSUserBundle/Resources/config/routing/profile.xml"
prefix: /profile
fos_user_register:
resource: "#FOSUserBundle/Resources/config/routing/registration.xml"
prefix: /register
fos_user_resetting:
resource: "#FOSUserBundle/Resources/config/routing/resetting.xml"
prefix: /resetting
fos_user_change_password:
resource: "#FOSUserBundle/Resources/config/routing/change_password.xml"
prefix: /profile
hwi_oauth_redirect:
resource: "#HWIOAuthBundle/Resources/config/routing/redirect.xml"
prefix: /c/connect
hwi_oauth_login:
resource: "#HWIOAuthBundle/Resources/config/routing/login.xml"
prefix: /c/connect
hwi_oauth_connect:
resource: "#HWIOAuthBundle/Resources/config/routing/connect.xml"
prefix: /c/connect
#HERE ADD FACEBOOK, TWITTER AND LINKEDIN SSO
hwi_facebook_login:
pattern: /c/connect/check-facebook
and finally my User.php
<?php
/**
* Users
*
*/
namespace IService\MyFuckingBundles\UserBundle\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="c_user")
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/** #ORM\Column(name="facebook_id", type="string", length=255, nullable=true) */
protected $facebookID;
/** #ORM\Column(name="facebook_access_token", type="string", length=255, nullable=true) */
protected $facebookAcessToken;
/** #ORM\Column(name="google_id", type="string", length=255, nullable=true) */
protected $googleID;
/** #ORM\Column(name="google_access_token", type="string", length=255, nullable=true) */
protected $googleAccessToken;
public function __construct()
{
parent::__construct();
// your own logic
}
public function getId(){
return $this->id;
}
/**
* Get Facebook_id
*/
public function getFacebookID(){
return $this->facebook_id;
}
/**
* set facebook Id
* #return User
*/
public function setFacebookID($facebook_id){
$this->facebook_id = $facebook_id;
return $this;
}
}
When I am trying the authentication with the following steps:
* url -> /c/connect I have the facebook connect link
* Click on it and then accept the facebook login
* Finally returning on the website and I am having this error: No resource owner with name 'check-facebook'
First off you might be disappointed with the registration process. I found it to be quite byzantine and finally gave up. It requires two different redirect urls (one for login and one for connecting) which not all oauth servers support. Facebook and Google do so you should be okay. I don't think twitter support multiple callback or if it does then I could not get it to work.
In any event, I found I had to use named routes for the check login stuff (which is different than the connect stuff)
security.yml
...
oauth:
resource_owners:
facebook: facebook_login_check
google: google_login_check
routing.yml
facebook_login_check:
pattern: /login/check-facebook
google_login_check:
pattern: /login/check-google
I never tracked down why but I think the "%resource_owner%_login_check" is hard coded somewhere and used to match the callback route to a specific resource owner.
In any event, give named routes a shot and see if that get's you passed the error. If it does then I suspect your fun will just be beginning.
============================================================
Update 1
I remember that I also had to add these named routes. Not sure but you could try it.
routing.yml
github_connect:
pattern: /connect/github
google_connect:
pattern: /connect/google
twitter_connect:
pattern: /connect/twitter
I am building a site using Symfony2 and it will be a white-label type of site, where multiple domains map to the same server. So coolsite.customer1.com and aservice.customer2.com would map to the same site, but would need to appear different to the end user. I already solved for the domains, and loading the unique configurations as a service.
With the FOS UserBundle setup and running with a custom user (that has the domain_id stored in it), registration, login, etc works fine except that users from domain1 can login to domain2 also. This is expected in the FOS UserBundle. I need to make modifications to the bundle so that it only will authenticate users on the domain they are assigned to.
I have created a userProvider that extends the original userProvider in FOS and have overridden the loadUserByUsername method to also check the domain. See below:
use FOS\UserBundle\Security\UserProvider as FOSProvider;
use Symfony\Component\DependencyInjection\ContainerInterface;
use FOS\UserBundle\Model\UserManagerInterface;
use Me\CoreBundle\Models\Core;
class UserProvider extends FOSProvider {
/**
*
* #var ContainerInterface
*/
protected $container;
public function __construct(UserManagerInterface $userManager, ContainerInterface $container) {
parent::__construct($userManager);
$this->container = $container;
}
/**
* {#inheritDoc}
*/
public function loadUserByUsername($username)
{
$core = $this->container->get('me_core');
/* #var $core Core */
$user = $this->findUserBy(array(
'username'=>$username,
'domain_id'=>$core->getDomainMap()->getId(),
));
if (!$user) {
throw new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $username));
}
return $user;
}
public function findUserBy(array $criteria) {
return $this->userManager->findUserBy($criteria);
}
}
I have configured the service with the following.
services:
me.security.authentication.userprovider:
class: Me\UserBundle\Security\UserProvider
arguments:
- #fos_user.user_manager
- #service_container
My security.yml looks like this:
security:
providers:
me.security.authentication.userprovider:
id: fos_user.user_provider.username
encoders:
FOS\UserBundle\Model\UserInterface: sha512
firewalls:
main:
pattern: ^/
form_login:
provider: fos_userbundle
csrf_provider: form.csrf_provider
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: ^/_wdt, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/public, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/admin/, role: ROLE_ADMIN }
- { path: ^/, role: ROLE_USER }
role_hierarchy:
ROLE_ADMIN: ROLE_USER
ROLE_SUPER_ADMIN: ROLE_ADMIN
What happens when I try to access the site is an exception. "ServiceNotFoundException: The service "security.authentication.manager" has a dependency on a non-existent service "security.user.provider.concrete.fos_userbundle"."
I based my modifications on This Cookbook Recipe
Any ideas? I am thoroughly stumped on this.
I was able to get it to work. Turns out I needed to make the "id" the same as the name of the service I was using. The commented lines are the originals that came with the bundle.
security:
providers:
me.security.authentication.userprovider:
id: me.security.authentication.userprovider
#fos_userbundle:
#id: fos_user.user_provider.username