0
votes

I understand Symfony2 brings the ability to configure users in-memory like that:

 providers:
    in_memory:
        memory:
            users:
                user1:  { password: pwd1, roles: [ 'ROLE_USER' ] }
                user2:  { password: pwd2, roles: [ 'ROLE_USER' ] }
                user3:  { password: pwd3, roles: [ 'ROLE_USER' ] }
                admin: { password: adminpass, roles: [ 'ROLE_ADMIN' ] }

I'm building small site and there will be photos galleries only accessible to authentified users. One gallery will match this route: http://mysite/clients/client-name

From Symfony documentation I can see we can restrict routes to specific roles. But that's not what I want because all my users (clients) will have the role ROLE_USER. What I want is to restrict each /clients/client-nameroute to a specific user. So for instance user1 would have access to/clients/john-smyth`

How do I do that ?

using access_control parameter, how do I replace roles by users ?

access_control:
    - { path: ^/clients/john-smyth, roles: ROLE_USER }
1
i dont think you can to that in the security.yml. Simple test in your controller the username ($this->getUser();) and if it is not correct redirect him to an error pageTuxes3

1 Answers

1
votes

You could write a Voter which matches a certain route or path against the username.

Here's a very basic example (I hacked together without testing, so it might need some debugging) to get you going:

class GalleryAccessVoter implements VoterInterface
{
    ...

    public function vote(TokenInterface $token, $object, array $attributes)
    {
        $request = $this->container->get('request');
        $route = $request->get('_route');
        $user = $token->getUser();

        if ($route == 'acme_gallery_show' && null !== $user) {
            $galleryId = $request->request->get('id');
            if ($galleryId == $user->getUsername()) {
                return VoterInterface::ACCESS_GRANTED;
            }
        }

        return VoterInterface::ACCESS_DENIED;
    }