11. Implementing Authorisation and Adding Admin Users
My next step is to implement authorisation so that users are only able to edit and delete posts they have created. To achieve this, I will make a post policy (app/Policies/PostPolicy.php), using the following command:
php artisan make:policy PostPolicy --model=Post
This command creates a new policy directory, a policy named PostPolicy and associates it with the post model, using the --model flag.
Two functions require authorisation - the updating and deleting of posts. To add authorisation to these areas of functionality, code has to be inserted within these sections of the post policy. This can be seen in the screen capture below:
These functions will return either true or false, depending on whether or not the current user's id is equal to the user_id foreign key of the post they are currently trying to update or delete.Now the above logic needs to be applied to the post controller in the edit, update and destroy functions through the use of a gate:
abort_unless(Gate::allows('[action]', $post), 403);
This statement will abort the function unless the action is granted according to the post policy. Otherwise, a 403 'not authorised' request status error will be returned.
Edit function in post controller:
To add admin functionality, I first need to add a column to the users table which would signify a role. For this, I will create a new database migration, which will alter the existing users table. The screen capture below shows a 'role' column being added to the users table, after the 'email' column. The default value is null. Admin users will have the role of 'admin'.
Next, I will create an admin seeder (database/seeders/AdminSeeder.php), which will populate the users table with a single admin user. Note that the password will be saved as a hashed version of the word 'admin123' and the role is set as 'admin'.
I can now add an additional function to the post policy (app/Policies/PostPolicy.php). The before() function runs before any other functions in the policy and it checks whether or not a user has the role of 'admin'. If the user does have an admin role, then true is returned - giving this user access to all of the functionality that requires authorisation. This means that admin users can make changes to posts by other users.
For the purposes of my application, I have added a delete button on the post index view (resources/views/posts/index.blade.php). The screen capture below shows an admin user logged in, with a delete button present on every post by every user:
This button will only be shown if a user has the role of admin, as achieved by the code below from the post index file. I used an @if tag, which checks that the current user is both logged in and has an admin role.
Comments
Post a Comment