Facebook token expiration and renewal, with Koala and omniauth-facebook

前端 未结 3 1904
时光取名叫无心
时光取名叫无心 2020-12-07 16:55

I\'m writing a Rails app that uses omniauth-facebook to authenticate the user against FB (and to get a FB OAuth access token for the user). The app then uses Koala to make

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-07 17:44

    What I have is a before_filter that is triggered on every page that requires an active Facebook session. Something like this should work:

      before_filter :reconnect_with_facebook
      def reconnect_with_facebook
        if current_account && current_account.token_expired?(session[:fb]["expires"])
    
        # re-request a token from facebook. Assume that we got a new token so
        # update it anyhow...
        session[:return_to] = request.env["REQUEST_URI"] unless request.env["REQUEST_URI"] == facebook_request_path
        redirect_to(with_canvas(facebook_request_path)) and return false
      end
    end
    

    The token_expired? method looks like this:

    def token_expired?(new_time = nil)
      expiry = (new_time.nil? ? token_expires_at : Time.at(new_time))
      return true if expiry < Time.now ## expired token, so we should quickly return
      token_expires_at = expiry
      save if changed?
      false # token not expired. :D
    end
    

提交回复
热议问题