title: Before_filter authentication function
body: <p>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.</p>
  
  <p>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.</p>
  
  <p>My questions are:</p>
  
  <ol>
  <li><p>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 error message.</p></li>
  <li><p>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).</p></li>
  </ol>
  
  <p>This is my current code.</p>
  
  <pre><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
  </code></pre>
  
  <p>Thankful for all input!</p>