Noah Clark
Noah Clark

Reputation: 8131

has_secure_password User Authorization

I have followed the Railcast #270 has_secure_password tutorial and have that all working.

For example, I have the following in my header:

<% if current_user %>
  <li><%= link_to "Profile", current_user %></li>
  <li class="last"><%= link_to "Logout", logout_path %></li>
<% else %>
 <li><%= link_to "Login", login_path %></li>
 <li class="last"><%= link_to "Register", signup_path  %></li>
<% end %>

But if a user can guess the path to a particular page then they can view that page if they are logged in or not. What is the easiest way to prevent this and only have authorized users view certain pages? Does rails have something to help built in?

Upvotes: 1

Views: 667

Answers (1)

tbuehlmann
tbuehlmann

Reputation: 9110

You can add a before filter to the controller, which will do exactly what you need. Like:

class ProductController < ActionController::Base
  before_filter :login_required, :only => [:new, :create, :edit, :update]

  # ...

  private

  def login_required
    unless current_user
      flash[:alert] = 'Log in!'
      redirect_to login_url, :status => 401
    end
  end
end

This is an imaginary example with products, but I think you'll get the idea.

Best regards

Tobias

Upvotes: 2

Related Questions