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