Reputation: 1821
I have a SessionsHelper
, which is where I define current_user
:
module SessionsHelper
def current_user
@current_user ||= user_from_remember_token
end
.
.
.
private
def user_from_remember_token
User.authenticate_with_salt(*remember_token)
end
def remember_token
cookies.signed[:remember_token] || [nil, nil]
end
end
I have a UsersController
that has a before_filter :authenticate
. This authenticate is in SessionsHelper
, and I am running into trouble here.
Rails handles all the cookies for me, but I built an API to use tokens for my mobile app, for which I have to send in params[:api_token]
upon login and set the current_user
.
I am thinking I have to do something like:
def current_user
@current_user ||=(user_from_remember_token || user_from_api_token)
end
but I am stuck because I am unsure if I can pass the params[:api_token]
in the helper.
Can anyone point me in the right direction?
EDIT: I also have,
class ApplicationController < ActionController::Base
protect_from_forgery
include SessionsHelper
...
end
which allows me to use before_filter :authenticate from UsersController and access this method in SessionsHelper
Upvotes: 0
Views: 2620
Reputation: 10898
If you're defining something in a helper which should be available to all views then you should put this into ApplicationHelper.
Also, I imagine you'll want to use these methods in your controllers at some point. Therefore you really should define them in ApplicationController and then flag them as helper methods with the helper_method function.
Here's an example:
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :authenticate
private
def authenticate
redirect_to root_url, :alert => 'You must log in to access this page' unless current_user
end
def current_user
@current_user ||= User.find_by_auth_token(cookies[:auth_token]) if cookies[:auth_token]
end
helper_method :current_user
end
There is then no need to pass params anywhere, since ApplicationController has direct access to it.
Upvotes: 0
Reputation: 5294
If you include SessionsHelper in UsersController, the methods defined in SessionsHelper should have access to params.
Upvotes: 2