2012-06-30 39 views
5

Tôi đã quản lý thiết lập xác thực json. Tôi đã triển khai mã sau:Xác thực lỗi xác thực thông qua json gửi lại html thay vì json

class Users:: SessionsController < Devise::SessionsController 
    def create 
    respond_to do |format| 
     format.html { super } 
     format.json { 
     warden.authenticate!(:scope => resource_name, :recall => "#{controller_path}#failure") 
     render :json => {:success => true} 
     } 
    end 
    end 

    def destroy 
    respond_to do |format| 
     format.html {super} 
     format.json { 
     Devise.sign_out_all_scopes ? sign_out : sign_out(resource_name) 
     render :json => {} 
     } 
    end 
    end 

    def failure 
    render :json => {:success => false, :errors => ["Login Failed"]} 
    end 
end 

Điều này làm việc tốt, nhưng khi xác thực thất bại, lỗi này không trả lại lỗi json. Tôi có một thất bại tùy chỉnh cho ra. Nếu tôi xóa redirect_url hoặc xóa hoàn toàn lỗi khách hàng, thì xác thực sẽ trả về một json với thông báo lỗi. thất bại tùy chỉnh của tôi là như sau:

class CustomFailure < Devise::FailureApp 
    def redirect_url 
    #return super unless [:worker, :employer, :user].include?(scope) #make it specific to a scope 
    '/' 
    end 

    # You need to override respond to eliminate recall 
    def respond 
    if http_auth? 
     http_auth 
    else 
    redirect 
    end 
end 

cuối

Anyway để tiếp tục chuyển hướng nếu nó yêu cầu html, và trả về một json với một msg thất bại nếu nó yêu cầu json?

Cảm ơn!

Trả lời

5

Bạn phải yêu cầu người quản lý sử dụng lỗi tùy chỉnh đó.

def failure 
    respond_to do |format| 
    format.html {super} 
    format.json do 
     warden.custom_failure! 
     render :json => {:success => false, :errors => ["Login Failed"]} 
    end 
    end 
end 
Các vấn đề liên quan