0

so i have a little tricky combination here

Company has many Users
User belongs to Company

The User is managed for authentication with devise

class User < ActiveRecord::Base

  belongs_to :company

  devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable

You can login as a User and create Objects that all belong to the Company of that, not to the user, for example: Text. (company.texts)

now i created a simple API using the acts_as_api gem. for this i simply have to modify my text-controller, f.e. the show action.

class TextsController < ApplicationController

  load_and_authorize_resource

  def show
    #@text = Text.find(params[:id])
    respond_to do |format|
      format.html
      format.json { render_for_api :texts_all, :json => @text }
    end

this works quite fine on the website. the problem is the API. i don't want to authenticate when accessing the api via the user model. the company does have a attribute called :hashwhich i want to use for Auth in the API.

i don't have any idea how to achieve this using devise (or any other method). so by default devise wants a user to be logged in because of load_and_authorize_resource in my controller which is fine for the html response but not for the json response.

any ideas?

thanks for reading this. please leave a comment if something is unclear!

choise
  • 24,636
  • 19
  • 75
  • 131

2 Answers2

0

Conditionally apply auth filters based on accepted format headers:

# override in controllers related ot API
def authenticate_user!
  respond_to do |format|
    format.html { super } # just like before
    format.json { enforce_api_auth }
  end
end

Now API calls enforce their own auth.

clyfe
  • 23,695
  • 8
  • 85
  • 109
0

Just use Token Authenticatable and send the token with each request on your API.

Here is a tutorial for it.

raskhadafi
  • 1,342
  • 2
  • 14
  • 19