我正在使用omniauth-twitter,我已经完成了所有设置:
用户.rb:
def self.create_with_omniauth(auth)
create! do |user|
user.provider = auth["provider"]
user.uid = auth["uid"]
user.name = auth["info"]["name"]
user.email = auth["info"]["email"]
# To pass password validation
user.password = user.password_confirmation = SecureRandom.urlsafe_base64(n=6)
end
end
session_controller.rb:
def create
user = User.find_by_email(params[:session][:email].downcase)
if user && user.authenticate(params[:session][:password])
sign_in user
redirect_back_or user
else
flash.now[:error] = 'Invalid email/password combination'
render 'new'
end
end
问题是您无法从 Twitter 检索电子邮件地址,因此由于我的验证规则,登录失败:
用户.rb:
before_save { |user| user.email = email.downcase }
before_save :create_remember_token
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true,
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
validates :password, presence: true, length: { minimum: 6 }
validates :password_confirmation, presence: true
我想让用户输入电子邮件,这样他们就可以登录而不会验证失败(仅限 Twitter,因为我也有 Facebook 和 Google 登录)。
有人有什么建议吗?
编辑:
users_controller.rb:
def create
@user = User.new(params[:user])
if @user.save
sign_in @user
flash[:success] = "Welcome to the Sample App!"
redirect_to @user
else
if params[:form_name] == "enter_email"
render 'enter_email'
else
render 'new'
end
end
end
用户/enter_email.html.erb:
<% provide(:title, 'Enter your email') %>
<h1>Enter your email</h1>
<div class="row">
<div class="span6 offset3">
<%= form_for(@user) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= f.label :email %>
<%= f.text_field :email %>
<%= f.hidden_field :provider, value: params[:oprovider] %>
<%= f.hidden_field :provider, value: params[:oprovider] %>
<%= f.hidden_field :uid, value: params[:ouid] %>
<%= f.hidden_field :name, value: params[:oname] %>
<%= f.hidden_field :password , value: params[:opassword] %>
<%= f.hidden_field :password_confirmation, value: params[:opassword_confirmation] %>
<% # To know to which form to redirect in case of validation error %>
<%= hidden_field_tag 'form_name', 'enter_email' %>
<%= f.submit "Create my account", class: "btn btn-large btn-primary" %>
<% end %>
</div>
</div>