#20
Apr 18, 2007

Restricting Access

In this second part of the series on administration, you will learn how to lock down the site to keep the public from accessing the administration features.
Download (18.6 MB, 4:32)
alternative download for iPod & Apple TV (8.3 MB, 4:32)
<!-- episodes/index.rhtml -->
<% if admin? %>
  <%= link_to 'New Episode', new_episode_path %>
<% end %>
# controllers/application.rb
helper_method :admin?

protected

def admin?
  false
end

def authorize
  unless admin?
    flash[:error] = "unauthorized access"
    redirect_to home_path
    false
  end
end

# episodes_controller.rb
before_filter :authorize, :except => :index

RSS Feed for Episode Comments 22 comments

1. Maledictus May 26, 2007 at 14:46

Doesn't the before_filter need to return true in the other case in order to normally proceed the request?


2. Ryan Bates May 26, 2007 at 23:48

Good question. It's not necessary because it continues as normal if it returns nil (which it will if the condition isn't met). The only time it stops is if it returns false.


3. Jack Wall May 30, 2007 at 15:03

flash[:error] does not work unless it is matched in the view layout, just in case anyone has issues getting the error message to show


4. Brian Jun 25, 2007 at 20:24

I follow the tutorial but i can login even i type wrong password.

How to fix?


5. Brian Jun 25, 2007 at 21:59

Hi i added the

<% admin? %>

<% end % >
it works great but when i combine it with the super simple authentication then the "must hidden" is not hidden.

any idea?

thanks


6. Brian Jun 25, 2007 at 22:10

@ryan bates

hi, i already fix my error.. sorry i didn't see the "==" in the password for the password is equals equals.

now its working and my next step is to connect ito database when i have users table.

Thanks =)


7. Piotr Mąsior Sep 24, 2007 at 13:43

If God would exists it will be you... very thanks for this screencast.

regards


8. jocelyn Dec 11, 2007 at 23:12

hi ryan,

i was just wondering if you have idea where i can get a dummy's guide for different levels of authorisation.

like some people will be able to CRUD,
some write only, some read only.

i'm very new to RoR sadly

thanks in advance!


9. cover Dec 25, 2007 at 02:04

@jocelyn

I'd add a string "level" column to each user. In that you could save for e.g "Writer", "Reader", "Editor", "Admin", and others you need. Then when you just need to add some controls as you do for the admin area. For e.g.
if current_user.writer?
  <show form to write>
end

and the writer? method would be like this:
def writer?
  current_user.level == "Writer"
end

Be aware of the level, if the user can choose her level pay attention she don't select the Admin level.


10. Jean-Marc Feb 29, 2008 at 14:53

I still have not resolved that question in my mind... if someones accesses a URL they should not, is redirecting the correct action?

I mean, it indicates your application will respond again and again to it.

On one project I did I simply determined to return a 404 (not found) when a protected resource was accessed. Indicating to the client they should not come back to that URI.

You got your thoughts on this dilemma?


11. Ryan Bates Mar 01, 2008 at 14:36

@Jean, I think returning 404 is an excellent solution, especially if you have a User model setup. You can then fetch resources through the user model and rails will handle the 404 automatically for you. For example, let's say a User has many Projects and you only want the user to have access to his own project. In the controller show action you can do this:

current_user.projects.find(params[:id])

This way the user can only fetch the project he owns. If he doesn't own it, he will receive a 404.


12. Ches Martin Apr 11, 2008 at 19:08

@Jean and Ryan,

Strictly speaking, you _really_ should be returning a 403 in those cases. There *is* as a resource there, it's just forbidden to that user (or role, or what have you).

The simple way to do this is Rails is:

head :forbidden

Nick Kallen has shown a nice pattern[1] for doing this type of thing consistently across your app, using Rails' rescue_action method.

In reality you might want to override rescue_action_in_public instead -- check the API docs to get more of an idea of how these methods work, like how to make sure you can still render a custom error file.

Thanks for all the great Railscasts, Ryan.

[1] https://blabs.pivotallabs.com/users/nick/blog/articles/272-access-control-permissions-in-rails


13. dazza Apr 22, 2008 at 07:52

great tips...

I added logged_in? to admin? to stop nil object errors...

 def admin?
    logged_in? && current_user.login == "admin"
  end


14. dazza Apr 22, 2008 at 18:26

woop...

I keep getting a major loop happening between the before_filter in my root controller...and the app controller authorize function, because if the filter chain is halted due to the admin not being logged in, the redirect is back to my root controller, which then calls the authorize function from the before filter...thus creating a loop...

so to remedy...this, from authorize
 I redirect to the /sessions/new which is fine...but now every route /url is redirected there ... even though I have an :except in my before filter

any ideas?

cheers

dion


15. dazza Apr 22, 2008 at 18:40

fixed...sorry for the spam

before_filter :my_authenticate , :except => [:index, :show]


16. bryan May 31, 2008 at 20:12

Hey Ryan,

As always, your webcasts are exceptional. They've helped me out tremendously in all the Rails applications I've been working on.

Quick question... have you ever done any role-based access control? If so, maybe this could be a topic for one of your future webcasts?!

--
Thanks!


17. Dale Jun 16, 2008 at 06:23

Will this still work for Rails 2.0 or is there a better way of doing it now?


