vkontakte api中的访问令牌

时间:2015-10-01 10:22:25

标签: ruby-on-rails rubygems omniauth vk

我通过deviseomniauth-vk获得授权的rails应用。这是omniauth_callbacks_controller.rb

中的代码
Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def vkontakte
binding.pry
@user = User.from_omniauth(request.env["omniauth.auth"])
token = request.env["omniauth.auth"]["credentials"]["token"]
current_user.token = @vk.token
current_user.vk_id = @vk.user_id
current_user.save

@vk = VkontakteApi::Client.new(current_user.token)

if @user.persisted?
  sign_in_and_redirect @user, :event => :authentication #this will throw if @user is not activated
  set_flash_message(:notice, :success, :kind => "vkontakte") if is_navigational_format?
else
  session["devise.vkontakte_data"] = request.env["omniauth.auth"]
  redirect_to new_user_registration_url

    if request.env["omniauth.auth"].info.email.blank?
      redirect_to "/users/auth/vkontakte?auth_type=rerequest&scope=email"
    end
  end
end

我想将当前经过身份验证的用户与其令牌绑定,但我不知道如何操作。 当我使用pry字符串current_user.token = @vk.token进行测试时,我遇到以下异常:

 NoMethodError: undefined method `token' for nil:NilClass
 from (pry):11:in `vkontakte'

1 个答案:

答案 0 :(得分:0)

你认为你没有在错误的地方定义@vk吗?检查此代码。

Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def vkontakte

@user = User.from_omniauth(request.env["omniauth.auth"])
token = request.env["omniauth.auth"]["credentials"]["token"]
@vk = VkontakteApi::Client.new(current_user.token)

current_user.token = @vk.token
current_user.vk_id = @vk.user_id
current_user.save

if @user.persisted?
  sign_in_and_redirect @user, :event => :authentication #this will throw if @user is not activated
  set_flash_message(:notice, :success, :kind => "vkontakte") if is_navigational_format?
else
  session["devise.vkontakte_data"] = request.env["omniauth.auth"]
  redirect_to new_user_registration_url

    if request.env["omniauth.auth"].info.email.blank?
      redirect_to "/users/auth/vkontakte?auth_type=rerequest&scope=email"
    end
  end
end