我有一个使用omniauth-facebook和Devise的应用程序,它必须在注册页面上有一些必需的额外属性。它工作得很好,但我在将身份验证分解为两种情况/行为方面遇到了一些困难:
问题在于first_or_create方法。
我需要在注册页面上创建一条记录,其中包含我所需的参数,否则,在登录页面上,我只需要检查用户是否已注册并在必要时重定向到注册页面。 /强>
我清楚了吗?
型号:
class User < ActiveRecord::Base
def self.from_omniauth(auth)
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.email = auth.info.email
user.password = Devise.friendly_token[0,20]
user.name = auth.info.name
user.avatar = auth.info.picture
user.username = auth.info.name.parameterize.dasherize.first(10) + Digest::SHA2.hexdigest("#{Time.now.utc}").first(5)
user.skip_confirmation!
end
end
end
回调:
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def facebook
@user = User.from_omniauth(request.env["omniauth.auth"])
params = request.env["omniauth.params"]
@user.username = params["username"]
@user.newsletter = params["newsletter"]
@user.diet_id = params["diet_id"]
if @user.persisted?
sign_in_and_redirect @user, event: :authentication
set_flash_message(:notice, :success, kind: "Facebook") if is_navigational_format?
else
session["devise.facebook_data"] = request.env["omniauth.auth"]
redirect_to new_user_registration_url
end
end
def failure
redirect_to root_path
end
end
注册页面的相关代码:
= form_tag user_facebook_omniauth_authorize_path(newsletter: @user.newsletter, username: @user.username, diet_id: @user.diet_id) do
登录页面的相关代码:
= link_to "Sign in with Facebook", user_facebook_omniauth_authorize_path