简体   繁体   中英

Symfony2 Authentication system logical issue

I'm trying to write a authorization system combining with the Symfony itself. My logic is like this:

  1. there is a User table who holds the system users.
  2. there is a Role table who take care of roles.
  3. there is a Permission table who keeps the Each part of websites' permission.
  4. there is a User_Role table which tells us which user is is which Role.
  5. there is a Role_Permission table which define Each Role's permission.

I have created the tables in the database and their relationships. and imported them to Symfony ( created entity ).

and now the problem is:

/**
* @inheritDoc
*/
public function getRoles()
{
    return array('ROLE_TEST');
}

How can I load each user's roles in the roles array?

public function getRoles()
{
    $roles = array();
    // Checking that the user has permissions attached
    if ($this->getPermissions() !== null)
    {
        // Looping on the permissions
        foreach($this->getPermissions() as $permission)
        {
            // Checking that the permission has roles attached
            if ($permission->getRoles() !== null)
            {
                // Looping on the roles for each permission
                foreach($permission->getRoles() as $role)
                {
                    $roles[] = $role->getName();
                }
            }
        }
    }
    return $roles;
}

Better solution is to create a UserManager Service and to get the roles via the Doctrine Query Builder (Less calls to the database):

/** @var EntityManager $this->em */
$roles = $this->em->createQueryBuilder()
    ->select('r')
    ->from('AcmeBundle:Role', 'r')
    ->innerJoin('r.permissions', 'p')
    ->innerJoin('p.users', 'u')
    ->where('u = :user')
    ->setParameter(':user', $user)
    ->getQuery()
    ->getResult()
;

Thanks to Guillaume Verbal, I found another solution for that. I made a view which just return User id and roles of the users ( make 4 tables one by view ) and finally make a logical relationship between user and user_role(view) tables. everything just work fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM