My app authenticates users through Facebook with OmniAuth and it works fine but every time a user has to create a session and sign in, the request t开发者_C百科o Facebook takes up to a minute because it is calling a lot of information through the API. How do I refactor the code below to only call the graph objects (profile, likes, friends) for when it does || User.create_with_omniauth(auth,omniauth)
?
def create
auth = request.env["omniauth.auth"]
omniauth = request.env["omniauth.auth"]
user = User.find_by_provider_and_uid(auth["provider"], auth["uid"]) || User.create_with_omniauth(auth,omniauth)
session[:user_id] = user.id
session['fb_auth'] = request.env['omniauth.auth']
session['fb_access_token'] = omniauth['credentials']['token']
session['fb_error'] = nil
@graph = Koala::Facebook::GraphAPI.new(current_user.token)
current_user.profile = @graph.get_object("me")
current_user.likes = @graph.get_connections("me", "likes")
current_user.friends = @graph.get_connections("me", "friends")
current_user.save
redirect_to root_url
end
The easiest way to do this is by extracting out the last part of what you are doing into an asynchronous job. There doesn't seem to be any need for you to have all this information prior to creating the user, and any requests to external services that are not necessary for the immediate needs should be offloaded.
I am doing the same thing with Facebook currently and I am using Redis/Resque to update the users details after they are created/authenticated.
精彩评论