18. Michael Mar 12, 2009 at 18:41

Hi Ryan,

Whats the bet way to handle roles now wuld you use http://www.writertopia.com/developers/authorization ?


19. Shaun May 14, 2009 at 19:43

Hi

I understand how to implement roles on the entire site, but how would you break this down even further, to an account level for example?

I have an application that hold accounts. Each account can have multiple users with multiple roles and each user could belong to multiple accounts, again, with differing roles. An editor of one account may be the owner of another, for example.

I'm struggling to see how I can check to see if the currently logged in user is in a particular role for the account that they are trying to access.

So far I have tried using a Privileges table that holds a user_id, role_id and account_id, but I can't find a way to find out if the current user within the current account belongs to a certain role.

Confused and probably making it worse for myself...

Thanks for the great post.


20. nruth Jul 22, 2009 at 09:05

With the default session store (cookies) the password will be stored in clear text on your pc.

It's worth looking at these links if you're concerned about how secure your login process is (you should be).

http://guides.rubyonrails.org/action_controller_overview.html#session

http://guides.rubyonrails.org/security.html


21. same Dec 16, 2009 at 16:19

hi
i'm new on ruby on rails
i have user and book model
user model contains login actions when i wrote this to the application controller
current_user.user_name == "Writer"
i'm having an error message
--undefined local variable or method `current_user' for #<BookController:0x77131b0>
why i'm having this message?
how to fix


22. Vasena Feb 19, 2010 at 03:00

i have user and book model


23. tiffany notes Jul 30, 2010 at 02:31

Great site. This could probably have the refactoring tag added t it.


24. cheap nike Aug 01, 2010 at 23:27

I added logged_in? to admin? to stop nil object errors too.


25. timberlandbootsuk Aug 02, 2010 at 02:08

we provide our buyers with an efficient and manageable procurement process covering every phase of the international supply chain and

streamlining trade channels. Also welcome wholesaling, feedback now!


27. cheap christian louboutin shoes Aug 06, 2010 at 02:38

This is a good website.we provide all kinds of christian louboutin women shoes and timberland boots.


28. children bikes Aug 09, 2010 at 18:27

Nice post! Although we are familiar with our culure, but we maybe don't really understand it. It need to study deeply.


29. paper napkins Aug 09, 2010 at 18:29

Excellent article that will provide the incentive and basis for my works.I wonder if I can mention the article as a bibliographic reference in my work. Thanks!


29. ear thermometer Aug 09, 2010 at 18:31

great topic. Thanks for your article, its been very helpful. Thanks for sharing your information.


30. infrared ear thermometer Aug 09, 2010 at 18:34

great topic. Thanks for your article, its been very helpful. Thanks for sharing your information.


31. medical thermometer Aug 09, 2010 at 18:35

Looks like a very interesting solution technology. Thanks for sharing .


32. solar water heater Aug 09, 2010 at 18:38

Great!This article is creative,there are a lot of new idea,it gives me inspiration.I think I will also inspired by you and think about more new ideas


33. free directory list Aug 11, 2010 at 22:16

David Heinemeier Hansson


34. Coach Outlet Aug 12, 2010 at 03:50

Here we have new style Coach Handbags.All the Coach purses are good quality and lower price.A fashion Coach Outlet is dreamed by the fashion females.Welcome to our store discountbagshop.com.I am sure you will find one for yourself.


35. p90 workout Aug 12, 2010 at 09:16

Yes, thats exactly what I wanted to hear! Great stuff here. The information and the detail were just perfect. I think that your perspective is deep, its just well thought out and really fantastic to see someone who knows how to put these thoughts down so well. Great job on this.


36. Air Jordan Spizike Aug 14, 2010 at 01:20

Looks like a very interesting solution technology. Thanks for sharing . Excellent article that will provide the incentive and basis for my works.


37. supra tk society Aug 18, 2010 at 18:48

good job,good article


38. jimmy choo wedges Aug 25, 2010 at 00:24

Thank you for sharing!


39. cool stuff Aug 25, 2010 at 01:57

very cool article ,thanks for sharing the article!like my cool stuff .very useful.


40. China Wholesale Directory Aug 25, 2010 at 02:01

excellent article , I added you to my Top China Wholesalers category.. thanks for sharing the article!


41. louis vuitton shoes Aug 26, 2010 at 21:10

Thanks for sharing your article. I really enjoyed it. I put a link to my site to here so other people can read it. My readers have about the same interets


42. snow boots Aug 31, 2010 at 02:01

On one project I did I simply determined to return a 404 (not found) when a protected resource was accessed.


43. Cheap Supra Shoes Sep 01, 2010 at 00:15

Thank you for sharing this perfect article.


44. GHD Hair Straighteners Sep 01, 2010 at 00:17

Good article. I would like promote it to more people.


45. GHD Australia Sep 01, 2010 at 00:18

I fond of this article very much. Thanks for sharing.


46. levis belts Sep 01, 2010 at 20:56

Intimately, the post is actually the best on this laudable topic. I harmonize with your conclusions and will eagerly look forward to your future updates. Saying thanks will not just be adequate, for the fantastic lucidity in your writing.

Add your comment:

(SKIP THIS ONE)

(required)

(not shown)


(use pastie or gist for code)

sponsored by:
if you want to help:
required:
Get Quicktime Player
Give Back to Open Source