Restful_authentication: Allowed? = NoMethodError (but logged_in? Works great ...?)
I don't understand why one method will work and the other will throw NoMethodError if they come from the same lib file.
# app/views/bunnies/show.html.erb
<% if logged_in? %>
<%= current_user.login %> |
<%= link_to 'Logout', logout_path %> |
<% if authorized? %>
<%= link_to 'Edit Details', edit_bunny_path(@broker) %> |
<% end %>
<%= link_to 'Back', bunnies_path %>
<% end %>
... throws a NoMethodError for authorized?
. If I comment that if block, the page works fine (c ).logged
_
?
# lib/authenticated_system.rb
def logged_in?
!!current_user
end
def authorized?
current_user.login == "admin"
end
# app/controllers/application.rb
class ApplicationController < ActionController::Base
include AuthenticatedSystem
end
What gives?
source to share
Correct, so I still don't understand why this doesn't work, but I found an alternative solution.
(1) Leave authenticated_system.rb as it is.
(2) Add a helper method for controllers /application.rb:
helper_method :is_admin?
def is_admin?
if logged_in? && current_user.login == "admin"
true
else
false
end
end
(3) authorized?
Use a helper method instead . If anyone wants to explain why the original code didn't work, I'm all ears!
(Thanks to this post )
source to share
I am assuming you are not logged in on error. NoMethod does not reference #authorized ?. This actually refers to the #login current_user method. If you are not logged in then current_user is zero, which results in NoMethod being called when current_user.login is called in #authorized ?.
Any assistant how authorized? which checks user status should include logged_in check? before working around this issue. Try it...
def authorized?
logged_in? and current_user.login == "admin"
end
This way you will drop the conditional if you are not logged in, and you are not trying to access the #login method unless you actually have an object available.
You can also explore some of the available role based authentication schemes that work with Restful_Authentication. If your access patterns are more complex than just admin validation, it will be easier to use one of these plugins.
By the way, further down in authenticated_system.rb you will find this code:
# Inclusion hook to make #current_user and #logged_in?
# available as ActionView helper methods.
def self.included(base)
base.send :helper_method, :current_user, :logged_in?, :authorized? if base.respond_to? :helper_method
end
This is what makes the methods in this module available as helper methods in the views. If you add an authenticated_system.rb method that returns the user's status (for example, something like #superuser?), You will need to add this method symbol to the call to base.send in this code. Again, if you find yourself writing a lot of access control code, learning one of the plugins will be fine.
source to share