Search code examples
symfonyyamlfosuserbundle

Logging by Username or Email when using two entities with FOSUserBundle


I am using FOSUSerBundle with two different Entities for different Users like DefaultUser and AdminUser

Therefore I have the following in security.yaml

    providers:
    user:
        entity:
            class: AppBundle:User
            property: 'email'
    admin:
        entity:
            class: AppBundle:Admin
            property: 'email'

and firewall is set like this:

 admin:
            pattern: ^/admin
            anonymous: ~
            provider: admin
            form_login:
                login_path: /admin/login
                csrf_token_generator: security.csrf.token_manager
                default_target_path: /admin
                check_path: admin_login_check
            logout_on_user_change: true
            logout:
                path: /admin/logout
                target: /admin
                invalidate_session: false
            access_denied_handler: AppBundle\Security\AccessDeniedHandler
            context: application

        main:
            pattern: ^/
            provider: user
            logout_on_user_change: true

            form_login:
#                csrf_token_generatlor: security.csrf.token_manager
                login_path: /login
                default_target_path: /user
                check_path: fos_user_security_check
            logout:
                  path:           user_logout
                  target:         user_login
                  invalidate_session: false

            context:         application
            anonymous:    ~
            access_denied_handler: AppBundle\Security\AccessDeniedHandler

How to get FOSUserBundle work, so I can use username or Email ?

Normally it is set by

id: fos_user.user_provider.username_email

but this cannot used in this configuration.


Solution

  • It's been a long time since I worked with the fos_userbundle, but from what I see in my code, you'll need to update your security.yml file to make use of it:

    security:
        providers:
            fos_userbundle_admin: appbundle.service.providing.admin_user
    

    And in that service (which extends FOS\UserBundle\Security\UserProvider), you'll want to override the findUser($username) method. There, you can use the provided username.

    I suppose (untested) you can create another provider (fos_userbundle_user) and use that one for users in your firewall.

    Hopefully this makes sense.. It's working here, but that was in a symfony 2.8 app. FOS_UserBundle has changed a fair bit since then.