Reputation: 43153
I've been googling this one and haven't turned up anything useful:
Assuming you use http basic auth in Rails is there a simple method to check if the user is authenticated? Ie. a way you can do something like this in a view:
- if http_basic_authenticated?
# show admin menu
Upvotes: 1
Views: 2055
Reputation: 852
From the oficial code you can extract snipets to use something like this in any controller inherited by ApplicationController:
class ApplicationController < BaseController
...
protected # Only inherited controllers can call authorized?
def authorized?
request.authorization.present? && (request.authorization.split(' ', 2).first == 'Basic')
end
...
end
Upvotes: 1
Reputation: 4515
Try this:
class ApplicationController < ..
before_filter :authenticate
def authenticate
authenticate_or_request_with_http_basic do |username, password|
@authenticated = username == "foo" && password == "bar"
end
end
def authenticated?
@authenticated
end
helper_method :authenticated?
end
You can now use authenticated
in your view.
Please write tests!
Upvotes: 4
Reputation: 6849
well, as I could know, there's no way to tell a view that the request is not authenticated, you could just tell the view that it is authenticated, but why? let's see the process of a request:
and in the 2nd step, the particular controller's method, which is before-filtered by the authentication method, that is, if you can go to the 3rd step -- the view, the request must be authenticated.
Upvotes: 0
Reputation: 4976
Use a session parameter accessible through a method defined in your ApplicationController
.
class ApplicationController < BaseController
...
def authorize
session[:authorized] = true
end
def http_basic_authenticated?
session[:authorized]
end
def end_session
session[:authorized] = nil
end
end
P.S. I'm not a security expert, so I can't comment on the suitability of using this in a production environment.
Upvotes: 3