Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Google::Auth::Stores::FileTokenStore with database

I'm trying to implement a 3 legged authentication in my app to the Google API, to be able to access registered users' Google Calendars.

In the quickstart Ruby guide, this command comes up that as far as I understand should point to the user's tokens:

token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)

It expects the tokens stored in a file (or Redis), but (of course) I store each user's tokens in my database (Postgres).

Have I understand the purpose of the command wrongly or otherwise - how do I use it with a database store?

Official documentation

like image 615
Fellow Stranger Avatar asked Aug 01 '16 10:08

Fellow Stranger


2 Answers

I implemented it myself based on @Rafe's answer. Just wanted to share in case someone wants to copy the ActiveRecord / Database store implementation:

module Google
  module Auth
    module Stores
      class DatabaseTokenStore < Google::Auth::TokenStore
        def load(id)
          user = User.find(id)
          {
            "client_id": ENV['google_client_id'],
            "access_token": user.token,
            "refresh_token": user.refresh_token,
            "scope": ENV['google_scopes'],
            "expiration_time_millis": user.token_expires_at
          }.to_json
        end
        def store(id, token)
          user = User.find(id)
          hsh = JSON.parse(token)
          user.update(
            token: hsh["access_token"],
            token_expires_at: hsh["expiration_time_millis"] / 1000
          )
        end
      end
    end
  end
end
like image 60
jshawl Avatar answered Nov 14 '22 13:11

jshawl


Implement it yourself, according to the the readme:

Custom storage implementations can also be used. See token_store.rb for additional details.

It shouldn't be too hard to implement the load(id), store(id, token) and delete(id) with ActiveRecord (or another ORM) by the looks of the mentioned files.

like image 30
Rafe Avatar answered Nov 14 '22 15:11

Rafe