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.