Reputation: 1638
I'm building a web application using symfony2. I have different types of users with different roles; ROLE_STUDENT and ROLE_TEACHER, those two user can access a course's details; if the user is a teacher, a button edit is shown and if it's the student then a button subscribe will be shown, and actually this is not secure because it just hides the path to the controllers action, if the student types in the address bar /course/2/edit the edit action would be executed so I had to secure the action using @security annotation:
This is what I have done so far:
/**
* @Security("has_role('ROLE_TEACHER')")
*/ public function editAction()
{}
and in twig :
{% if is_granted('ROLE_TEACHER') %}
<a href="{{path('edit', {'id': course.id})}}">edit</a>
{% elseif is_granted('ROLE_STUDENT')%}
<a href="{{path('subscribe', {'id': course.id})}}">subscribe</a>
.
The problem is that I have a lot of accessible content to both users and I think there is a better solution to this instead of copy/past the same code all over. I'm new to Symfony 2, please bear with me.
Upvotes: 0
Views: 34
Reputation: 3356
There are multiple ways to achieve this but what you are doing is not wrong.
One way to achieve this is to set ROLE
for the ROUTES
so that ROLE_STUDENT roles can only access URLs that will be something like this website.com/students
and ROLE_TEACHER can only access website.com/teachers
access_control:
- { path: ^/student/, roles: ROLE_STUDENT }
- { path: ^/teamleader/, roles: ROLE_TEACHER }
You can then set the edit route only for teachers like website.com/teachers/course/2/edit
this way no edit route is going to be available for ROLE_STUDENT
and they will get 404 error or access denied error if they try to access teacher route. You can do the same for the subscribe feature.
Like I said there are more ways to achieve this and this is one of them.
Upvotes: 1