4

I would like to know how to use rails as backend for my iOS app.

All I need is a User with email and password to authenticate using devise. I already have a User created with devise and rails 4.

I did find this post http://jessewolgamott.com/blog/2012/01/19/the-one-with-a-json-api-login-using-devise/ explaining what I need, but some things are still missing.

  1. When I try to do a POST via my iOS app, I get the message "Can't verify CSRF token authenticity". How do I solve that without skipping the filter verify_authenticity_token ?

  2. How would the request code for the iOS look like? Right now I'm doing a POST to http://localhost:3000/api/users/sign_in.json and setting the HTTPBody = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:0 error:&jsonError], but the rails server is receiving only a string as key with the entire json dictionary, not an actual json dictionary.

    params = {"{\"user\":{\"email\":\"qwe\",\"password\":\"123\"}}"=>nil, "action"=>"create", "controller"=>"api/sessions", "format"=>"json"}

  3. How would I do an https request instead of http, so I can hide the password and email fields in case someone else tries to watch my internet traffic?

Thank you very much.

Community
  • 1
  • 1
Rodrigo Ruiz
  • 4,248
  • 6
  • 43
  • 75
  • Regarding rails part I believe, you're looking for answer that has already been posted here: http://stackoverflow.com/questions/5669322/turn-off-csrf-token-in-rails-3 – Lukasz Muzyka Aug 25 '14 at 02:24
  • Not directly an answer to your question but just in case it's of use, perhaps you might look at http://helios.io --you can integrate it easily into a Rails app and get most of the backend that you need "for free", including synchronisation with CoreData on the iOS side. – Stefan Magnuson Sep 04 '14 at 06:04

1 Answers1

0

To use Rails Applications Mobile and Android and IOS, necessarily you have to use JSONP: example:

JS sample:

$.ajax({
  url: '/api_mobile',
  jsonp: "callback",
  dataType: "jsonp",
  cache: true,
  data: {method: 'login', other_data ...},
  success: function(res) {
    // response object
    console.log(res)
  },
  error: function(request, status, error) {
    alert("Error server: " + request.status);
  }
});

RAILS 4:

protect_from_forgery with: :exception, only: :api_mobile

# route /api_mobile
def api_mobile  
   json = {error: 'Not found Method'}
   case params[:method]
      when: 'login'
         if User.login(params[:username], params[:password])
            json = {notice: 'Login success'}
         else
            json = {error: 'Error Username or Password'}
         end
   end
   render json: json, :callback => params[:callback]
end

All functions must be personalized and parameterized

froilanq
  • 934
  • 7
  • 8