views:

333

answers:

2

Working from the railscast #160 base code I've set up a very simple site that allows me to log in, out and register an account. (Its almost identical except that I've removed the 'username' from the users migrate table and relevant views so only an email address is required)

I'm now trying to create a new log in action so that I can log in via JSON.

I'd like to be able to send a get request to http://app:3000/[email protected]&password=p4ssw0rd and have the rails app store the IP address the request came from (if the log in was correct) and send a relevant response (in JSON).

So far I have added a section to controllers/user_sessions_controller.rb so that it goes:

class UserSessionsController < ApplicationController
  #...
  def new_api
    respond_to do |format|
      format.json
    end
  end
end

To routes.rb:

map.apilogin "apilogin", :controller => "user_sessions", :action => "new_api"

But I'm at a loss as to what to put in views/user_sessions/new_api.json.rb! Can you help?

A: 

You can do something like this:

  def new_api
    respond_to do |format|
      format.json { render :json => user.slice(:name).to_json }
    end
  end

Or you can also generate the JSON in views/user_sessions/new_api.json.erb as you would write normal erb code. Not a good idea though:

{"name":"<%= @user.name %>"}
htanata
+2  A: 

You don't need to define a view at all - just return appropriate json from the controller.

def new_api
  @user_session = UserSession.new({:email => params[:email], :password => params[:password]})
  respond_to do |format|
    if @user_session.save
      format.json { render :json => {:success => true} }
    else
      format.json { render :json => {:success => false, :message => 'incorrect username or password'}, :status => :unauthorized }
    end
  end
end
Jonathan Julian
Thanks very much for your response - its very helpful, but I'm still at a loss as to how to test for correct login details!I have `params[:email]` and `params[:password]` set but AuthLogic doesn't pick those up automatically with `@user_session = UserSession.new` - do you know how I pass my (self-labeled) login credentials to the UserSession class?
JP
I've edited my answer with the creation of the UserSession model. Have a look at the Authlogic example app (http://github.com/binarylogic/authlogic_example/).
Jonathan Julian
That's fantastic! I'm trying to learn a lot about rails all in one go, I appreciate your help!
JP