0

omniauth-google-oauth2을 사용하여 인증 된 경로 /me을 만들려고합니다. 지금까지 라이브러리를 로그인 및 로그 아웃하도록 설정 했으므로 정상적으로 작동합니다. 그러나 사용자가 로그인했을 때만 특정 경로에 액세스 할 수 있도록하고 싶습니다. this snippet을 찾았으며 설정에 맞게 약간의 변경 작업을 수행했습니다.Omniauth Google 인증 경로

application_controller.rb

before_filter :authenticate 
def authenticate 
    redirect_to :login unless User.from_omniauth(env["omniauth.auth"]) 
end 

user.rb

def self.from_omniauth(auth) 
    where(provider: auth.provider, uid: auth.uid).first_or_initialize.tap do |user| 
     user.provider = auth.provider 
     user.uid = auth.uid 
     user.name = auth.info.name 
     user.first_name = auth.info.first_name 
     user.last_name = auth.info.last_name 
     user.email = auth.info.email 
     user.picture = auth.info.image 
     user.oauth_token = auth.credentials.token 
     user.oauth_expires_at = Time.at(auth.credentials.expires_at) 
     user.save! 
    end 

그게 내가 내 SessionsController에 사용되는 인증 해시이기 때문에 내가 env["omniauth"]을 사용했다. 내가 localhost:3000에 갈 때마다

그러나 지금, 나는 다음과 같은 오류 얻을 : env["omniauth.auth"]application_controller.rb에서 액세스 할 수 없기 때문에이

undefined method `provider' for nil:NilClass 

내가 겠지를 어떻게됩니까? 그렇다면 인증 해시에 올바르게 액세스하려면 어떻게해야합니까?

+1

'from_omniauth' 클래스 메쏘드는'user.rb' 파일 내에서 어떻게 생겼습니까? –

+0

@JustinLicata가 방금 원래 게시물을 업데이트했습니다. – Carpetfizz

+1

"localhost : 3000"을 방문하면'env [ "omniauth.auth"]'는'nil'을 반환합니다. 내가 믿는 이유는이 env 변수가 사회적 로그인 후에 콜백 요청에서만 설정된다는 것입니다. 다른 모든 요청의 경우이 값은 'nil'입니다. –

답변

1

이 시도 :

application_controller.rb이 먼저 이미 로그인 사용자 (세션) 가져 오기 위해 노력할 것입니다

before_filter :authenticate 

def authenticate 
    redirect_to :login unless user_signed_in? 
end 

def user_signed_in? 
    !!current_user 
end 

def current_user 
    @current_user ||= begin 
    User.find(session[:current_user_id]) || fetch_user_from_omniauth 
    end 
end 

def fetch_user_from_omniauth 
    user = User.from_omniauth(env['omniauth.auth']) 
    session[:current_user_id] = user.id 
    user 
end 

. 발견되지 않으면 omniauth에서 사용자를 생성 한 다음 세션에서 ID를 설정하려고 시도하므로 다음 요청의 경우 현재 사용자를 찾기 위해 env에 필요하지 않습니다.

+0

감사합니다. 귀하의 답변을 이해하려고합니다. 'social_controller.rb'에서 인증을 건너 뛰는 이유는 무엇입니까? 또한이 컨트롤러의 역할은 무엇입니까? 이것은 세션을 생성하는 것과 동일합니까? – Carpetfizz

+0

그건 그렇고, 내 Sessions.rb는 인증 콜백이 – Carpetfizz

+0

인 곳입니다. 지금 확인하십시오. –