[英]Why signing in doesn't work?
当我尝试使用数据库中已经存在的实际用户信息登录时,系统将显示“无效的电子邮件/密码确认”错误,但这不是应该的。
这是为什么?
controllers / sessions_controller.rb
class SessionsController < ApplicationController
def new
end
def create
user = User.authenticate(params[:session][:email], params[:session][:password])
if user.nil?
flash.now[:error] = "Invalid email/password confirmation."
render :new
else
sign_in user
redirect_to user
end
end
def destroy
sign_out
redirect_to signin_path
end
end
app / views / sessions / new.html
<h1>Sign in</h1>
<% if flash[:error] %>
<p><%= flash[:error] %></p>
<% end %>
<%= simple_form_for(:session, url: sessions_path) do |f| %>
<%= f.input :email %>
<%= f.input :password%>
<%= f.button :submit %>
<% end %>
<p>New user? <%= link_to "Sign up now!", signup_path %></p>
app / helpers / sessions_helper.rb
module SessionsHelper
def sign_in(user)
session[:user_id] = user.id
self.current_user = user
end
def current_user=(user)
@current_user = user
end
def current_user
if session[:user_id]
@current_user ||= User.find(session[:user_id])
end
end
def signed_in?
!current_user.nil?
end
def sign_out
session[:user_id] = nil
self.current_user = nil
end
def current_user?(user)
user == current_user
end
def deny_access
redirect_to signin_path, notice: "Please sign in to access this page."
end
end
型号/user.rb
class User < ActiveRecord::Base
has_many :tasks
attr_accessor :password, :salt, :encrypted_password
EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :first_name, presence: true,
length: {maximum: 20}
validates :last_name, presence: true,
length: {maximum: 40}
validates :email, presence: true,
format: {with: EMAIL_REGEX},
uniqueness: {case_sensitive: false}
validates :password, presence: true,
confirmation: true,
length: {within: 6..40}
before_save :encrypt_password
def has_password?(submitted_password)
encrypted_password == encrypt(submitted_password)
end
def self.authenticate(email, submitted_password)
user = find_by_email(email)
return nil if user.nil?
return user if user.has_password?(submitted_password)
end
private
def encrypt_password
self.salt = Digest::SHA2.hexdigest("#{Time.now.utc}--#{password}")
self.encrypted_password = encrypt(password)
end
def encrypt(pass)
Digest::SHA2.hexdigest("#{self.salt}--#{pass}")
end
end
有人可以帮忙吗?
尝试从models / user.rb的以下行中删除:salt和:encrypted_password
attr_accessor :password, :salt, :encrypted_password
改成:
attr_accessor :password
这些值存储在数据库中,因此您可能会覆盖为这两个字段创建的活动记录中创建的方法,并且永远不会对其进行初始化。
从您的代码中,我看到的是一个confirmation :true
password
confirmation :true
,但是您的form
没有password_confirmation
字段。 尝试包括它
<%= f.input :password_confirmation %>
并将其作为attr_accessor
在User
模型中。
如果您不希望输入密码确认字段,则删除confirmation: true
对于验证中的密码,为confirmation: true
。
validates :password, presence: true, length: {within: 6..40}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.