1

I have a native Rails app that uses Devise for authentication (using the token_authenticatable module). With an existing account I can successfully perform API calls in my native iOS app using JSON once I get a token.

I'd like to add the capability to create a new account via the iOS app, without using a browser. Does Devise only allow account creation via HTML?

I've looked at this post Rails/Devise - Creating new users via json request

And tried various things via CURL, including:

$ curl -H "Content-Type: application/json" -d '{"email":"who@me.com","password":"mypass"}' -vX POST http://localhost:5000/users.json
...
* Connected to localhost (127.0.0.1) port 5000 (#0)
> POST /users.json HTTP/1.1
> User-Agent: curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8r zlib/1.2.5
> Host: localhost:5000
> Accept: */*
> Content-Type: application/json
> Content-Length: 44
> 
* upload completely sent off: 44 out of 44 bytes
< HTTP/1.1 406 Not Acceptable 
< Content-Type: application/json; charset=utf-8
< X-Ua-Compatible: IE=Edge
< Cache-Control: no-cache
< X-Request-Id: 338234ca2a6c378426ab67d7a080d44e
< X-Runtime: 0.006427
< Server: WEBrick/1.3.1 (Ruby/1.9.3/2012-12-25)
< Date: Sat, 09 Feb 2013 23:11:19 GMT
< Content-Length: 1
< Connection: Keep-Alive
< Set-Cookie: _MyRailsApp_session=BAh7BkkiD3Nlc3Npb25faWQGOgZFRkkiJTY1ZWIzMTdiYzc5ODdmMzNkOWI5MDM4NTMzYTQ0MWVkBjsAVA%3D%3D--c5871e8577987f36c614483b7a28b08fed55b7b8; path=/; HttpOnly
Community
  • 1
  • 1
joseph.hainline
  • 24,829
  • 18
  • 53
  • 70

1 Answers1

7

enable json for devise

config.navigational_formats = ["/", :json]

and add new file

class RegistrationsController < Devise::RegistrationsController

  def create

    @user = User.create(params[:user])
    if @user.save
      render :json => {:state => {:code => 0}, :data => @user }
    else
      render :json => {:state => {:code => 1, :messages => @user.errors.full_messages} }
    end

  end
end

in routes:

  devise_for :users, :controllers => {:registrations => "registrations"}

UPDATE

Also json should look:

{"user" : {"email":"who@me.com","password":"mypass"}}
NeverBe
  • 5,213
  • 2
  • 25
  • 39
  • 1
    To get this to work with HTML and JSON, I ended up with this solution: http://stackoverflow.com/questions/14447835/using-devise-to-sign-up-sign-in-and-sign-out-with-an-ios-app/14800237#14800237 – joseph.hainline Feb 10 '13 at 17:07
  • Thanks! I needed to add a private method user_params to the controller to whitelist :email and :password. I also had to disable CSRF protection as suggested [here](http://stackoverflow.com/a/10049965/313633). – Sjors Provoost Mar 06 '14 at 18:40