2014-10-07 91 views
2

我目前正在使用來自Throughbot的Clearance進行身份驗證。我需要爲我的產品添加一個API,並且似乎找不到有關在API中使用清除的文檔。是否有某個標題可以設置,Clearance將自動檢查,如果沒有,我可以使用什麼?我想我可以使用this使用清除API

回答

3

爲了解決這個問題,我最終覆蓋了ApplicationControllerUser模型上的authenticate方法。它看起來是這樣的:

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更改爲使用新字段。