Repository URL to install this package:
|
Version:
1.0.1 ▾
|
# frozen_string_literal: true
require 'googleauth'
require 'googleauth/stores/file_token_store'
module Faculty
module Google
module Auth
# Class for handing OAuth logins in local development instances
class OAuth
def initialize(path: Dir.pwd, scopes: [], user_id: 'default')
@path = path
@scopes = scopes
@user_id = user_id
end
def authorization
credentials = authorizer.get_credentials(@user_id)
raise 'No Credentials. Check `rake` for a command to setup OAuth2.' if credentials.nil? && !$stdout.isatty
credentials = fetch_credentials if credentials.nil?
credentials
end
BASE_URL = 'http://localhost'
private
def authorizer
@authorizer ||= begin
FileUtils.mkdir_p(File.dirname(credentials_path))
client_id = ::Google::Auth::ClientId.from_file(client_secrets_path)
token_store = ::Google::Auth::Stores::FileTokenStore.new(file: credentials_path)
::Google::Auth::UserAuthorizer.new(client_id, @scopes, token_store)
end
end
def client_secrets_path
"#{@path}/google-client-secrets.json"
end
def credentials_path
"#{@path}/google-oauth.yaml"
end
def fetch_credentials
url = authorizer.get_authorization_url(base_url: BASE_URL)
puts "Open this URL in a browser and enter the auth code back here:\n\n#{url}\n\nCode:"
code = $stdin.gets.chomp
authorizer.get_and_store_credentials_from_code(user_id: @user_id, code:, base_url: BASE_URL)
end
end
end
end
end