问题
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
回答1:
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
回答2:
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.
来源:https://stackoverflow.com/questions/38696478/use-googleauthstoresfiletokenstore-with-database