使用Clearance with API

时间:2014-10-07 20:37:23

标签: ruby-on-rails clearance

我目前正在使用来自Throughbot的Clearance进行身份验证。我需要在我的产品中添加API,而且似乎无法找到有关在API中使用Clearance的文档。是否有一个我可以设置的标题,清除将自动检查,如果不能,我可以使用什么?我想我可以使用this

1 个答案:

答案 0 :(得分:2)

为了解决这个问题,我最终覆盖了authenticateApplicationController模型上的User方法。它看起来像这样:

class ApplicationController < ActionController::Base
  include Clearance::Controller
  include Clearance::Authentication

  def authenticate(params)
    if request.headers['AUTH-TOKEN']
      return nil unless user = User.where(remember_token: request.headers['AUTH-TOKEN']).first
      sign_in user
    else
      User.authenticate(params[:session][:email], params[:session][:password])
    end
  end
  #rest of class omitted for bevity
end

然后我将SessionsController子类化为覆盖create方法,如下所示:

class SessionsController < Clearance::SessionsController
  def create
    @user = authenticate(params)

    sign_in(@user) do |status|
      respond_to do |format|
        if status.success?
          format.html { redirect_back_or url_after_create }
          format.json { render json: @user, status: :ok }
        else
          format.html do
            flash.now.notice = status.failure_message
            render template: 'sessions/new', status: :unauthorized
          end
          format.json { render json: [errors: status.failure_message], status: :unauthorized }
        end
      end
    end
  end
  #rest of class omitted for bevity
end

然后,您要测试或使用的所有操作都是将请求AUTH-TOKEN标头设置为users记忆标记,并且您已完成设置。我选择使用记忆令牌,因为每当用户注销时它都会更新。您可能不希望这种情况发生,而是可以在模型上生成auth_token字段,并更改where以使用新字段。