2013-11-04 4 views
0

Ruby on Rails의 새로운 기능에 대해 사과합니다. 간단한 문제이지만 몇 주 동안 해결 방법을 찾은 후에 사과하는 것이 더 쉽습니다.레일 4 활성 레코드 로그인 세션 실패

저는 active_record 기반 인증을 받고자하는 Rails 4 사이트에서 일하고 있습니다. 이 예제 다음에 가입과 로그인 프로세스를 모델로 만들었습니다. http://railscasts.com/episodes/250-authentication-from-scratch?view=asciicast

이 예제는 세션 저장에 쿠키를 사용하면 작동하지만 백그라운드에서 active_record로 전환하면 잘 동작합니다. 로그인을 시도하면 플래시 메시지가없는 메인 페이지로 돌아가고 current_user에는 아무 것도 표시되지 않습니다 (리디렉션 대신 로그인 페이지에서 새로운 부분을 렌더링하고 사용자 정보를 찾을 수있는 테스트를 수행 했음에도 불구하고, 하지만 멀리 이동하면 세션이 끊어집니다.)

쿠키 세션은 파일 크기 제한으로 인해 작동하지 않지만 다른 옵션을 사용할 수 있습니다. active_records를 가리 키기 위해 이니셜 라이저를 설정했고, 그것을 gemfile에 추가했지만, 어디에서 깨지는 지 알 수는 없습니다. db에 추가 할 삽입 단계가 없습니다.

또 다른 단서는 내 protect_from_forgery 줄이 "CSRF 토큰 신뢰성을 확인할 수 없습니다."라고하지만 다른 줄을 주석 처리하면 세션이 여전히 실패합니다.

매우 간단한 수정이라면 사과드립니다.하지만 제가 언급 한 것처럼 지금 당분간은 해결책을 찾고 있습니다.

다음은 실행중인 주 코드입니다. 더 이상 코드를보고 싶다면 알려주세요.

application_controller.rb

class ApplicationController < ActionController::Base 
    protect_from_forgery with: :null_session 
    helper_method :current_user 

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

session_controller.rb

class SessionsController < ApplicationController 
    def new 
    end 

    def create 
    user = User.authenticate(params[:email], params[:password]) 
    if user 
     session[:user_id] = user.id 
     redirect_to root_url, :notice => "Logged in! #{User.find(session[:user_id]).email}" 
    else 
     flash.now.alert = "Invalid email or password" 
     render "new" 
    end 
    end 

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

보기/세션/new.html.erb

<h1>Log in</h1> 

<%= form_tag sessions_path do %> 
<p> 
    <%= label_tag :email %><br /> 
    <%= text_field_tag :email, params[:email] %> 
</p> 

<p> 
    <%= label_tag :password %><br /> 
    <%= password_field_tag :password %> 
    <%= hidden_field_tag('authenticity_token', form_authenticity_token.to_s)%> 

</p> 

<p class="button"><%= submit_tag "Log in" %></p> 
<% end %> 

모델/user.rb

class User < ActiveRecord::Base 

attr_accessible :email, :password, :password_confirmation 

attr_accessor :password 
before_save :encrypt_password 

validates_confirmation_of :password 
validates_presence_of :password, :on => :create 
validates_presence_of :email, :on => :create, :message => "Can't be blank" 
validates_uniqueness_of :email 

    def self.authenticate(email, password) 
user = find_by_email(email) 
if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt) 
    user 
else 
    nil 
end 
    end 

    def encrypt_password 
if password.present? 
    self.password_salt = BCrypt::Engine.generate_salt 
    self.password_hash = BCrypt::Engine.hash_secret(password, password_salt) 
end 
    end 
end 

답변

1

당연히 나는 게시 한 다음날 수정 프로그램을 비틀 거려야 할 것이지만 다른 사람들이 같은 문제가있는 경우에 대비하여 찾은 것을 공유하고 싶었습니다. 내가 공유 한 예제에서 전체 프로젝트를 다시 만들기 시작했다. 이 예제를 실행했을 때 데이터가없는 세션을 만들려고한다는 Null 예외가 발생하기 시작했습니다. I합니다 (active_record의 GitHub의 사이트를 살펴 가져다가 "문제"나는 얻고 있었다 널 심판을 고정하고 내 주요 사이트에 그것을 연결 때 문제를 해결 한 것으로 나타납니다 섹션 https://github.com/rails/activerecord-session_store/issues/6

이 링크를 발견 또는 적어도 내가 페이지를 변경할 때 나를 로그 아웃하지 않는다). 그것이 실제로 그것을 고쳤던 방법을 모르고있다. 그러나 나는 내가 얻을 수있는 것을 가져갈 것이다.

초기화/session_store.rb

ActiveRecord::SessionStore::Session.attr_accessible :data, :session_id 
관련 문제