I am developing an API using Rails 3. I have done my own authentication logic and I use an before_filter called authenticate_user! to check if a user is logged in.
In this function I check if there is a current user session active. If there is I do nothing, but if there are no active session I want to stop the rest of the functions/resources from being used and then return an error to the calling app that the user is not logged in.
My questions are:
How can I "stop" the request in my authentication function if there is not current session. I do not want to redirect the user, only display an erro开发者_StackOverflow中文版r message.
How can I display an error message that will be sent back to the calling app? It would be best if I could "answer" in JSON (and XML if possible).
This is my current code.
def authenticate_user!
unless current_user
if params[:token]
user = User.authenticate_token(params[:token])
if user
session[:user_id] = user.id
else
SEND BACK SOMETHING HERE AND STOP THE PROCESS?
end
end
end
end
Thankful for all input!
I also wanted to know the answer to this question.
In my case I did the following in the above else clause:
else
redirect_to :root, :status => 401
return false
end
This will return a 401 not authorized and redirect to the root and stop the filter
精彩评论