← Back to Upcase

Using Tokens with Username/Password Combo


(Slav Kurilyak) #1

Hi Guys,

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
  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 CreateDevices < ActiveRecord::Migration
  def change
    create_table :devices do |t|
      t.timestamps null: false
      t.string :device_token
    end
  end
end

with the following models:

class User < ActiveRecord::Base
  has_one :device
end

and

class Device < ActiveRecord::Base
  belongs_to :user
end

I am on the right track? Please advise.


(Austin ) #2

Hey, I think so. I rolled my own in a multi-tenant Ember app i wrote for a coding exercise a couple months ago that you may look at. I don’t use device but the main logic is in application_controller, and then User has many Tokens (I’m not certain but Token may have caused some problems i couldn’t figure out in some of the queries).

By doing has_one, it is limiting to one client. Depending on your business logic, it may make sense to do has_many so they can have multiple end points. .