Authentitcation identifies a user, and authorization controls what a user can do. The most famous gem used for authorization in rails is CanCan, which is developed by Ryan Bates. However, this gem was no longer maintained. CanCanCan and Pundit are alternative gems we could use. Here I choosed Pundit.
First, implement user roles. Define roles in User Model by using enum and add a new column to user table.
enum role: [:guest, :vip, :admin]
rails g migration AddRoleToUsers role:integer
Set the default user as guest. We could assign roles like user1.admin! and question the roles like user1.admin?
gem "pundit" into Gemfile and run bundle install.
rails g pundit:install to generate a default policy in app/policies/application_policy.rb
Then create own policy, for example, a Post Policy.
So if current user is not the author of this post or admin, then he is not allowed to update or destroy the post.
After that, add
autorize @post to update and destroy action in Post Controller.
In Post show page, if current user do not have the permission, he will not see the edit and delete button.
Finally, add following code to Application Controller, so that we include Pundit and show the customized alert.
Sometimes current_user are not defined, for example a guest user who is not signed in. Then the above authorization may raise a
undefined method 'admin?' for nil:NilClass problem, which I met. The solution would be changing