我们是rails的新手,并希望在我们的主页上使用Javascript SDK“Connect with Facebook”按钮。在我们的应用程序中使用此按钮,我们希望允许用户通过Facebook注册我们的网站,并能够使用他们的Facebook个人资料图片作为我们的网络应用程序的个人资料图片。
使用我们的Rails 3应用程序实现此Facebook连接的最佳方式是什么?
devise_for :users
resources :authentications
resources :users do
member do
get :following, :followers
end
end
resources :sessions, :only => [:new, :create, :destroy]
resources :microposts, :only => [:create, :destroy]
resources :relationships, :only => [:create, :destroy]
match '/signup', :to => 'users#new'
match '/signin', :to => 'sessions#new'
match '/signout', :to => 'sessions#destroy'
match '/contact', :to => 'pages#contact'
match '/home', :to => 'pages#home'
match '/help', :to => 'pages#help'
match '/feedback', :to => 'pages#feedback'
match '/privacy', :to => 'pages#privacy'
match '/terms', :to => 'pages#terms'
match '/', :to => 'pages#home'
resources :microposts
resources :users
resources :sessions, :only => [:new, :create, :destroy]
root :to => 'pages#home'
match "/auth/twitter/callback" => "sessions#omnicreate"
match "/auth/facebook/callback" => "sessions#omnicreate"
end
SessionsController
class SessionsController < ApplicationController
def new
@title = "Sign in"
end
def create
user = User.authenticate(params[:session][:email],
params[:session][:password])
if user.nil?
flash.now[:error] = "Invalid email/password combination."
@title = "Sign in"
render 'new'
else
sign_in user
redirect_back_or user
end
end
def destroy
sign_out
redirect_to root_path
end
end
答案 0 :(得分:2)
omniauth gem是通过第三方服务设置身份验证的好方法。他们有Facebook策略。我已经习惯了它,设置起来很简单。只需将api密钥粘贴在rails初始化程序中即可。
答案 1 :(得分:1)
看起来你需要做几件事:
更改路线文件中的以下行:
root :to => 'pages#home'
match "/auth/twitter/callback" => "sessions#omnicreate"
match "/auth/facebook/callback" => "sessions#omnicreate"
对此:
match "/auth/:provider/callback" => "sessions#omnicreate"
root :to => 'pages#home' # this one should always be last
Twitter和Facbook都采用相同的方法,因此您需要稍后获取:provider
参数,以确定其Twitter或Facebook是否发送了它们。
接下来,您需要在SessionsController
中创建一个接收回调的方法,如下所示:
def omnicreate
data = request.env['omniauth.auth'] # here is all the user data
if params[:provider] == 'twitter'
#parse twitter data
elsif params[:provider] == 'facebook'
#parse fb data
else
# something is broken
redirect_to '/404.html'
end
user = User.create! #use data you parsed to create a user
redirect_to some_path, :notice => 'awwww yeah'
end
祝你好运!