Authentication and Authorization

Authentication and authorization are two important part of almost any modern web application. Although I already added authentication but this week I added full authorization also, so only administrator can access and modify users, settings and home page.

In Ruby on Rails either you can build authentication and authorization from scratch or you can use powerful gems and customize them according to your need. For this application I used Devise for authentication and Pundit for authorization. Pundit is a very powerful and popular ruby gem for authorization and you can control access to resources as you want.

To add authorization with Pundit you have to first added it to your gem files and install it by running

bundle install

after installation run

rails g pundit:install

This will generate a policy folder under app, and inside that folder an application_policy ruby class, you can either customize application_policy or build your own custom policy. For this application I created custom polices to restrict access to users, settings and home pages. below is the code that I write to control settings page

class SettingPolicy
	attr_reader :current_user, :model

	def initialize(current_user, model)
		@current_user = current_user
		@setting = model
	end

	def edit?
		@current_user.try(:admin?)
	end
end

for any other controller also you can write your own policy just change class name and what action you want to control. For example if you want to restrict access to posts index page you have to write your policy as follow:

class PostPolicy
	attr_reader :current_user, :model

	def initialize(current_user, model)
		@current_user = current_user
		@post= model
	end

	def index?
		@current_user.try(:admin?)
	end
end

and then in post controller under index method write

authorize Post

Last week I also added nested forms and for that I used a popular gem called cocoon which allows you to add as many custom content as you want. It can be image, video, text, …

I linked cocoon to pages controller so if you use the application you can add as much images and custom content to every page as you want and they are all dynamic, means you can easily add and remove them without knowing how it works.

apart from authorization and nested fields I also worked a little bit on frontend of the application so home page and most of the links are working now and the application almost done and ready for use.

below images are some of the works that I did last week

Leave a Reply

Your email address will not be published.

Wordpress Social Share Plugin powered by Ultimatelysocial