Rails身份验证不对错误的用户名或密码做出反应

时间:2013-12-03 18:28:58

标签: ruby-on-rails ruby

我正在构建一个需要登录的rails应用程序。我只设置了一个用户,每当我输入错误的用户或密码时,它什么也没做,只是追加“utf8 =✓& authenticity_token = TnSbSndhlfVfO6VLpeGLWgkCdrcXvMFD6gUVyCRax64%3D& email =& password =& commit =提交“到URL。我把它设置为说“无效的用户名或密码”,但它什么也没做。我需要它来验证并指导用户到下一页。它没有带我到正确的用户名和密码的下一页。它只是将该字符串附加到URL而不执行任何其他操作。如果我不够清楚,我是新来的,所以道歉。这是我的代码:

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
  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

appplication_controller.rb

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  helper_method :current_user
  before_filter :require_login


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

  def require_login
    unless current_user
      redirect_to log_in_path, :notice => "Please log in to access this page."
    end
  end
end

sessions_controller.rb

class SessionsController < ApplicationController
  skip_before_filter :require_login 

  def new
  end

  def create
    user = User.authenticate(params[:email], params[:password])
    if user
      session[:user_id] = user_id
      redirect_to stats_path, :notice => "Welcome"
    else 
      flash.now.alert = "Invalid email or password"
      render "new"
    end
  end

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

表单视图html

<h2 class="form-signin-heading">Log In</h2>
<form class="form-signin">
  <%= form_tag sessions_path do %>
      <% flash.each do |name, msg| %>
      <%= content_tag :div, msg, class: name %>
  <% end %>

  <%= text_field_tag :email, params[:email], :placeholder => "Email address", :class => "form-control" %><br />

  <%= password_field_tag :password, params[:password], :placeholder => "Password", :class => "form-control" %><br />


  <%= submit_tag "Submit", :class => "btn btn-lg btn-primary btn-block" %>
<% end %>
</form>

1 个答案:

答案 0 :(得分:1)

您似乎错过了视图中的ERB以显示Flash消息。例如:

<% flash.each do |name, msg| -%>
  <%= content_tag :div, msg, class: name %>
<% end -%>

有关详细信息,请参阅此rails guide