2014-03-31 3 views
0

처음부터 R Bates 인증을 here에서 롤링하고 있습니다. 응용 프로그램 컨트롤러에서 authorize 메소드를 호출하고 싶습니다. 기본적으로 전체 앱을 잠그고 싶습니다. 다음은 앱 컨트롤러입니다 ...R Bates authentication with application controller

class ApplicationController < ActionController::Base 
    before_filter :authorize 
    # Prevent CSRF attacks by raising an exception. 
    # For APIs, you may want to use :null_session instead. 
    protect_from_forgery with: :exception 
    private 

    def current_user 
    @current_user ||= User.find(session[:user_id]) if session[:user_id] 
    end 
    helper_method :current_user 

    def authorize 
    redirect_to login_url, alert: "Not authorized" if current_user.nil? 
    end 
end 

하지만 아마도 내 URL 호출에 무한 루프가 발생합니다. 어떻게해야합니까?

세션 제어기

class SessionsController < ApplicationController 
    def new 
    end 

    def create 
    user = User.find_by_email(params[:email]) 
    if user && user.authenticate(params[:password]) 
     session[:user_id] = user.id 
     redirect_to root_url, notice: "Logged in!" 
    else 
     flash.now.alert = "Email or password is invalid" 
     render "new" 
    end 
    end 

    def destroy 
    session[:user_id] = nil 
    redirect_to root_url, notice: "Logged out!" 
    end 
end 

답변

0

당신은 SessionsController의 어떤 행동에 대한 before_filter (@vee 응답처럼) 건너 뛸 수 있습니다 :

skip_before_filter :authorize, only: [:new, :create] 

은 또한 당신이 어떤 경우에 리디렉션을 방지하기 authorize 방법을 수정할 수 있습니다

def authorize 
    return if skip_authorization?("#{controller_name}##{action_name}") 
    redirect_to login_url, alert: "Not authorized" if current_user.nil? 
end 

def skip_authorization?(location) 
    %w(sessions#new sessions#create).include?(location) 
end 
+0

가장 예쁜 것은 아니지만 작동합니다! – Lumbee

+0

네가 맞다. @Lumbee, 가장 예쁜 것은 아니다. 방금 skip_before_filter 접근법을 언급 한 답변도 편집했습니다. – markets

+0

@markets가 맞지만 건너 뛰기 필터가 작동하지 않습니다. – Lumbee

0

루프 때문에 redirect_to login_url...이다. ,

class SessionsController < ApplicationController 
    skip_before_filter :authorize, only: :login 

    def login 
    ... 
    end 
    ... 
end 

또는 모든 작업 authorize 필터를 건너 뛸 수있는 only 옵션없이 skip_before_filter :authenticate을 사용

당신은로 정의 login 작용을 컨트롤러에 authorize 필터를 생략한다.

+0

흠을, 아니 직장. 위의 세션 컨트롤러를 추가했습니다. 건너 뛰기 필터를 추가 한 후 로그인 페이지가 렌더링되지만 로그인 할 수없는 경우에도 동일한 로그인 페이지 – Lumbee

+0

@ Lumbee로 리디렉션됩니다. 사용자가 인증을 받습니까? – vee

+0

아니요 ... 여기에 콘솔에있는 내용이 있습니다. http://pastie.org/8983541 – Lumbee