Reputation: 1150
I'm trying to create a login system in Rails 3 where I can access the logged in user not only from the views but also from the controller/model level. The reason is that I want to adapt functionality according to a privilege system where logged in users may execute different functions than those that are not logged in.
Up to this point, I tried to implement the login system from railstutorial.com, chapter 9.
When I use the login system only from the view, it works. However, if I try to use the system via a controller, I get the error undefined method 'cookie_jar' for nil:NilClass
.
Thank you for any help or best practices you can provide for creating an authentication system where the logged in user can be identified from a controller.
Upvotes: 1
Views: 388
Reputation: 3766
If everything done according to the tutorial you should be able to get current_user
from both controllers and views. There's also another tutorial on authentication on asciicasts.com by Ryan Bates. You may want to explore it if you are just starting Rails, but for real-life applications it's highly recommended to use Devise or AuthLogic, which are thoroughly tested and constantly evolving.
Upvotes: 0
Reputation: 1405
An extremely simple way is to do it as mentioned in railscast episode : http://railscasts.com/episodes/20-restricting-access
As mentioned in the screen cast, you can use the plugin acts as authenticated
(http://www.railsrocket.com/acts_as_authenticated-plugin) for all your user model needs.
Upvotes: 0
Reputation: 3224
The best advice here is probably "don't". If you want an authentication system, use something like Devise - which has had a lot of time and effort spent making sure that evildoers can't get in
If you want different users to execute different functions, this is access control, and for that you probably want something like cancan or ACL
And you want access to the logged in user from the model level? Again, the best practice is "don't". The model should have no interest in the currently logged in user - that is a matter for the controller.
(That said, rules are sometimes made to be broken - if you are doing an audit trail and need to store information about the user who made a change, for example, passing the currently logged in user to the model may be the best answer ....)
And finally, if you really, really want to do it all from scratch, take a look at this railscast
Upvotes: 4