Ruby on Rails development from scratch (Windows) (17)-Control access rights

Source: Internet
Author: User
Tags ruby on rails

Last we achieved the login page, now we distinguish between the administrator and ordinary users, according to the user's different identities, into different pages

Filter is provided in rails to intercept requests to access an action, and you can use filter to add our own processing before or after the action is invoked. Here, we add interceptors before the action in Admin's controller is invoked. If it is an administrator, enter the admin page, if it is a normal user, enter the login page.

1. Add the authorize method to the Applicationcontroller class in the APPLICATION.RB code as follows:

def authorize
unless session[:user_id]
flash[:notice] = "Please log in"
redirect_to (: Controller => " Login ",: Action =>" login ")
end

Then add a line of code in the Admin.rb file where the Admincontroller class starts:

Class Admincontroller < Applicationcontroller
before_filter:authorize
...

In this way, we add an interceptor, and now the authorize method is invoked before all the action in Admincontroller is invoked.

We also need to modify the Login_controller.rb file to add a code to the Logincontroller:

Class Logincontroller < Applicationcontroller
before_filter:authorize,: except =>: Login
...

2. Now, if we directly access the http://localhost:3003/admin/ship, we will directly navigate to the login page, and prompted to log in first. As shown in figure:

If you have already logged in before, because the session still exists, so will not see the effect, as long as the browser is turned off before repositioning the Admin/ship page can be.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.