简体   繁体   中英

Access token in vkontakte api

I have rails app with authorization via devise and omniauth-vk . This is code in 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

I want to tie current authenticated user with his token but I don't know how. When I test with pry string current_user.token = @vk.token I am having the following exception:

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

Don't you think you have define @vk in wrong place ?? check this code.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM