iosruby-on-rails

Using Tokens with Username/Password Combo


I'm trying to figure out a way to integrate both tokens and username/password combo into a rails API. The front-end of the API is an iOS app which requires username/password combination to keep track of user's profiles.

Following thoughtbot/ios-on-rails github repo along with thoughtbot's iOS on Rails book, I am able to create a user's model by using device tokens to handle authentication.

However, as noted by the thoughtbot team:

Our app doesn’t require username/password login, instead we will create a user object on the first run of the app and then consistently sign our requests as this user. This behavior is useful for apps that don’t require login, or have some sort of guest mode.

Here is the migration file for such token based authentication API:

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.timestamps null: false
      t.string :device_token
    end

    add_index :users, :device_token
  end
end

In my case, I'm building an iOS app that does require username/password login on the client and I need to create the database schema in rails to handle this. Here is how I'm thinking of building this:

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.timestamps null: false
      t.string :first_name, null: false
      t.string :last_name, null: false
    end
  end
end

and

class CreateTokens < ActiveRecord::Migration
  def change
    create_table :tokens do |t|
      t.timestamps null: false
      t.string :device_token
    end
  end
end

with the following models:

class User < ActiveRecord::Base
  has_many :tokens
end

and

class Token < ActiveRecord::Base
  belongs_to :user
end

I am on the right track? Please advise.


Solution

  • that looks about right, may want to use a table name called authentication_tokens as the following post suggests

    http://www.brianauton.com/posts/token-authentication-devise.html