app/models/user.rb
# A user's token expires after one hour from issuance, this will refresh token if expired
A user's token expires after one hour from issuance, this will refresh token if expired
A user ' s token expires after one hour from issuance this will refresh token if expired
def refresh_token_if_expired
    if token_expired?
      conn = Faraday.new(:url => 'https://www.reddit.com/api/v1/access_token')
      conn.basic_auth(ENV['REDDIT_KEY'], ENV['REDDIT_SECRET'])
      body = { 
        grant_type: "refresh_token",
        refresh_token: self.refresh_token,
        duration: 'permanent'
      }
      response = conn.post do |req|
          req.body = body
      end
      refresh_hash = JSON.parse(response.body)
      self.reddit_token = refresh_hash['access_token']
      self.refresh_duration = (Time.now + refresh_hash['expires_in']).to_i
      self.save
    end
  end
def refresh_token_if_expired if token_expired? conn = Faraday . new ( :url => 'https://www.reddit.com/api/v1/access_token' ) conn . basic_auth ( ENV [ 'REDDIT_KEY' ] , ENV [ 'REDDIT_SECRET' ] ) body = { grant_type : "refresh_token" , refresh_token : self . refresh_token , duration : 'permanent' } response = conn . post do | req | req . body = body end refresh_hash = JSON . parse ( response . body ) self . reddit_token = refresh_hash [ 'access_token' ] self . refresh_duration = ( Time . now + refresh_hash [ 'expires_in' ] ) . to_i self . save end end
A user's token expires after one hour from issuance, this will refresh token if expired
A user ' s token expires after one hour from issuance this will refresh token if expired
# upon successful authorization redirect we have to make a post request for access token # API requirements for body to obtain new access_token